File Upload In Php Example Code Demo

A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.

HTML Code:

Here is a brief description of the important parts of the above code:

  • enctype=”multipart/form-data” – Necessary for our to-be-created PHP file to function properly.
  • action=”uploader.php” – The name of our PHP page that will be created, shortly.
  • method=”POST” – Informs the browser that we want to send information to the server using POST.
  • input type=”hidden” name=”MA… – Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example.
  • input name=”uploadedfile” uploadedfile is how we will access the file in our PHP script.

Save that form code into a file and call it upload.html.

file uploads

Creating an upload script

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input’s name attribute in uploading form was file, then PHP would create following five variables −

  • $_FILES[‘file’][‘tmp_name’] − the uploaded file in the temporary directory on the web server.
  • $_FILES[‘file’][‘name’] − the actual name of the uploaded file.
  • $_FILES[‘file’][‘size’] − the size in bytes of the uploaded file.
  • $_FILES[‘file’][‘type’] − the MIME type of the uploaded file.
  • $_FILES[‘file’][‘error’] − the error code associated with this file upload.

Example

It will produce the following result –

Upload file

Thanks for reading my article about “File Upload In Php Example Code Demo”. If you like this article do me favor by sharing it with your friends.

Digital Technology Hub