Uploading files to a web server via PHP

From Knowledge Kitchen
Jump to navigation Jump to search


This example shows how to use PHP to upload a file from the web client to the web server.

Note: You must have a folder named 'uploads' in the same folder as this code. The permissions on this folder must be writeable by 'others'.

Main HTML page

<!doctype html>
 <html>
 	<head>
 		<title>Example of file upload</title>
 	</head>
 	<body>
 		<h1>Example of file upload</h1>
 		<p>
 			This example shows how to upload a file using PHP.
 		</p>
 
 		<form action="process_upload.php" method="POST" enctype=" multipart/form-data">
 			<label for="file">Please select a file</label>
 			<input type="file" id="file" name="file" />
 			<br />
 			<input type="submit" value="Upload!" />
 		</form>
 
 	</body>
 </html>


PHP script

<?php
 
 //get the temporary location of the file that was just uploaded
 $temporaryPath = $_FILES['file']['tmp_name'];
 
 //generate the path where you want to store it permanently on your server
 $permanentPath = "uploads/" . $_FILES['file']['name'];
 
 //try moving it from its temporary location the permanent one
 $success = move_uploaded_file($temporaryPath, $permanentPath);
 
 //decide what to do next...
 if ($success) {
 	echo "Yes! Upload successful.";
 }
 else {
 	echo "No! Upload failed.";
 }
 
 ?>


What links here