How to upload image or file in php ?

 

Image or file upload is a crucial part in every web application. Using PHP you can upload any type of file to the server. One more thing which is very important is that, as per security concern make sure you have implemented all the security checks (like file is valid or maximum upload file size and so on). In this tutorial we will see how to upload image,file,multiple files using PHP.

Before upload any image or file below are the recommendation you should check.
1)Check file_uploads is set to 1 in your PHP configuration file.if 0 then you can’t upload file.
2)Your folder must be writable where you want to store your uploaded files.
3)Your form must have the enctype=”multipart/form-data” attributes with “method=post”.

class.image.php
We have created a class file which have 7 properties and 6 methods.We will discuss one bye one.

Name Type Description
$upload_folder Properties All uploaded image/files will upload in this folder
$path Properties Store absolute full path of the upload folder
$max_upload_size Properties Maximum file upload size in bytes. Default is 2 MB
$new_file_name Properties Whether you want to give a new name to the uploaded file.
$rename_file Properties If value is "true" then the file will rename after uploaded. Default is false
$allowed_file_type Properties These are the allowed files type which can be uploaded. By default extension with ("zip","pdf","doc", "jpg", "bmp", "jpeg", "gif", "png") will support
__construct() Method This is a constructor method. By default store the absolute path of the file upload folder.
getMIMEExtension($ext) Method This method returns the MIME type of a file.
SupportedMIMEExtension($ext) Method Defined the MIME supported type.
maxFileUploadSize($size_in_bytes) Method This method checks the maximum upload file size
getAllFilesAsArray($posted_file) Method Mainly use for multiple files upload.Store all the information about a file in an array.
getFileExtention($file_information) Method Returns the file extension
isValidFile($file_information) Method This method checks whether file is a proper MIME type file. Using this function you can checks whether uploaded is a valid file. Suppose if someone tries to rename a xxx.exe file to xxx.png and tries to upload then this method does not allow the user to upload the file.
uploadFile($file_information) Method This method uploads the file to the server and returns the new filename

Upload single image or file

index.php
Below are the code for single file or image upload.

<?php
include("class.image.php");
$Obj=new Image();
$error='';
$Obj->allowed_file_type=array('jpeg','jpg','png','gif');
$Obj->max_upload_size=1048576; //1 MB
if($_SERVER['REQUEST_METHOD']=='POST'){		
	if($_FILES["img_name"]['tmp_name']==''){
		$error.='<li>Please upload file.</li>';
	}else if($Obj->isValidFile($_FILES["img_name"])==false){
		$error.='<li>'.$_FILES["img_name"]['name'].' is not a valid '.implode(',',$Obj->allowed_file_type).' file.</li>';
	}else if($Obj->maxFileUploadSize($_FILES["img_name"]['size'])==false){
		$error.='<li>'.$_FILES["img_name"]['name'].' size should not a be greater than '.$Obj->max_upload_size.' bytes.</li>';
	}
	
	if($error!=''){
		$error='<ul>'.$error.'</li>';
	}else{	
		$Obj->rename_file=true;
		$Obj->new_img_name=time(); //You can put your new file name
		$Obj->uploadFile($_FILES["img_name"]);
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>File Upload Script</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
  <?php
  if($error!==''){
  	 echo $error;
  }
  ?>
  Image:
  <input name="img_name" type="file"><br />  
  <input type="submit" value="Upload">  
</form>
</body>
</html>

In the above code we have called this property $Obj->allowed_image=array(‘jpeg’,’jpg’,’png’,’gif’); to allow only image. So when user uploads a file other than this defined file then the script does not allow. Next the script checks, file should not be blank and then it is valid image and finally the script checks the maximum upload size. Here we have defined a file size must not be greater than 1 MB. If there is no any error then it executes next section of code. If image will be uploaded successfully, then we want to rename the image with the help of $Obj->rename_file=true; properties and give a new name to the image using of $Obj->new_img_name to current time. Finally the image will be successfully uploaded.

Upload multiple images or files

For multiple files upload, a form input file types name must be an array like this <input name=”img_name[]” type=”file”>. You can upload multiple files as many as you want. For multiple files above code is used but with this time within a loop because we are going to upload multiple files.

<?php
include("class.image.php");
$Obj=new Image();
$error='';
$Obj->allowed_file_type=array('jpeg','jpg','png','gif','doc','xlsx');
if($_SERVER['REQUEST_METHOD']=='POST'){
	$fileArray = array();
    $totalfile = count($_FILES["img_name"]['name']);	
	$PostedFile=$Obj->getAllFilesAsArray($_FILES["img_name"]);	
	if(count($PostedFile)>0){
		foreach ($PostedFile as $key =>$val) {	
			$file_name=$val['name'];
			if($val['tmp_name']==''){
				$error.='<li>Field '.($key+1).' is blank. Please upload file.</li>';
			}else if($Obj->isValidFile($val)==false){
				$error.='<li>'.$val['name'].' is not a valid '.implode(',',$Obj->allowed_file_type).' file.</li>';
			}		
		}
	}
	
	if($error!=''){
		$error='<ul>'.$error.'</li>';
	}else{
		$Obj->rename_file=true;
		foreach ($PostedFile as $key =>$val) {
			$Obj->new_file_name=time().$key;
			$Obj->uploadFile($val);			
		}
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Multiple File Upload Script</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
  <?php
  if($error!==''){
  	 echo $error;
  }
  ?>
  Image:
  <input name="img_name" type="file"><br />  
  <input type="submit" value="Upload">  
</form>
</body>
</html>

This is the script for single file and multiple file uploads. I hope you’ve got good knowledge. Keep in touch with me for more tutorials.

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories