How to upload file using PHP - Tanseer

How to upload file using PHP


These days almost every web application contains file upload option, so I will guide you that how to upload file to server using PHP. This will be basic file upload not multiple file or ajax based and I will post article for that later.

HTML Form:

<form action="upload_file.php" method="post" enctype="multipart/form-data">
	Your File: <input type="file" name="my_file" />
	<input type="submit" name="submit" value="Upload" />

First you need to put  enctype attribute in form tag with value multipart/form-data. Then you need at least one file input field in form.

PHP Upload Code:

//check if form contain file input with specify name attribute
	//if no errors...
	    $valid_file = true;
		//Change file name if needed, I put time() before file name to append current unix time number to make file unique
		$new_file_name = time().'_'.strtolower($_FILES['my_file']['name']); //rename file
		if($_FILES['my_file']['size'] > (1024000)) //check file size if you want. Can't be larger than 1 MB
			$valid_file = false;
			echo  'Oops!  Your file\'s size is to large.';  // Show message or save in varialbe if you want
		//if file is valid
			//Main Function to move uploaded file from temp location to real location on server
			move_uploaded_file($_FILES['my_file']['tmp_name'], 'uploads/'.$new_file_name);
			echo 'Congratulations!  Your file was accepted.';   // show or save success message if you want
	//if there is an error...
		//set that to be the returned message
		echo 'Ooops!  Your upload triggered the following error:  '.$_FILES['photo']['error'];  // show or save error message if you want

In above PHP code first I checked if form with input file is submitted and then I check for file error, If no error found then rename file with unique name using time() function to get current time UNIX time number and append before filename. I also check file size and if file size is less than or equal to 1MB then upload file by moving temp uploaded file to uploads directory.

You can also get following detail from $_FILES.


There are some issue that can occurred during file uploading:

  • Issue with Max file upload size. To fix this you need to modify php.ini file upload_max_filesize value. You can also set this using php by calling ini_set() function.
  • Issue with $_POST size, you can fix this by increasing size in php.ini post_max_size.

Comment if you have any issue.

One Comments

  • Ramzan Raza March 26, 2018 Reply

    I want to get designed my website by using XFileSharing Pro Script. Can you design?

Leave a Reply

Read previous post:
Skip Else statement in conditional Statement - Tanseer
How to skip Else statement

Hello everyone, This is my first post related to Programming. I always love to write code with best practices and...