Home >Backend Development >PHP Tutorial >PHP function example for uploading images

PHP function example for uploading images

WBOY
WBOYOriginal
2016-07-25 08:57:001053browse
This article shares a code for uploading images in PHP. File upload is implemented through the built-in PHP function. Friends in need can refer to it.

1, form part

<!-- Form Area -->
<form enctype="multipart/form-data" action="uploader.php" method="post"> 
Select Image: <input type="file" name="userfile"> 
<input type="submit" value="Upload!"> 
</form> 
<!-- Form Area -->

2. PHP code for uploading image files

<?php 

# Variables
$path = "images/";  
$max_size = "200000"; 

# File
$filename = $_POST['userfile']; 

# Control
if (!isset($HTTP_POST_FILES['userfile'])) exit; 

if (is_uploaded_file($HTTP_POST_FILES['userfile']['tmp_name'])) { 

if ($HTTP_POST_FILES['userfile']['size']>$max_size) {  
echo "文件太大,超过了上传文件的最大限制。The Max File Size is $max_size KB<br>n";  
exit;  
} 

# Type Control
if ( 
   ($HTTP_POST_FILES['userfile']['type']=="image/gif")   ||          
   ($HTTP_POST_FILES['userfile']['type']=="image/jpg")   ||   
   ($HTTP_POST_FILES['userfile']['type']=="image/bmp")   || 
   ($HTTP_POST_FILES['userfile']['type']=="image/png")   || 
   ($HTTP_POST_FILES['userfile']['type']=="image/jpeg") 
) 
{ 

# If File Exist
if (file_exists($path . $HTTP_POST_FILES['userfile']['name']))  
{  
echo "同名的文件已存在。<br>";  
exit;  
} 

$res = copy($HTTP_POST_FILES['userfile']['tmp_name'], $path . 

$HTTP_POST_FILES['userfile']['name']); 
if (!$res){  
echo "上传失败!<br>";  
exit;  
}  
else{  
echo "上传成功!<br>";  
} 

echo "File Name: ".$HTTP_POST_FILES['userfile']['name']."<br>"; 
echo "File Size: ".$HTTP_POST_FILES['userfile']['size']." bytes<br>"; 
echo "File Type: ".$HTTP_POST_FILES['userfile']['type']."<br>"; 
echo "View Image"; 
}  
else  
{ 
echo "错误的文件类型<br>";  
exit;  
} 
} 
?>

Note: Code after php5 no longer uses this method and instead uses the global variable $_FILE to receive uploaded data.



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