In this article , You will get code with that you can upload any image or photo to your server using PHP.You can use same code for uploading any file you want. Just change the extensions defined in the code. Following code supports only jpeg,jpg and png image extensions upto file size of 2 mb.

HTML CODE

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="photo">
<input type="submit" value="Upload Image" name="submit">
</form>

 

PHP CODE – upload.php

<?php
if(isset($_FILES)
{
function rand_string( $length )  // rand_string() function declaration
{
$str="";
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars ); // strlen() checks length of string $chars
for( $i = 0; $i < $length; $i++ ) 
{
$str .= $chars[ rand( 0, $size - 1 ) ]; // ‘ .= ‘ concatenating assignment operator  
}
return $str; 
}
$file_error=$_FILES['photo']['error'];
if($file_error!=0)
{
echo "Browse file before uploading";
}
else
{
$file_name = $_FILES['photo']['name'];
$file_size =$_FILES['photo']['size'];
$file_tmp =$_FILES['photo']['tmp_name'];
$file_type=$_FILES['photo']['type'];
$file_ext=strtolower(end(explode('.',$file_name)));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
echo "Photo extension not allowed, please choose a JPEG or PNG file.";
}
elseif($file_size > 2097152){
echo 'Photo size must be less than 2 MB';
}
else
{
$random=rand_string(5);
$newphoto=$random."_".$file_name;
$upload=move_uploaded_file($file_tmp,"images/".$newphoto);
if($upload)
{
echo "Photo uploaded successfully to images directory";
}
else
{
echo "Problem uploading photo! Please try after sometime.";
}
}
}
}
else
{
echo "<center>Sorry! You are not allowed to visit this page.</center>";
}

Note: Create a directory with name images in the same directory of upload.php