Image upload in php

Image upload in php

Now a days everything will be done on to the internet and by the using of web apps or website all the thing would be done. To manage all the thins on to front end side we need to write backend script. And to upload files and images on to the website there is mandatory to write file-upload script in backend. So, are you getting problems to upload files using all the validations?? Then don’t worry this tutorial is for you only. Just follow the below code for file upload in php with proper validation.

Step 1: Create a new file with the name fileupload.php

Step 2: Write a form script for upload a file using Html file-upload attribute.  For that I have mention below code.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>FUP 23</title>
</head>

<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" />
</form>
</body>
</html>

Step 3: Write a script for uploading file using php. Please follow below code.

	if(isset($_FILES['image'])){
$err=array();
$fn=$_FILES['image']['name'];
$fs=$_FILES['image']['size'];
$ft=$_FILES['image']['type'];
$ftmp=$_FILES['image']['tmp_name'];
$fext=strtolower(end(explode('.',$fn)));
$ext=array("jpg","jpeg","gif","png");
if($fs > 2097152){
$err[]="File size error";
}
if(file_exists("upload/".$fn)){
$err[]="File exist error";
}
if(in_array($fext,$ext)===false){
$err[]="File extension error";
}
if(empty($err)==true){
move_uploaded_file($ftmp,"upload/".$fn);
echo "<br>fn : ".$fn;
echo "<br>fs : ".$fs;
echo "<br>ft : ".$ft;
echo "<br>ferr : ".$_FILES['image']['error'];
}
else{
print_r($err);
}
}

Explanation of php script :

  • First if condition is used to check weather image is selected or not.
  • All the variable is defined for the upload a file using html file-upload attribute and as the syntax of php.
  • Second if condition is used to check the size of file for limitation of uploading file size.
  • Third condition is used to check the file is already exist or not into the directory. If file is already existing then it will show error.
  • And the last if condition is use to check errors if there is not any error occur during the execution of file it will simply upload your file into directed directory folder. And if it any type of error occurs during execution of file it will simply give error for the particular reason.

Congratulation, your file will be uploaded successfully!

That’s all. If you find this article is helpful don’t forget to share with your friends. Please help us by doing comment using comment box. Thank you!

Also Read:

Indian ‘TikTok Alternative’ Chingari App Crosses 100 millions Downloads in just few days

Post Comments(0)

Leave a reply