File Upload

Uses the $_FILES super global.

 

A simple form requesting file name to upload:

<html>
<body>
	<form action="fileUpload.php" method="post" enctype="multipart/form-data">
		<input type="file" name="myUploadFile" />
		<input type="submit" name="submit" value="Submit" />
	</form>
</body>
</html>

*note:

  • the form has an enctype="multipart/form-data"
  • the first element in the above form is of type="file", and has a name "myUploadFile" (just for this example)

 

Upon submit, the data is sent using the POST method to the file specified in the form action: "fileUpload.php".

 

<?php
	move_uploaded_file($_FILES["myUploadFile"]["tmp_name"], "/uploads/" . $_FILES["myUploadFile"]["name"]);
	echo "Stored in: " . "/uploads/" . $_FILES["myUploadFile"]["name"] ;
?>

The uploaded file is then copied from its temp location for permanent storage.

 

Ensure the script has the correct permissions in order to save the file to the desired location.

 

And that the desired location exists!

 

<?php
	move_uploaded_file($_FILES["myUploadFile"]["tmp_name"], "./uploads/" . $_FILES["myUploadFile"]["name"]);

	$fileIn = "./uploads/" . $_FILES["myUploadFile"]["name"] ;

	echo "Stored in: $fileIn <br><br>" ;

	if (file_exists($fileIn) ) {

		echo "File moved OK:<br>" ;

		//uploaded file in the temporary directory on the web server
		echo $uploadedFile = $_FILES['myUploadFile']['tmp_name'] . "<br>" ;

		//actual name of the uploaded file
		echo $fileName = $_FILES['myUploadFile']['name'] . "<br>" ;

		//size in bytes of the uploaded file
		echo $fileSize = $_FILES['myUploadFile']['size'] . "<br>" ;

		//MIME type of the uploaded file
		echo $mimeType = $_FILES['myUploadFile']['type'] . "<br>" ;

		//error code associated with this file upload
		echo $errorCode = $_FILES['myUploadFile']['error'] . "<br>" ;

	} else {

	echo "Problem uploading file: $errorCode" ;
	}
?>

Leave a Reply