How to Upload File in PHP

In this tutorial you will learn how to upload file using PHP. You can check the tutorial to implement multiple file upload using jQuery and PHP.

File uploading is an important part of web application. Every website has some file upload functionality. So here in this tutorial, we we will explain how to implement file upload with PHP. We will handle the file upload with built-in PHP function move_uploaded_file().

Also, read:

We will cover this tutorial with live example and create a HTML Form with file browse input. Then we will handle file upload functionality using PHP. So let’s start the coding.

Step1: Create File Upload HTML Form

First we will create HTML Form for file upload with file input and a submit button. We will also use the form attribute enctype=”multipart/form-data” to specify the content type of submitted form. The multipart/form-data is important for file upload as it handles the form submit data has its content type, file name and data separated by boundary from other field.


<form name="form" class="form" action="" method="post" enctype="multipart/form-data">							
	<div class="form-group">
		<label for="captcha" class="text-info">
		<?php if($message) { ?>
			<span class="text-warning"><strong><?php echo $message; ?></strong></span>
		<?php } ?>	
		</label><br>
		<input type="file" name="fileUpload" id="fileUpload" class="form-control">
	</div>														
	<div class="form-group">	
		<input type="submit" name="upload" class="btn btn-info btn-md" value="Upload">							
	</div>							
</form>

Step2: Implement File Upload with PHP

Now we will implement the file upload functionality when From submitted. We will check file upload size.If file is larger than 500KB, then display error message. Then we will handle file upload using move_uploaded_file() and upload file to uploads direcotry.

We will display upload success error message if file uploaded successfully otherwise file upload failed message.

<?php
$uploadDir = "uploads/";
$canUpload = 1;
$message = '';
if(isset($_POST["upload"]) && $_FILES["fileUpload"]["name"]) {
	$targetFile = $uploadDir . time().basename($_FILES["fileUpload"]["name"]);
	if ($_FILES["fileUpload"]["size"] > 500000) {
		$message = "Sorry, your file is too large.";
		$canUpload = 0;
	}
	if ($canUpload == 0) {
		$message = "Sorry, File upload failed.";
	} else {
		if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $targetFile)) {
			$message = "The file has been uploaded successfully.";
		} else {
			$message = "Sorry, Error in uploading file.";
		}
	}
}
?>

You may also like:

One thought on “How to Upload File in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *