Example Form to Upload A File Using PHP

The example is a web page that allows one to select a file from their computer, and have that file uploaded to the webserver.

The first file is the web page that contains the component to allow one to select a file and the script to run, upload_attachment.php, when the form is submitted.

uploadFile.html

<HTML>
<BODY>

<!--- Simple Form to select a file from computer ---->
<H2> Example of a Web Page to Upload a File </H2>
<form action='upload_attachment.php' method='post'enctype='multipart/form-data'>
      Filename  <input type='file' name='uploadedfile'></div>
      <INPUT TYPE='SUBMIT' Name='Submit' Value='Submit'>
</form>

</BODY>
</HTML>

Screenshot of Sample Web Page. When the Choose File button is clicked, file manager appears to allow one to select a file. As mentioned above, when the Submit button is clicked, the upload_attachment.php script runs. It contains the script that uploads the selected file to a specific location on the web server.

upload_attachment.php

<?php

//generates a random number to be used as part of the filename and store in variable $rand.
$rand=rand(100,9999999999); 

//gets the current month and year and place in variables $month and $year
$month = date("m");
$year = date("Y");

//creates a subfolder in docs based on the month and year
mkdir("docs/"."$month-$year",0755,true);

//specifies the location where to upload the file on the web server
$target_path = "docs/$month-$year/";

//adds the filename to the $target_path variable
$target_path = $target_path .$rand. "-".basename( $_FILES['uploadedfile']['name']);

//specifies the filename 
$filename = $rand. "-".basename( $_FILES['uploadedfile']['name']); 

	//starts uploading file
        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
		{
	        //add script to insert filename into a database table if keeping track into a database table
 		}
?>