Home > Article > Backend Development > Image upload class_PHP tutorial
Image upload class
Solution
class upphoto{
public $previewsize=0.125; //Preview image ratio
public $preview=1; //Whether to generate a preview, 1 if yes, 0 if not
public $datetime; //random number
public $ph_name; //Upload image file name
public $ph_tmp_name; //Temporary image file name
public $ph_path="uploadimg/"; //Upload file storage path
public $ph_type; //Picture type
public $ph_size; //Picture size
public $imgsize; //Upload image size, used to determine display ratio
public $al_ph_type=array('image/jpg','image/jpeg','image/png','image/pjpeg','image/gif','image/bmp','image/xpng'); / /Allow image type to upload
public $al_ph_size=1000000; //Allow upload file size
function __construct(){
$this>set_datatime();
}
function set_datatime(){
$this>datetime=date("YmdHis");
}
//Get file type
function get_ph_type($phtype){
$this>ph_type=$phtype;
}
//Get file size
function get_ph_size($phsize){
$this>ph_size=$phsize."
";
}
//Get the upload temporary file name
function get_ph_tmpname($tmp_name){
$this>ph_tmp_name=$tmp_name;
$this>imgsize=getimagesize($tmp_name);
}
//Get the original file name
function get_ph_name($phname){
$this>ph_name=$this>ph_path.$this>datetime.$phname;
}
//Determine the directory where uploaded files are stored
function check_path(){
if(!file_exists($this>ph_path)){
mkdir($this>ph_path);
}
}
//Determine whether the uploaded file exceeds the allowed size
function check_size(){
if($this>ph_size>$this>al_ph_size){
$this>showerror("Uploaded image exceeds 2000KB");
}
}
//Determine file type
function check_type(){
if(!in_array($this>ph_type,$this>al_ph_type)){
$this>showerror("Uploaded image type is wrong");
}
}
//Upload pictures
function up_photo(){
if(!move_uploaded_file($this>ph_tmp_name,$this>ph_name)){
$this>showerror("Error uploading file");
}
}
//Picture preview
function showphoto(){
if($this>preview==1){
if($this>imgsize[0]>2000){
$this>imgsize[0]=$this>imgsize[0]*$this>previewsize;
$this>imgsize[1]=$this>imgsize[1]*$this>previewsize;
}
echo("");
}
}
//Error message
function showerror($errorstr){
echo "";
exit();
}
function save(){
$this>check_path();
$this>check_size();
$this>check_type();
$this>up_photo();
$this>showphoto();
}
}
I am a newbie in PHP, and this is the first class I have written. If there are any shortcomings, you are welcome to criticize and correct me. Thank you very much!
D8888D’s reply content
test.php file
//Instantiation of class:
include("upoop.php");//The file name of the class is upoop.php
$up=new upphoto;
$up>get_ph_tmpname($_FILES['photo']['tmp_name']);
$up>get_ph_type($_FILES['photo']['type']);
$up>get_ph_size($_FILES['photo']['size']);
$up>get_ph_name($_FILES['photo']['name']);
$up>save();
//HTML of uploaded image: