go top

File uploading with PHP

PHP allows you to upload files using a simple HTML form on your web page directly on the server. There are few things that you need to do to make this working – page with web form, uploading script, folder on your server with permission set to be able to write in it.

Lets start with the form. Below you can see a basic web form for uploading a file.

<form action="upload.php" method="post" enctype="multipart/form-data">
File: <input type="file" name="filename" />
<input type="submit" value="Upload" />
</form>


The most important about the form is that you should make it uses POST and not GET method and also you should use enctype="multipart/form-data" so it knows that a file will be transferred.
Now we need to make a folder (names 'uploading') on our web server and set its permissions to 777 so the upload.php script that we will do is able to write the file in it. In rare cases depending on your server configuration you may not need to do this. We should also know the absolute path on the server for that folder (example: /home/username/www/uploading/)
Now we are ready to make our upload.php script.

<?php
$folder = “/home/username/www/uploading/”;
if (is_uploaded_file($HTTP_POST_FILES['filename']['tmp_name'])) {
if (move_uploaded_file($HTTP_POST_FILES['filename']['tmp_name'], $folder.$HTTP_POST_FILES['filename']['name'])) {
Echo “File uploaded”;
} else {
Echo “File not moved to destination folder. Check permissions”;
};
} else {
Echo “File is not uploaded.”;
};
?>


Now, I will explain what the above code do. When, a file is uploaded it is first given a temp filename and then put in the temp folder of your web server. That temp filename is accessible using the global $HTTP_POST_FILES array variable. On our web form we have our browse field named “filename” (<input type="file" name="filename" />), so the name of that temp file is:
$HTTP_POST_FILES['filename']['tmp_name']


The real name of the file being uploaded is stored in another variable called $HTTP_POST_FILES['filename']['name']. As you can see this just another array element named “name” in the $HTTP_POST_FILES['filename'] array.

Now after having that file upload in our web server temp folder we need to move it to the folder specified $folder=“/home/username/www/uploading/”. This is done using the move_uploaded_file() function.

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


the first parameter that it takes is the temp filename and the second parameter is the destination folder and filename. If it successfully moves the temp file to the folder that we want it returns TRUE and we made it print “File uploaded” message on the screen.
  • Free Scripts

    Add great new functionalities to your website with our Free Scripts collection.

    Free scripts
  • PHP Scripts

    Check our extensive collection of top-notch PHP Scripts that will enhance your website!

    Commercial PHP scripts

71 Comments to "File uploading with PHP"

  • Amisha Shah

    Amisha Shah

    July 13, 2015 at 13:02 pm

    I want to code for insert image in particular web form & dispaly in image field using php & mysql

  • GANDE

    GANDE

    June 16, 2015 at 13:05 pm

    i want passport ( photo) uploaded in application form with file size less than 15kb and the passport previewed on same place without form submission. somebody pls help

  • jigar

    jigar

    June 2, 2015 at 08:21 am

    index.php
    <?php
    include('config.php');
    if (!isset($_FILES['image']['tmp_name'])) {
    echo "";
    }else{
    $file=$_FILES['image']['tmp_name'];
    $image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $image_name= addslashes($_FILES['image']['name']);

    move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);

    $location="photos/" . $_FILES["image"]["name"];
    $caption=$_POST['caption'];

    $save=mysql_query("INSERT INTO photos (location, caption) VALUES ('$location','$caption')");
    header("location: index.php");
    exit();
    }
    ?>
    addexec.php
    <?php
    include('config.php');
    if (!isset($_FILES['image']['tmp_name'])) {
    echo "";
    }else{
    $file=$_FILES['image']['tmp_name'];
    $image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $image_name= addslashes($_FILES['image']['name']);

    move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);

    $location="photos/" . $_FILES["image"]["name"];
    $caption=$_POST['caption'];

    $save=mysql_query("INSERT INTO photos (location, caption) VALUES ('$location','$caption')");
    header("location: index.php");
    exit();
    }
    ?>

    • rocky

      rocky

      September 29, 2015 at 07:33 am

      <?php
      include ("conn.php");
      $sid=$_REQUEST['sid'];
      $result =mysql_query("SELECT * FROM city WHERE sid = '$sid'");
      ?>
      <option>Select city</option>
      <?php while ($row=mysql_fetch_array($result)) { ?>
      <option value=<?php echo $row['ctid'];?>><?php echo $row['ctname'];?></option>
      <?php } ?>
      <script>
      function getState(val) {
      $.ajax({
      type: "POST",
      url: "get_state.php",
      data:'cid='+val,
      success: function(data){
      $("#state-list").html(data);
      }
      });
      }
      </script>
      <select name="cname" onChange="getState(this.value)">
      <option>Select Country</option>
      <?php while($row=mysql_fetch_array($result))
      { ?>
      <option value="<?php echo $row['cid']?>"><?php echo $row['cname']?></option>
      <?php }?>
      </select>
      <td><select name="sname" id="state-list" onChange="getCity(this.value)">
      <option value="">Select State</option>
      </select>
      </td>

  • jayasree

    jayasree

    September 30, 2014 at 12:08 pm

    nice

  • Peter

    Peter

    August 1, 2014 at 10:16 am

    Hi

    Plse help, after the file is uploaded via the above upload script I want it also to be displayed on a php page. The next users upload must be displayed on the same page but next to the previous users etc etc... is this possible?

  • vipul singh

    vipul singh

    July 1, 2014 at 10:49 am

    while applying the mention code in the tutorial, i'm getting the folllowing error msg..


    Notice: Undefined variable: HTTP_POST_FILES in C:xampphtdocsfile_uploadupload.php on line 23
    File is not uploaded.

  • Claudia Rogers

    Claudia Rogers

    May 23, 2014 at 12:20 pm

    I have not tried this yet but it looks like its exactly what I need.

    I want my registered users to be able to upload video files to specific folders.

    Here is what I am thinking"

    Step 1-Write an upload.php file for each directory I want files moved to using a varied name.

    example:
    upload1.php
    upload2.php

    Step 2-Change the move to part to reflect the directory I want

    for example:
    move_uploaded_file($HTTP_POST_FILES['filename']['tmp_name'], $folder.$HTTP_POST_FILES['filename']['folder1'])

    move_uploaded_file($HTTP_POST_FILES['filename']['tmp_name'], $folder.$HTTP_POST_FILES['filename']['folder2'])

    Step 3-Change the form action to the specific upload.php

    example:
    <form action="upload1.php" method="post" enctype="multipart/form-data">
    <form action="upload2.php" method="post" enctype="multipart/form-data">

    Am I correct here or is there an easier way?

    One other thing:
    How do I specify file types?

    Thank you
    Claudia



  • Daniel

    Daniel

    April 10, 2014 at 07:56 am

    So when I do it. every time it yells at me saying file is not uploaded. What should I change in the code to make it work?

  • Jamil

    Jamil

    February 8, 2014 at 22:09 pm

    Consider having someone proof-read articles before uploading them. It's important to make your content look professional.

  • rokad naina

    rokad naina

    January 29, 2014 at 19:05 pm

    for php website solution.......

Add your comment

Captcha