File Upload in PHP

PHP allow you to upload any type of a file i.e. image, binary or text files. PHP has one in built global variable i.e. $_FILES, it contains all information about file.

By the help of $_FILES global variable, we can get file name, file type, file size and temp file name associated with file. In HTML, File Upload control can be created by using following.

<input type="file" name="fileupload"/>

$_FILES['filename']['name'] - returns file name.

$_FILES['filename']['type'] - returns MIME type of the file.

$_FILES['filename']['size'] - returns size of the file (in bytes).

$_FILES['filename']['tmp_name'] - returns temporary file name of the file which was stored on the server.

move_uploaded_file() function

  • The move_uploaded_file() function moves the uploaded file to a new location.
  • It moves the file if it is uploaded through the POST request.

Syntax

move_uploaded_file (string $filename , string $destination)

Configure The "php.ini" File

  • First, ensure that PHP is configured to allow file uploads.
  • In your "php.ini" file, search for the file_uploads directive, and set it to “On” i.e. file_uploads = On

Some rules to follow for the HTML form above:

  • Make sure that the form uses method="post" The form also needs the following attribute:enctype="multipart/form-data". It specifies which content-type to use when submitting the form
  • Without the requirements above, the file upload will not work.

Other things to notice

  • The type="file" attribute of the <input> tag shows the input field as a file-select control, with a "Browse" button next to the input control.
  • The form above sends data to a file called "upload.php", which we will create next.

Example: fileupload.html

<html>
	<head>
	<title>File Upload</title>
	</head>
	<body>
		<form action="upload.php" method="post" enctype="multipart/form-data">
			Select File:
			<input type="file" name="fileToUpload"/>
			<input type="submit" value="Upload Any File" name="submit"/>
		</form>
	</body>
</html>

Example: upload.php

<?php
	if(isset($_POST["submit"]))
	{
		$target_path = "D:/uploads/";
		$target_file = $target_path.basename($_FILES['fileToUpload']['name']);
		if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file))
		{
			echo "File uploaded successfully!";
		}
		else
		{
			echo "Sorry, file not uploaded, please try again!";
		}
	}
?>

PHP Script Explained:

  • $target_path = "D:/uploads/" - specifies the directory where the file is going to be placed.
  • $target_file specifies the path of the file to be uploaded.
  • move_uploaded_file - move the uploaded file to the target path.