search
HomeBackend DevelopmentPHP TutorialPHP file upload program code_PHP tutorial

PHP file upload program code_PHP tutorial

Jul 20, 2016 am 11:12 AM
phpuploadundercodeussearchdocumentNowuseprogramkind

Now we only need to search for a lot of file upload classes, but there are not many upload classes that are really useful. Below I will introduce this file upload class, which I have used for a long time. It is a very good code. You can refer to Reference 1.

The code is as follows Copy code

/**
* File upload class
*/
class uploadFile {

public $max_size = '1000000';//Set the upload file size
public $file_name = 'date';//The renaming method represents naming by time, and others use given Name
public $allow_types;//File extensions allowed to be uploaded, different file types are separated by "|"
public $errmsg = '';//Error message
public $uploaded = '' ;//Uploaded file name (including file path)
public $save_path;//Uploaded file saving path
private $files;//Submitted files waiting to be uploaded
private $file_type = array() ;//File type
private $ext = '';//Upload file extension

/**
* Constructor, initialization class
* @access public
* @param string $file_name Uploaded file name
* @param string $save_path Uploaded target folder
*/
public function __construct($save_path = './upload/ ',$file_name = 'date',$allow_types = '') {
                                                                                                                                  use   use to be named                                                    ->save_path = (preg_match('//$/',$save_path)) ? $save_path : $save_path . '/';
$this->allow_types = $allow_types == '' ? 'jpg| gif|png|zip|rar' : $allow_types;
}

/**
* Upload files
* @access public
* @param $files Files waiting to be uploaded ($_FILES[] from the form)
* @return boolean Return Boolean value
*/
public function upload_file($files) {
$name = $files[ 'name'];
$type = $files['type'];
$size = $files['size'];
$tmp_name = $files['tmp_name'];
$error = $files['error'];

switch ($error) {
case 0 : $this->errmsg = '';
break;
case 1 : $this->errmsg = 'Exceeded the file size in php.ini';
                                                                                                                                                                                                                                                                   break;
                                                                                                                                                                                                                      > Break; Case 5: $ this-& gt; errmsg = 'Upload file size is 0';
Break;
default: $ this-& gt; errmsg = 'Upload file fails! ';
break;
}
If($error == 0 && is_uploaded_file($tmp_name)) {
//Detect file type
if($this->check_file_type($name) == FALSE){
return FALSE;
                                                                                                                                                                                                                                                                                             = red>'.$name.' is too large, the maximum supported file is '.ceil($this->max_size/1024).'kb';
            return FALSE; ?$this-> ;file_name.'.'.$this->ext : date('YmdHis').'.'.$this->ext;//Set the new file name
                                                                                                ->save_path.$new_name;//Uploaded file name
                                                                                                                                                                                                  = 'File'.$this->uploaded.'Uploaded successfully! ';
                return TRUE; ! ';
                return FALSE;                                                              $filename){
        $ext = $this->get_file_type($filename);
         $this->ext = $ext;
           $allow_types = explode('|',$this->allow_types);// Split the file extensions that are allowed to be uploaded into an array
//echo $ext;
//Check whether the uploaded file extension is among the file extensions that are allowed to be uploaded
if(in_array($ext,$allow_types )){
                         return TRUE; Support upload & lt; font color = red & gt; '. Str_replace (' | ',', ', $ this- & gt; all_types).
}
}

/**
* Check the uploaded file type
* @access public
* @param string $filename The name of the file waiting to be checked
* @return Returns TRUE if the check passes, FALSE and an error message if it fails
*/
public function get_file_type($filename){
$info = pathinfo ($filename); > Public function set_save_path(){
$this->save_path = (preg_match('//$/',$this->save_path)) ? $this->save_path : $this->save_path . '/';
if(!is_dir($this->save_path)){
//If the directory does not exist, create the directory
}
}


/**
* Set the saving path after uploading the file
*/
public function set_dir($dir = null){
//Check whether the path exists
if(!$dir } ';
}
$dir = explode('/', $dir);
foreach($dir as $v){
if($v){
$d .= $v . '/';
if(!is_dir($d)){
$state = mkdir($d, 0777);
if(!$state)
$this-> ;errmsg = 'Error creating directory ' . $d . '! ' ;
class uploadImg extends uploadFile {

public $mark_str = 'kickflip@php100'; //Watermark string
public $str_r = 0; //String color R
public $str_g = 0; // String color G
public $str_b = 0; //String color B
public $mark_ttf = './upload/SIMSUN.TTC'; //Watermark text font file (including path)
public $mark_logo = './upload/logo.png'; //Watermark image
public $resize_h;//Generate thumbnail height
public $resize_w;//Generate thumbnail width
public $source_img; //Source image file
public $dst_path = './upload/';//Thumbnail file storage directory, if left blank, it will be the source image storage directory

/**
* Generate thumbnail The picture after the thumbnail is generated
* @access public
* @param integer $w The width of the reduced image (px)
* @param integer $h The height of the reduced image (px)
* @param string $source_img Source image ( Path + file name)
*/
public function img_resized($w,$h,$source_img = NULL){
$source_img = $source_img == NULL ? $this->uploaded : $source_img ;//Get the address of the source file. If it is empty, it defaults to the last uploaded image
if(!is_file($source_img)) { //Check whether the source image exists
$this->errmsg = 'File'.$source_img.' does not exist';
return FALSE;
}
$this->source_img = $source_img;
$source = $this->img_create($source_img); //Create source image
            $this->resize_w = $w;
              $this->resize_h =  $h;  
            $thumb = imagecreatetruecolor($w,$h);
imagecopyresized($thumb,$source,0,0,0,0,$w,$h,$img_info[0],$img_info[1]);// Generate thumbnail images
$dst_path = $this->dst_path == '' ? $this->save_path : $this->dst_path; //Get the target folder path
$dst_path = (preg_match ('//$/',$dst_path)) ? $dst_path : $dst_path . '/';//Add /
after the target folder if(!is_dir($dst_path)) $this-> set_dir($dst_path); //If the target folder does not exist, create
$dst_name = $this->set_newname($source_img);
$this->img_output($thumb,$dst_name); //Output image
imagedestroy($source);
imagedestroy($thumb);
}

/**
*Watermark
*@access public
*@param string $source_img Source image path + file name
*@param integer $mark_type Watermark type (1 is English string, 2 is Chinese character String, 3 is the picture logo, the default is the English string)
*@param integer $mark_postion watermark position (1 is the lower left corner, 2 is the lower right corner, 3 is the upper left corner, 4 is the upper right corner, the default is the lower right corner) ;
*@return watermarked picture
*/
public function img_mark($source_img = NULL,$mark_type = 1,$mark_postion = 2) {
$source_img = $source_img == NULL ? $this->uploaded : $source_img;//Get the address of the source file, if it is empty, the default is the above The image uploaded this time
if(!is_file($source_img)) { //Check whether the source image exists
$this->errmsg = 'File'.$source_img.'does not exist';
return FALSE;
}
$this->source_img = $source_img;
$img_info = getimagesize($source_img);
$source = $this->img_create($source_img); // Create source image
$mark_xy = $this->get_mark_xy($mark_postion);//Get the watermark position
$mark_color = imagecolorallocate($source,$this->str_r,$this->str_g, $this->str_b);

switch($mark_type) {

case 1: //Add English string watermark
$str = $this->mark_str; ImageString ($ Source, 5, $ Mark_xy [0], $ Mark_xy [1], $ Str, $ Mark_color); reak;

Case 2: // Add Chinese string watermark
if (! IS_FILE ($ this- & gt; mark_ttf)) {// Check whether the font file exists
$ this- & gt; errmsg = 'Watermark failure: font failure: font File '. $ This- & gt; mark_ttf.' Does not exist! ';
Return false;
}
$ Str = $ this- & gt; mark_str;
// $ str = iconv (' '' ' gbk','utf-8',$str);//Convert character encoding. If you use GBK encoding, please remove the comment on this line
. Watermark
If(is_file($this->mark_logo)){ //If there is a watermark logo image, get the basic information of the logo image, if it does not exist, exit
mark_logo);
            }else{
                                                                                                                                                                     mark_logo); ';
                return FALSE;
            }
 
            $logo_info = getimagesize($this->mark_logo);
            if($logo_info[0]>$img_info[0] || $logo_info[1]>$img_info[1]) { //If the source image is smaller than the logo size, exit
                                                                                                                   'Smaller than '.$this->mark_logo.'! ' ; source, $logo, $mark_xy[ 4], $mark_xy[5], 0, 0, $logo_info[0], $logo_info[1]);
                                                                                                   >
default: //Others are text images
$str = $this->mark_str;
imagestring($source,5,$mark_xy[0],$mark_xy[1],$str ,$mark_color);
$this->img_output($source,$source_img);
break;
}
imagedestroy($source);
}

/**
* Get the watermark position
* @access private
* @param integer $mark_postion The position of the watermark (1 is the lower left corner, 2 is the lower right corner, 3 is the upper left corner, 4 is the upper right corner, others are right Lower corner)
* @return array $mark_xy The coordinates of the watermark position (index 0 is the English string watermark coordinate X, index 1 is the English string watermark coordinate Y,
* Index 2 is the Chinese string watermark coordinate X, Index 3 is the Chinese string watermark coordinate Y, index 4 is the watermark image coordinate X, index 5 is the watermark image coordinate Y)
*/
private function get_mark_xy($mark_postion){
$img_info = getimagesize($this->source_img);

$stre_w = strlen($this->mark_str)*9+5; //The length of the watermark English string (px) (the English character size of size 5 is about 9px, plus 5px for beauty)
                          (The Chinese character size of size 12 is 12px. In utf8, the length of a Chinese character is 3 bytes and 4px per byte, while the length of an English character is approximately 9px
// In order to mix Chinese and English As shown below, set its length to the number of bytes*7px)
$strc_w = strlen($this->mark_str)*7+5; //The length of the watermark Chinese string (px)

If(is_file($this->mark_logo)){ //If there is a watermark logo image, get the basic information of the logo image
$logo_info = getimagesize($this->mark_logo);
}

//Due to the different starting positions of strings in the imagestring function and imagettftext function, the Y positions of English and Chinese strings are also different
//The imagestring function is referenced from the upper left corner of the text. The imagettftext function is From the lower left corner of the text as a reference
switch($mark_postion){

case 1: //Position lower left corner
$mark_xy[0] = 5; //Watermark English string coordinates X
             $mark_xy[1] = $img_info[1]-20; // Watermark English string coordinates Y
             $mark_xy[2] = 5; //              Chinese string coordinates = $ img_info [1] -5; // Watermark Chinese string coordinates y
$ MARK_XY [4] = 5; // Watermark image coordinates x
$ MARK_XY [5] = $ img_info [1]-$ $ $ logo_info[1]-5; //Watermark image coordinates Y
break;

case 2: //Position lower right corner
$mark_xy[0] = $img_info[0]-$stre_w; //Watermark English string coordinates ; //Watermark Chinese string coordinates logo_info[0]-5;//Watermark image coordinates
          case 3: //Position upper left corner
                                                                                                                                                                                                                                 _> $ Mark_xy [2] = 5; // Watermark Chinese string coordinates x
$ Mark_xy [3] = 15; // Watermark Chinese String Coordinates y
$ Mark_xy [4] = 5; // Watermark image coordinates img_info[0]-$stre_w; //Watermark English string coordinates $strc_w; //Watermark Chinese string coordinates$mark_xy[4] = $img_info[0]-$logo_info[0]-5;//Watermark image coordinates >
default: // Other defaults are the lower right corner
$mark_xy[0] = $img_info[0]-$stre_w; // Watermark English string coordinates X
$mark_xy[1] = $img_info [1]-5;//The watermark English string coordinates Y
                                                                                                                                              img_info[1]-15;//Watermark Chinese string coordinates Y
                                                                                                                                                                         5] = $img_info[1]-$logo_info[1]-5;//Watermark image coordinates Y
break;
}
return $mark_xy;
}

/ **
* Create a source image
* @access private
* @param string $source_img Source image (path + file name)
* @return img Create an image from the target file
*/
private function img_create($source_img) {
$info = getimagesize($source_img);
switch ($info[2]){
case 1:
If(!function_exists('imagecreatefromgif')){
$source = @imagecreatefromjpeg($source_img);
}else{
$source = @imagecreatefromgif ($source_img);
}
             break; $source = @imagecreatefrompng($source_img);
break ;
                                                                                                                                                                                                               $source =                                                                               🎜> break;
}
return $source;
}

/**
* Rename the image
* @access private
* @param string $source_img Source image path + file name
* @return string $dst_name Renamed image name (path + file name)
*/
private function set_newname($sourse_img) {
$info = pathinfo($sourse_img);
$new_name = $this->resize_w.'_'.$this->resize_h.'_'.$info['basename'];//Change the file name to: width_height_filename
if( $this->dst_path == ''){ //If the path to store the thumbnail is empty, it defaults to the same folder as the source file
                                                                                                                                  );
}else{
$dst_name = $this->dst_path.$new_name;
}
return $dst_name;
}

/**
* Output picture
* @access private
* @param $im processed image
* @param $dst_name output image name (path + file name)
* @return output image
*/
public function img_output($ im,$dst_name) {
$info = getimagesize($this->source_img);
switch ($info[2]){
case 1:
if(!function_exists('imagegif ')){
imagejpeg($im,$dst_name);
}else{
imagegif($im, $dst_name);
}
          break;
           case 2:
                       imagejpeg($im,$dst_name); 🎜>         case 6:
                    imagewbmp( $im,$dst_name);
break;
}
}

}
?>




Usage

The code is as follows Copy code

Upload file
td>
 浠g
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use