Showing posts with label PHP File upload. Show all posts
Showing posts with label PHP File upload. Show all posts

Wednesday, February 22, 2012

Upload only JPEG file using PHP


This program will upload only .jpeg file to upload. If you try to upload other than .jpeg file it will generate a error output.


<?php
 if($_FILES["file"]["type"]=='image/jpeg')
{
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

   if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
        echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
       move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      } 
}
else
{
   echo "Not a JPEG file.Please choose one JPEG file to upload";
}
?>
<html>
<body>
                <form action="myajax.php" method="post" enctype="multipart/form-data">
                Choose file to upload:-<input type="file" name="file">
                <input type="submit" name="sub" value="Upload">
                </form>
</body>
</html>

File upload using PHP


File uploading using PHP is very commonly use in PHP driven website . To upload file using PHP you have to insert one attribute into form tag that is enctype="multipart/form-data" . It defines how the form content will encrypt when it will travel to server.
Create a upload folder in current location of your program. And after uploading the file will save in upload folder.



Step 1) copy and paste following code to upload file using PHP. It will work for any type of file.


<?php
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
        echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      } 
?>
<html>
<body>
                <form action="myajax.php" method="post" enctype="multipart/form-data">
                Choose file to upload:-<input type="file" name="file">
                <input type="submit" name="sub" value="Upload">
                </form>
</body>
</html>