Hey there! any question in your mind? Ask It Now!.

Popular Categories





upload file with size ,type and extension restrictions.

+5 votes
937 views
asked in Programming by vicky (390 points)
edited by Bhartesh
I am using php and i am using code for uploading a file but there is no restriction in so i want upload file with size ,type and extension restrictions.

Thanks for answer!

1 Answer

0 votes
answered by nisha (720 points)
edited by Bhartesh

Use this code by this you can check format ,size, extension of file

this is html part

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

this is upload_file.php

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    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 "Invalid file";
  }
?>

Related Questions

0 votes
1 answer 247 views
0 votes
1 answer 405 views
+1 vote
2 answers 78 views
+6 votes
2 answers 1,557 views
+2 votes
1 answer 139 views
+1 vote
1 answer 221 views
asked in Programming by duke Expert (5,813 points)
+6 votes
3 answers 6,836 views
0 votes
1 answer 133 views

Not a Member yet?

Ask to Folks Login

My Account
749 Folks are online
60 members and 689 guest online
Your feedback is highly appreciated