Jump to content

Validating uploaded files types (RESOLVED)


InGale

Recommended Posts

Hi!I'm trying to validate that the uploaded files are in correct format. So I have this code:

  if ($_FILES["magazine"]["error"] > 0)  {  echo "Error: " . $_FILES["magazine"]["error"] . "<br />";  }  elseif ($_FILES["cover"]["error"] > 0)  {  echo "Error: " . $_FILES["cover"]["error"] . "<br />";  }else  {	  	  if (($_FILES["cover"]["type"] == "image/jpeg")|| ($_FILES["magazine"]["type"] == "pdf/pdf")|| ($_FILES["magazine"]["type"] == "application/zip")||($_FILES["magazine"]["type"] == "application/x-zip-compressed"))		  {			  echo "Upload: " . $_FILES["magazine"]["name"] . "<br />";  echo "Type: " . $_FILES["magazine"]["type"] . "<br />";  echo "Size: " . number_format(($_FILES["magazine"]["size"] / 1024), 2) . " Kb<br />";    //Retrieve magazine file  if (file_exists("../magazines/" . $_FILES["magazine"]["name"]))	  {	  echo $_FILES["magazine"]["name"] . " already exists. ";	  }  elseif (file_exists("../magazines/" . $_FILES["cover"]["name"]))	  {	  echo $_FILES["cover"]["name"] . " already exists. ";	  }	else	  {	  move_uploaded_file($_FILES["magazine"]["tmp_name"],	  "../magazines/" . $_FILES["magazine"]["name"]);	  $mag_url = "../magazines/" . $_FILES["magazine"]["name"]; 	   move_uploaded_file($_FILES["cover"]["tmp_name"],	  "../magazines/" . $_FILES["cover"]["name"]);	  $cover_url = "../magazines/" . $_FILES["cover"]["name"];	  	  	  $issue_num = $_REQUEST['issue_num'];	  $issue_desc = $_REQUEST['issue_desc'];	  $issue_month = $_REQUEST['issue_month'];	  $issue_year = $_REQUEST['issue_year'];	  	  $query = "INSERT INTO vanity_mag (issue_num, issue_month, issue_year, mag_url, cover_url, issue_desc) VALUES ('$issue_num', '$issue_month', '$issue_year', '$mag_url', '$cover_url', '$issue_desc')";	  mysql_query($query, $connection)		  or die ("Query failed" . mysql_error());	  echo "Stored in: " . "../magazines/" . $_FILES["magazine"]["name"];	  	  $query = "SELECT * from vanity_mag ORDER BY mag_id desc";	  $result = mysql_query($query)		  or die ("Query failed: " . mysql_error());	  echo "<table border='1'>";		  echo "<TR>";		echo "<TH>ID</TH><TH>Issue number</TH><TH>URL</TH><TH>Cover URL</TH><TH>Description</TH>";		echo "</TR>";	  while ($row = mysql_fetch_array($result))	  {		  echo "<TR>";		  echo "<TD>", $row['mag_id'], "</TD><TD>", $row['issue_num'], "</TD><TD>", $row['mag_url'], "</TD><TD><a href='", $row['cover_url'], "'>", $row['cover_url'], "</TD><TD>", $row['issue_desc'], "</TD>";		  echo "</TR>";	  }	  echo "</table>";	  }		}  else	  { 	 echo "<span class='message_error'>Only .pdf, .zip and .jpg files are allowed!</span>";	  }  }

It does upload the files, but it uploads ANY file, not only the ones I want to allow. How do I fix it? Thanks!

Link to comment
Share on other sites

I tried it too, but I'm still able to upload any file. Here's the new code:

if (($_FILES["cover"]["type"] == "image/jpeg")|| ($_FILES["magazine"]["type"] == "pdf/pdf")|| ($_FILES["magazine"]["type"] == "application/zip")|| ($_FILES["magazine"]["type"] == "application/x-zip-compressed"))  {  if ($_FILES["magazine"]["error"] > 0)	  {	  echo "Error: " . $_FILES["magazine"]["error"] . "<br />";	  }	  elseif ($_FILES["cover"]["error"] > 0)	  {	  echo "Error: " . $_FILES["cover"]["error"] . "<br />";	  }	  else		  {		  echo "Upload: " . $_FILES["magazine"]["name"] . "<br />";		  echo "Type: " . $_FILES["magazine"]["type"] . "<br />";		  echo "Size: " . number_format((($_FILES["magazine"]["size"] / 1024))/1024, 2) . " MB<br />";		  		  //Retrieve magazine file		  if (file_exists("../magazines/" . $_FILES["magazine"]["name"]))			  {			  echo $_FILES["magazine"]["name"] . " already exists. ";			  }		  elseif (file_exists("../magazines/" . $_FILES["cover"]["name"]))			  {			  echo $_FILES["cover"]["name"] . " already exists. ";			  }			else			  {			  move_uploaded_file($_FILES["magazine"]["tmp_name"],			  "../magazines/" . $_FILES["magazine"]["name"]);			  $mag_url = "../magazines/" . $_FILES["magazine"]["name"];		 			   move_uploaded_file($_FILES["cover"]["tmp_name"],			  "../magazines/" . $_FILES["cover"]["name"]);			  $cover_url = "../magazines/" . $_FILES["cover"]["name"];			  			  			  $issue_num = $_REQUEST['issue_num'];			  $issue_desc = $_REQUEST['issue_desc'];			  $issue_month = $_REQUEST['issue_month'];			  $issue_year = $_REQUEST['issue_year'];			  			  $query = "INSERT INTO vanity_mag (issue_num, issue_month, issue_year, mag_url, cover_url, issue_desc) VALUES ('$issue_num', '$issue_month', '$issue_year', '$mag_url', '$cover_url', '$issue_desc')";			  mysql_query($query, $connection)				or die ("Query failed" . mysql_error());			  echo "Stored in: " . "../magazines/" . $_FILES["magazine"]["name"];			  			  $query = "SELECT * from vanity_mag ORDER BY mag_id desc";			  $result = mysql_query($query)				or die ("Query failed: " . mysql_error());			  echo "<table border='1'>";				echo "<TR>";				echo "<TH>ID</TH><TH>Issue number</TH><TH>URL</TH><TH>Cover URL</TH><TH>Description</TH>";				echo "</TR>";			  while ($row = mysql_fetch_array($result))			  {				  echo "<TR>";				  echo "<TD>", $row['mag_id'], "</TD><TD>", $row['issue_num'], "</TD><TD>", $row['mag_url'], "</TD><TD><a href='", $row['cover_url'], "'>", $row['cover_url'], "</TD><TD>", $row['issue_desc'], "</TD>";				  echo "</TR>";			  }			  echo "</table>";			  }		}  }else	  { 	 echo "<span class='message_error'>Only .pdf, .zip and .jpg files are allowed!</span>";	  }

Link to comment
Share on other sites

well, what specifically is the problem? uploading, or filtering by file type? you should make sure the uploading part works, then the filtering part.

Link to comment
Share on other sites

well, what specifically is the problem? uploading, or filtering by file type? you should make sure the uploading part works, then the filtering part.
The upload part works. The problem is that I need to allow upload of .pdf, .jpg and .zip files only, and at the moment this code uploads any file - .pdf, .jpg, .zip, .exe, .rar, .doc etc...
Link to comment
Share on other sites

Before getting on with the hard part of the script, try this simple test:var_dump($_FILES);exit;See what it gets you. Specifically, check the value and data type of $_FILES["cover"]["type"]. Automatic type casting leads to strange results. For instance, (0 == "image/jpeg") evaluates to true.

Link to comment
Share on other sites

The difference between your code and the tutorial is that you are checking more than one upload, and you're using OR to do it. If the cover file is a jpg, then the other one can be anything. If the magazine is a PDF, then the cover can be anything. Look at your if condition and think about what you really want to check.

Link to comment
Share on other sites

The difference between your code and the tutorial is that you are checking more than one upload, and you're using OR to do it. If the cover file is a jpg, then the other one can be anything. If the magazine is a PDF, then the cover can be anything. Look at your if condition and think about what you really want to check.
Yup, it helped, thank you! I changed the code to
if (($_FILES["cover"]["type"] == "image/jpeg")&& ($_FILES["magazine"]["type"] == "pdf/pdf")|| ($_FILES["magazine"]["type"] == "application/zip")|| ($_FILES["magazine"]["type"] == "application/x-zip-compressed"))

and it worked.However, now I tried to add another upload field, "magazine_ereader", I added the appropriate (as it seems) coding, but the code doesn't check that field. It allows this field only to upload any file. Here's the new code:

if (($_FILES["cover"]["type"] == "image/jpeg")|| ($_FILES["cover"]["type"] == "image/jpg")&& ($_FILES["magazine"]["type"] == "pdf/pdf")|| ($_FILES["magazine"]["type"] == "application/zip")|| ($_FILES["magazine"]["type"] == "application/x-zip-compressed")&& ($_FILES["magazine_ereader"]["type"] == "pdf/pdf")|| ($_FILES["magazine_ereader"]["type"] == "application/zip")|| ($_FILES["magazine_ereader"]["type"] == "application/x-zip-compressed"))  {	  if ($_FILES["magazine"]["error"] > 0)		  {		  echo "Error: " . $_FILES["magazine"]["error"] . "<br />";		  }	  elseif ($_FILES["magazine_ereader"]["error"] > 0)		  {		  echo "Error: " . $_FILES["magazine_ereader"]["error"] . "<br />";		  }	  elseif ($_FILES["cover"]["error"] > 0)		  {		  echo "Error: " . $_FILES["cover"]["error"] . "<br />";		  }	  else			{ etc...

I had a few other problems that I managed to solve, but again I'm stuck with this validation...

Link to comment
Share on other sites

Use parentheses to separate the conditions.

if ((  $_FILES["cover"]["type"] == "image/jpeg"	|| $_FILES["cover"]["type"] == "image/jpg") && (  $_FILES["magazine"]["type"] == "pdf/pdf"	|| $_FILES["magazine"]["type"] == "application/zip"	|| $_FILES["magazine"]["type"] == "application/x-zip-compressed") && (  $_FILES["magazine_ereader"]["type"] == "pdf/pdf"	|| $_FILES["magazine_ereader"]["type"] == "application/zip"	|| $_FILES["magazine_ereader"]["type"] == "application/x-zip-compressed"))

Link to comment
Share on other sites

Use parentheses to separate the conditions.
if ((  $_FILES["cover"]["type"] == "image/jpeg"	|| $_FILES["cover"]["type"] == "image/jpg") && (  $_FILES["magazine"]["type"] == "pdf/pdf"	|| $_FILES["magazine"]["type"] == "application/zip"	|| $_FILES["magazine"]["type"] == "application/x-zip-compressed") && (  $_FILES["magazine_ereader"]["type"] == "pdf/pdf"	|| $_FILES["magazine_ereader"]["type"] == "application/zip"	|| $_FILES["magazine_ereader"]["type"] == "application/x-zip-compressed"))

Didn't work - I'm getting the "Only .pdf, .zip and .jpg files are allowed!" error message, even though these are the files I'm trying to upload...
Link to comment
Share on other sites

are you sure pdf/pdf is the right mime type? it says here pdf uses application/pdfalso if any of the 3 fields are optional you'll need to "skip" the type check for those fields, like

if ((  !isset($_FILES["cover"])	|| $_FILES["cover"]["type"] == "image/jpeg"	|| $_FILES["cover"]["type"] == "image/jpg")

Link to comment
Share on other sites

Do Dad's suggestion in post 6 to see what's being submitted. The conditions look fine to me.
Did that. Here's the result that I got:array(3) { ["magazine"]=> array(5) { ["name"]=> string(19) "D7000_ENnoprint.zip" ["type"]=> string(28) "application/x-zip-compressed" ["tmp_name"]=> string(27) "C:\Windows\Temp\php7E75.tmp" ["error"]=> int(0) ["size"]=> int(23250721) } ["magazine_ereader"]=> array(5) { ["name"]=> string(35) "Calendario-SerieA-Tim-2011-2012.pdf" ["type"]=> string(15) "application/pdf" ["tmp_name"]=> string(27) "C:\Windows\Temp\php821F.tmp" ["error"]=> int(0) ["size"]=> int(2010678) } ["cover"]=> array(5) { ["name"]=> string(17) "IKS_0507-Edit.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(27) "C:\Windows\Temp\php82AD.tmp" ["error"]=> int(0) ["size"]=> int(593505) } } So apparently the type should be "application/pdf", rather than "pdf/pdf". Now it seems to work. All 3 big browsers displayed the same result. Also, the .zip file type is "application/x-zip-compressed" in all of them, so I guess I won't be needing the line with the "application/zip" file type, right? I just read somewhere that FF recognizes .zip as "application/x-zip-compressed" and IE as "application/zip", that's why I put 2 lines for .zip files in the first place...Many, many thanks to all of you!!!
Link to comment
Share on other sites

are you sure pdf/pdf is the right mime type? it says here pdf uses application/pdfalso if any of the 3 fields are optional you'll need to "skip" the type check for those fields, like
if ((  !isset($_FILES["cover"])	|| $_FILES["cover"]["type"] == "image/jpeg"	|| $_FILES["cover"]["type"] == "image/jpg")

Yup, MIME type was wrong. I used it cause I've seen it in some example code, thought it was right...Thank you for the link! Good to know these types in case I'll need them (and I know I will)! However, it also says that .zip file are "application/zip", while the browser says it's "application/x-zip-compressed"... I'm confused...Regarding the optional fields, actually all of them have to be filled. I have to think how I make sure of it... Any suggestions? :)
Link to comment
Share on other sites

i think application/zip and application/x-zip-compressed are 2 different versions of zip files, wiki says the mime type is application/zip, and here explains the compressed one.i'd definitely recommend supporting both of those zip types, as users may have the non-compressed or compressed versions of the zip file, also older browser versions may not support the compressed one.actually there's another one on that page, application/x-zip, might be worth supporting that too lolfor the required fields, you can do:

if (!isset($_FILES["cover"]) || $_FILES["cover"]["size"] == 0){	echo "cover not uploaded!";}

Link to comment
Share on other sites

I wrote this code to make sure that the fields aren't empty:

$issue_num = $_REQUEST['issue_num'];$issue_month = $_REQUEST['issue_month'];$issue_year = $_REQUEST['issue_year'];$issue_theme = $_REQUEST['issue_theme'];$issue_desc = $_REQUEST['issue_desc'];if (!isset($_FILES["cover"]) || $_FILES["cover"]["size"] == 0){	$empty_cell = "Cover not uploaded!<br>";}if (!isset($_FILES["magazine"]) || $_FILES["magazine"]["size"] == 0){	$empty_cell = $empty_cell . "Magazine not uploaded!<br>";}if (!isset($_FILES["magazine_ereader"]) || $_FILES["magazine_ereader"]["size"] == 0){	$empty_cell = $empty_cell . "Magazine for e-readers not uploaded!<br>";}if (!isset($issue_num)){	$empty_cell = $empty_cell . "Please state the issue number!<br>";}if (!isset($issue_month) || $issue_month == '0'){	$empty_cell = $empty_cell . "Please state this ussue month!<br>";}if (!isset($issue_year) || $issue_year == '0'){	$empty_cell = $empty_cell . "Please state this issue year!<br>";}if (!isset($issue_theme)){	$empty_cell = $empty_cell . "Please state this issue main theme!<br>";}if (!isset($issue_desc)){	$empty_cell = $empty_cell . "Please describe this issue!<br>";}if ($empty_cell > 0){Here comes the rest of the code, with files type validation, uploading etc...}else	{		echo "<span class='message_error'>", $empty_cell, "</span>";	}

Well, it gives me some of the error messages, however it doesn't warn me about some cells being empty and even when they're all filled - I don't get the error message, but I also don't get the files uploaded, validated etc...

Link to comment
Share on other sites

OK, got the error! Now everything works! Here's what I changed:if (!isset($issue_num) || $issue_num == ''){ $empty_cell = $empty_cell . "Please state the issue number!<br>";}if (!isset($issue_theme) || $issue_theme == ''){ $empty_cell = $empty_cell . "Please state this issue main theme!<br>";}if (!isset($issue_desc) || $issue_desc == ''){ $empty_cell = $empty_cell . "Please describe this issue!<br>";}.....if (!isset($empty_cell))Again, thank you very much!!! :)

Link to comment
Share on other sites

no problem, PHP actually supports an operator to put a string on the end of a variable, so instead of doing:

$empty_cell = $empty_cell . "Magazine not uploaded!<br>";

you could also do:

$empty_cell .= "Magazine not uploaded!<br>";

or if you get tired of writing the <br> in every error, you could push the error text onto an array:

$errors = array();if (!isset($_FILES["magazine"]) || $_FILES["magazine"]["size"] == 0){	$errors[] = "Magazine not uploaded!";}...if (!sizeof($errors)) {}else {	foreach ($errors as $key => $error) $errors[$key] = htmlentities($error);	echo implode('<br>', $errors).'<br>';}

Link to comment
Share on other sites

no problem, PHP actually supports an operator to put a string on the end of a variable, so instead of doing:
$empty_cell = $empty_cell . "Magazine not uploaded!<br>";

you could also do:

$empty_cell .= "Magazine not uploaded!<br>";

or if you get tired of writing the <br> in every error, you could push the error text onto an array:

$errors = array();if (!isset($_FILES["magazine"]) || $_FILES["magazine"]["size"] == 0){	$errors[] = "Magazine not uploaded!";}...if (!sizeof($errors)) {}else {	foreach ($errors as $key => $error) $errors[$key] = htmlentities($error);	echo implode('<br>', $errors).'<br>';}

Thank you very much, James! Appreciate your help! I'll give this code a try!I'm new to PHP, it'll take time till I'll get the hang of it... Many more errors to come! :)
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...