on May 6th, 2008File Uploading in PHP

File uploading is very simple in PHP when comparing to other server side programming languages. File uploading is very useful in most of the situations like uploading user’s photos, uploading csv reports, uploading pdf reports and so on.

Making a simple front end with file browsing box:

  1.  
  2. <form method="post" enctype="multipart/form-data">
  3. Upload a file
  4. <input name="my_file" type="file" />
  5. <input value="Upload" type="submit" />
  6. </form>

Note: You should have this enctype=”multipart/form-data”‘ in your form tag while uploading files.
The php source code to upload the files

  1.  
  2. if(isset($_FILES[‘my_file’][‘name’]) &amp;&amp; $_FILES[‘my_file’][‘name’] != )
  3. {
  4. $upload_dir = ‘home/myaccount/public_html/images’;//uploading directory, this folder should have write permission to the current user
  5. $upload_file = $upload_dir.‘/’.basename($_FILES[‘my_file’][‘name’]);
  6.  
  7.   //check if the file name already exists
  8.    if(file_exists($upload_file))
  9.      {
  10.      echo "File Already Exists"; //if file already exists print the error message
  11.      }
  12.      else
  13.      {
  14.           if(move_uploaded_file($_FILES[‘my_file’][‘tmp_name’],$upload_file))
  15.              {
  16.              echo "File Uploaded";
  17.              }
  18.             else
  19.             {
  20.             echo "There was a problem to upload file";
  21.             }
  22.      }
  23. }
  24. ?>

5 Responses to “File Uploading in PHP”

  1. file concepton 07 May 2008 at 3:26 am

    Nice tutorial for beginners

  2. phpbitson 07 May 2008 at 5:36 am

    thanks for your comment

  3. sturaton 08 May 2008 at 2:46 pm

    Thanks , It will really help me

  4. Linux Forumon 15 May 2008 at 12:27 pm

    Nice tutorial, but how to validate the file extensions?

  5. zend phpon 15 May 2008 at 12:29 pm

    Great php file uploading tutorial, but it needs few works to secure the functionality.

Trackback URI | Comments RSS

Leave a Reply