Home  >  Article  >  Backend Development  >  PHP image upload learning notes and experiences_PHP tutorial

PHP image upload learning notes and experiences_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:15:18872browse

We must use the #_FILE variable when uploading files in PHP. This automatic global variable $_FILES is supported starting from PHP 4.1.0 version. Prior to this, starting with version 4.0.0, PHP supported the $HTTP_POST_FILES array. These arrays will contain all the information about the files you uploaded, of which we recommend using $_FILES.

If the PHP setting option register_globals is on, the related variable names will also exist. Starting from PHP version 4.2.0, the default value of register_globals is set to off.

We assume the name of the file upload field is userfile. The name can be whatever you want.

$_FILES['userfile']['name']
The original name of the client machine file.

$_FILES['userfile']['type']
The MIME type of the file, which requires browser support for this information, such as "image/gif".

$_FILES['userfile']['size']
The size of the uploaded file, in bytes.

$_FILES['userfile']['tmp_name']
The temporary file name stored on the server after the file is uploaded.

$_FILES['userfile']['error']
Error code related to the file upload. ['error'] was added in PHP 4.2.0.

Handling function:

move_uploaded_file()
(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file -- Move the uploaded file to a new location

Description
bool move_uploaded_file (string filename, string destination)

This function checks and ensures that the file specified by filename is a legal upload file (that is, uploaded through PHP's HTTP POST upload mechanism). If the file is legal, it is moved to the file specified by destination.

If filename is not a valid uploaded file, no operation will occur and move_uploaded_file() will return FALSE.

If filename is a valid uploaded file but cannot be moved for some reason, no action will occur and move_uploaded_file() will return FALSE. A warning is also issued.

If the target file already exists, it will be overwritten.

Example:

The code is as follows Copy code
if(move_uploaded_file($_FILES["magfile" ]["tmp_name"], $uploaddir))
 代码如下 复制代码
if(move_uploaded_file($_FILES["magfile"]["tmp_name"], $uploaddir))
  {
    echo "Update OK!";
  }
{

echo "Update OK!";
}


You can also use copy(PHP 3, PHP 4, PHP 5) copy -- copy file

bool copy (string source, string dest)

Copy files from source to dest. Returns TRUE on success, FALSE on failure.

 代码如下 复制代码

 
 
accept="image/x-png,image/gif,image/jpeg"> 
 

Submission page:

The code is as follows Copy code
 代码如下 复制代码

    if($_FILES['picurl']['size'] > 0){
      if(move_uploaded_file ($_FILES['picurl']['tmp_name'], $_FILES['picurl']['name'])){
        echo "图片上传成功";
      }
    }

accept="image/x-png,image/gif,image/jpeg">
Processing page:
The code is as follows Copy code
if($_FILES['picurl']['size'] > 0){ If(move_uploaded_file ($_FILES['picurl']['tmp_name'], $_FILES['picurl']['name'])){ echo "Picture uploaded successfully";         } }

Other non-File type forms can still be received using $_POST['name'].

Easy implementation of uploading images in php

 代码如下 复制代码
 
 
PHP上传图片简单实现  
 
 
if($_GET['action'] == 'upfile')
{
$target_path = 'temp_'.$_FILES['photo']['name'];
echo '上传的临时文件:' .$_FILES['photo']['tmp_name'] . '
';
echo '上传的目标文件:' .$target_path . '
';
echo $_SERVER["SCRIPT_FILENAME"] . '
';
echo $_SERVER["OS"] . '
';
//测试函数: move_uploaded_file
//也可以用函数:copy
move_uploaded_file($_FILES['photo']['tmp_name'], $target_path); 
echo "Upload result:"; 
if(file_exists($target_path)) { 
 if($_SERVER["OS"]!="Windows_NT"){
  @chmod($target_path,0604);
 }
 echo 'Succeed!
'; 
} else { 
 echo 'Failed!'; 

exit; 

?> 

Registration

 
 
 
Your information 
     
  • Your Phot
  •  
 
 
 
 
 

The above code is only suitable for learning. If you want to use it on the current server, we must write it as follows

The code is as follows Copy code

/***************************************************** ******************************

Parameter description:
$max_file_size : upload file size limit, unit BYTE
$destination_folder: Upload file path
$watermark : Whether to add a watermark (1 means adding watermark, others means not adding watermark);

Instructions for use:
1. Remove the ; number in front of the "extension=php_gd2.dll" line in the PHP.INI file, because we need to use the GD library;
2. Change extension_dir = to the directory where your php_gd2.dll is located;
*************************************************** ****************************/

//Upload file type list
$uptypes=array(
'image/jpg',
'image/jpeg',
'image/png',
'image/pjpeg',
'image/gif',
'image/bmp',
'image/x-png'
);

$max_file_size=2000000; //Upload file size limit, unit BYTE
$destination_folder="uploadimg/"; //Upload file path
$watermark=1; //Whether to add a watermark (1 means adding watermark, others means not adding watermark);
$watertype=1; //Watermark type (1 is text, 2 is picture)
$waterposition=1; //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, 5 is in the center);
$waterstring="http://www.bKjia.c0m/"; //Watermark string
$waterimg="xplore.gif"; //Watermark image
$imgpreview=1; //Whether to generate a preview image (1 is generated, others are not generated);
$imgpreviewsize=1/2; //Thumbnail ratio
?>


ZwelL Image Uploader



Upload file:



The file types allowed to be uploaded are:

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
If (!is_uploaded_file($_FILES["upfile"][tmp_name]))
//Whether the file exists
{
echo "The picture does not exist!";
exit;
}

$file = $_FILES["upfile"];
If($max_file_size < $file["size"])
//Check file size
{
echo "The file is too large!";
exit;
}

if(!in_array($file["type"], $uptypes))
//Check file type
{
echo "File type does not match!".$file["type"];
exit;
}

if(!file_exists($destination_folder))
{
           mkdir($destination_folder);
}

$filename=$file["tmp_name"];
$image_size = getimagesize($filename);
$pinfo=pathinfo($file["name"]);
$ftype=$pinfo['extension'];
$destination = $destination_folder.time().".".$ftype;
If (file_exists($destination) && $overwrite != true)
{
echo "The file with the same name already exists";
exit;
}

if(!move_uploaded_file ($filename, $destination))
{
echo "Error moving file";
exit;
}

$pinfo=pathinfo($destination);
$fname=$pinfo[basename];
echo " has been uploaded successfully
File name: ".$destination_folder.$fname."
" ;
echo " width:".$image_size[0];
echo " length:".$image_size[1];
echo "
Size:".$file["size"]." bytes";

if($watermark==1)
{
          $iinfo=getimagesize($destination,$iinfo);
          $nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
         $white=imagecolorallocate($nimage,255,255,255);
         $black=imagecolorallocate($nimage,0,0,0);
         $red=imagecolorallocate($nimage,255,0,0);
Imagefill($nimage,0,0,$white);
         switch ($iinfo[2])
            {
case 1:
              $simage =imagecreatefromgif($destination);
             break;
case 2:
              $simage =imagecreatefromjpeg($destination);
             break;
case 3:
               $simage =imagecreatefrompng($destination);
             break;
case 6:
              $simage =imagecreatefromwbmp($destination);
             break;
                 default:
                die("Unsupported file type");
exit;
}

imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
Imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);

switch($watertype)
            {
Case 1: // Add water print string
Imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
             break;
Case 2: // Add watermark pictures
              $simage1 =imagecreatefromgif("xplore.gif");
Imagecopy($nimage,$simage1,0,0,0,0,85,15);
                 imagedestroy($simage1);
             break;
}

        switch ($iinfo[2])
        {
            case 1:
            //imagegif($nimage, $destination);
            imagejpeg($nimage, $destination);
            break;
            case 2:
            imagejpeg($nimage, $destination);
            break;
            case 3:
            imagepng($nimage, $destination);
            break;
            case 6:
            imagewbmp($nimage, $destination);
            //imagejpeg($nimage, $destination);
            break;
        }

        // 更多原格式文件
        imagedestroy($nimage);
        imagedestroy($simage);
    }

    if($imgpreview==1)
    {
    echo "
图片最佳:
";
    echo "图片图片:r文件名:";
    }
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628871.htmlTechArticle We are in php中安全文件就师下使用#_FILEvariable了,This automatic global variable $_FILES is from PHP 4.1. 0 版线电影被手机。 Before this,从4.0.0 特許庁,PHP support...
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