PHP – File Upload Simple Example


Uploading a file involves two steps.

In first step, we create a form with attribute method=”post”. It does not work with get method. We also add another attribute enctype=”multipart/form-data” to the form tag. This attribute is basically to encrypt the file contents. After that we add a input field with type file and a submit.

In second step, we use php to move the file to desired folder. When we submit the form, it uploads the file to some temporary location $_FILES[“myFile”][“tmp_name”]. And from that temporary location we move the file to our desired directory.

The sample code for the first step is as below.

Line 6: It would render a browse  button which open the browser window.

Following is the code of action page.

Line 2: The FILES is a built in 2 d associative array. The first key of this array is the name of the input field of file type that was defined in previous name. the second key “name” would give the name of the uploaded file.

Line 4: the tmp_name is used to get the current temporary path where the file was temporarily uploaded.

Line 7: the built in php function to move the file from given temporary location to desired folder. the first argument is source and the second argument is destination. You can change the destination path and name whatever you desire.

Happy Coding!!!!