Sunday, August 11, 2013

PHP File Uploader

Let's see how to create a simple File Uploader into your php form or your web page.
As you use input types such as text, radio, password, etc..., there is a input type called "file".
And there is a small text should be included to ur html form as an attribute and value.
This is the code.

<form enctype="multipart/form-data">
      <input type="file" name="myuploader" id="myuploader1"><br/>
      <input type="submit" name="submit" value="Submit">
</form>

This is how it looks like...



You must set your form encrypt type as "multipart/form-data". Attribute name is "enctype".

To upload file, the action to be performed in form, you need to code it in another file. Assume its name is "uploadmyfile.php". Then your form with action and data parse method should be like this.

<form enctype="multipart/form-data" action="uploadmyfile.php" method="post">
      <input type="file" name="myuploader" id="myuploader1"><br/>
      <input type="submit" name="submit" value="Submit">
</form>

You must set your form method as "post". The file uploaders will not work on "get" method.
Now your "uploadmyfile.php" file code should be like this.

if ($_FILES["myuploader"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["myuploader"]["error"] ;
    }
  else
    {
   
    if (file_exists("upload/" . $_FILES["myuploader"]["name"]))
      {
      echo $_FILES["myuploader"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["myuploader"]["tmp_name"],
      "upload/" . $_FILES["myuploader"]["name"]);
      echo "Your File has been Stored in: " . "upload/" . $_FILES["myuploader"]["name"];
      }
    }
  }

By using this code, you can upload your files into folder called "upload" where your "uploadmyfile.php" file exists.

No comments:

Post a Comment