0
Posted December 31, 2012 by Victor in PHP Programming
 
 

File Uploading in PHP

upload-file
upload-file

There is no doubt that there are countless reasons why you may want to upload files when working online. Sometimes, it is to initiate a file transfer while at other times it is to save the file and the list continues. Did you know that PhP is a scripting language that will help you in uploading files? Indeed, you can use PhP scripts to upload files, control the file type to be uploaded and control even the size of your upload. Here is what you need to do in order to upload files with PhP.

1.  Create an Upload Form Using HTML

The first step that you will take is to create a HTML interface. This interface will allow your users to upload files as it will provide the general framework of the file upload interface. Here is how we do it:


<html>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">

<!--This passes the upload information from the html file to the php file.-->

<label for="fileupload">My File:</label>

<input type="file" name="fileuploadbox" id="file"><br>

<input type="submit" name="submit" value="Upload File">

</form>

</body>

</html>

  • The form enctype attribute is used on the form tag line to specify the type of content to be used when the form is being submitted. As such the multipart/form enctype means that the form will use binary information such as file content being uploaded.
  • The type enlisted as file in the input tag means that the input received will be processed as a file.

2.  Create the PhP Script For Uploading Files

The next step after creating the HTML file for accepting upload, we will have to create the uploads.php file which will have the PhP scripts enabling the file upload to take place successfully. To perform this, here are the codes that you will use:


<html>

<body>

<form name="upload.php" method="get">

<?php

$upload_path = “/home/victorservername/public_html/victor.com”;

if (is_uploaded_file($HTTP_POST_FILES['filename']['tmp_name']))

  {

    if (move_uploaded_file($HTTP_POST_FILES['filename']['tmp_name'],  $upload_path.$HTTP_POST_FILES['filename']['name']))

      {

         echo "file uploaded succesfully.";

      }

  }

    else

        {

          echo "file has not been uploaded.";

        }

?>

</body>

</html>

Note that the upload.php and the upload.html are saved as two different files. When the both files are saved in a server and the URL of upload.html is typed, you will get a form to upload a file. When you browse and get the file to upload and click on the upload button, link for your upload will be passed to the upload.php file which will in turn upload the file to selected folder location path.


Victor