Advance File Upload in PHP

I’ll show you a so called advance file upload implementation in PHP.
Advance because we’ll be changing the file name of the uploaded file for some good reason. I’m sure you’re thinking why should we change the file name of the uploaded file. The reason for that is that every time we’ll upload a file, we are going to store it in our server.

So what happens now if the file name already exist in the server? PHP will automatically replace the file without letting us now, so it’s kinda weird.

Think of it this way:
User1 uploads a file called “document.doc“. Then, User2 uploads a file called “document.doc”(same file name with User1). Of course those 2 files have different content in it, they just have the same file name. PHP replaces the file of User1 into the file that was uploaded by User2. So now, you got my point. :)

Here’s what we’re going to do.

<form action="upload.php" method="post" enctype="multipart/form-data">
if( $_SESSION['img_upload_error'] ) echo $_SESSION['img_upload_error'];
     <label for="uploadImage">Upload Profile Picture</label>
     <input id="file" type="file" name="file" />
     <input type="submit" />
unset( $_SESSION['img_upload_error'] );


$file = $_FILES['file'];
#this is a function that will get the file extension of the uploaded file
 $file_extension = GetFileExtension( $file['name'] );

#we will change the name of the file name at the same time we'll append the file extension
$fileName = GenerateRandomStringAndInt().".".$file_extension;

if ( $file["error"] > 0 ) #If there's an error, return back to the previous page
   $_SESSION['img_upload_error'] = "There was an error while uploading your image. Please try again";
   header( "location: ".$_SERVER['HTTP_REFERER'] ); #this would redirect user to the previous page
     #1MB, We are limiting the file upload into 1MB you can always change this one depending on your  preference.
     if( $file['size'] > 1024000 ) 
        $_SESSION['img_upload_error'] = "There was an error while uploading your image. Please try again";
        header( "location: ".$_SERVER['HTTP_REFERER'] );

     #while the file is exsting in the server, replace the filename
     while( file_exists( "/files/" . $fileName ) ) #/files/ is the directory where we will store the files
        $fileName = GenerateRandomStringAndInt().$file_extension;

       move_uploaded_file( $file["tmp_name"], "/files/" . $fileName );

function GetFileExtension( $filename )
   return pathinfo( $filename, PATHINFO_EXTENSION );

function GenerateRandomStringAndInt( $length = 15 )
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string ="";
    for ( $p = 0; $p < $length; $p++ ) {
        $string .= $characters[ mt_rand( 0, strlen( $characters ) ) ];
    return $string;

Now you are golden! Just create a directory named  “files” so that we’ll store the files in there.

This is how easy to implement an Advance File Upload in PHP.

Hope this helps someone.

Have a happy coding! :)