Hi everyone and thanks for reading. I'm having problems validating the file size of my uploads. With my current script, If I upload anything that is over 2Mb, I keep getting the error about file types rather than the ones about the file size. Even if I dont submit anything, I still get the one about the file type. Why are the other errors not showing too? They're separate if statements. It must be something to do with my syntax. I've listed the code below anyway:

<html>
<head>
<title>Upload File To File Server</title>
</head>

<body>
<?
// $uploadDir is relative to the form because if you use a slash at the start it doesn't work.
// $uploadDirMySQL will be for the HTML to call and it should work fine.
$uploadDir = '../../images/photos/';
$uploadDirMySQL = "/images/photos/";

if (isset($_POST['upload'])) {

if (($_FILES["userfile"]["type"] == "image/gif") || ($_FILES["userfile"]["type"] == "image/jpeg") || ($_FILES["userfile"]["type"] == "image/pjpeg") || ($_FILES["userfile"]["type"] == "image/png") && ($_FILES['userfile']['size'] > 0) && ($_FILES['userfile']['size'] < 2000000)) {

	$fileName = $_FILES['userfile']['name'];
	$tmpName  = $_FILES['userfile']['tmp_name'];
	$fileSize = $_FILES['userfile']['size'];
	$fileType = $_FILES['userfile']['type'];

    // the files will be saved in filePath
    $filePath = $uploadDir . $fileName;
	$filePathMySQL = $uploadDirMySQL . $fileName;

    // move the files to the specified directory
	// if the upload directory is not writable or
	// something else went wrong $result will be false
    $result    = move_uploaded_file($tmpName, $filePath);
	if (!$result) {
		echo "Error uploading file";
		exit;
	}
	
    include 'config.php';
    include 'opendb.php';

    if(!get_magic_quotes_gpc())
    {
        $fileName  = addslashes($fileName);
        $filePath  = addslashes($filePath);
	$filePathMySQL = addslashes($filePathMySQL);
    }

	$query = "INSERT INTO upload2 (name, size, type, path ) ".
			 "VALUES ('$fileName', '$fileSize', '$fileType', '$filePathMySQL')";

    mysql_query($query) or die('Error, query failed : ' . mysql_error());

    include 'closedb.php';
    
    echo "<p>File uploaded successfully:<br />";
	echo "Name: " . $_FILES["userfile"]["name"] . " <br />";
	echo "Size: " . round(($_FILES["userfile"]["size"] / 1024)) . " KB<br />";
	echo "Type: " . $_FILES["userfile"]["type"] . "</p>";
} else {

if ($_FILES["userfile"]["size"] = 0) {
echo "<p>There was a problem uploading your file. Either the file is broken or you did not ask to upload anything. The file size is apparently 0kb which is impossible.</p>";
}

if ($_FILES["userfile"]["size"] > 2000000) {
echo "<p>There was a problem uploading your file. The file is too large. The limit is 2MB and your file was over that. Try uploading a smaller file.</p>";
}

if (($_FILES["userfile"]["type"] != "image/gif") || ($_FILES["userfile"]["type"] != "image/jpeg") || ($_FILES["userfile"]["type"] != "image/pjeg") || ($_FILES["userfile"]["type"] != "image/png")) {
echo "<p>There was a problem uploading your file. The file type was not correct. You can only upload <strong>jpg</strong>, <strong>gif</strong> or <strong>png</strong>.</p>";
}

} // This one closes the main part of the script.
} // This one closes the top if statement which checks to see if the upload button was clicked or not.
?>
<form action="" method="post" enctype="multipart/form-data" name="uploadform">
  <table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
    <tr> 
      <td width="246"><input type="hidden" name="MAX_FILE_SIZE" value="2000000"><input name="userfile" type="file" class="box" id="userfile">
		 </td>
      <td width="80"><input name="upload" type="submit" class="box" id="upload" value="  Upload  "></td>
    </tr>
  </table>
</form>
</body>
</html>

Thanks for reading!

Anthony

Recommended Answers

All 7 Replies

Your problem is in the first if-statement:

if ($_FILES["userfile"]["size"] = 0)

You are using an assignment here rather than the comparator == as I think you mean. In PHP though, your statement is legal, just that it will always be evaluated to false (and thus will never cause the code block following it to execute).

As for not getting the error when you upload a 2MB file, I'm not sure what is happening there, especially since 2000000 bytes < 2MB (which is 2 * 2 ^20 = 2 * 1024 * 1024). I would suggest doing the following to see exactly what is happening when you upload a file:

print_r($_FILES);
exit;

Executing this code will print the FILES array and might give you a clue as to why your code is not behaving as you would like.

Hope this has helped,
darkagn :)

commented: Helpful +1

Your problem is in the first if-statement:

if ($_FILES["userfile"]["size"] = 0)

You are using an assignment here rather than the comparator == as I think you mean. In PHP though, your statement is legal, just that it will always be evaluated to false (and thus will never cause the code block following it to execute).

As for not getting the error when you upload a 2MB file, I'm not sure what is happening there, especially since 2000000 bytes < 2MB (which is 2 * 2 ^20 = 2 * 1024 * 1024). I would suggest doing the following to see exactly what is happening when you upload a file:

print_r($_FILES);
exit;

Executing this code will print the FILES array and might give you a clue as to why your code is not behaving as you would like.

Hope this has helped,
darkagn :)

Hi darkagn,

Thanks for the heads up on the comparison statement, I totally hadn't seen I was missing a second equals sign. That error validation now works perfectly but I'm still stuck about the over two megabyte error. Can you explain the formula you typed in you last message, sorry it's just I don't understand it.

I took your suggestion and got this:

Array ( [userfile] => Array ( [name] => DSC_0932.JPG [type] => [tmp_name] => [error] => 2 [size] => 0 ) )

The file I tried to upload was 2.15Mb

Thanks,

Anthony

I decided to water down the code in hope that someone will be able to spot the problem better (and the problem is that my IF statements for catching files over 2mb won't work!). Here goes:

<html>
<head>
<title>Upload File To File Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<?
// $uploadDir is relative to the form because if you use a slash at the start it doesn't work.
// $uploadDirMySQL will be for the HTML to call and it should work fine.
$uploadDir = '../../images/photos/';
$uploadDirMySQL = "/images/photos/";

if (isset($_POST['upload'])) {

if ((($_FILES["userfile"]["type"] == "image/gif") || ($_FILES["userfile"]["type"] == "image/jpeg") || ($_FILES["userfile"]["type"] == "image/pjpeg") || ($_FILES["userfile"]["type"] == "image/png")) && ($_FILES['userfile']['size'] > 0) && ($_FILES['userfile']['size'] < 2000000)) {

	$fileName = $_FILES['userfile']['name'];
	$tmpName  = $_FILES['userfile']['tmp_name'];
	$fileSize = $_FILES['userfile']['size'];
	$fileType = $_FILES['userfile']['type'];
    $filePath = $uploadDir . $fileName;

    // If the file doesn't already exist, then move it to the specified directory. 
	if (file_exists("../../images/photos/" . $fileName)) {
      echo "<p>Sorry, but the filename: <strong>" . $fileName . " </strong> already exists. Please rename it and try again.";
	  die; } else {
	  move_uploaded_file($tmpName, $filePath);
	  }
  
      echo "<p>File Uploaded Successfully:<br>";
      echo "Name: " . $_FILES["userfile"]["name"] . " <br>";
      echo "Size: " . round(($_FILES["userfile"]["size"] / 1024)) . " KB<br>";
      echo "Type: " . $_FILES["userfile"]["type"] . "</p>";
  } else {

if ($_FILES["userfile"]["size"] == 0) {
echo "<p>There was a problem uploading your file. Either the file is broken or you did not ask to upload anything. The file size is apparently 0kb. Please try again.</p>";
}

if ($_FILES["userfile"]["size"] > 2000000) {
echo "<p>There was a problem uploading your file. The file is too large. The limit is 2MB and your file was over that. Try uploading a smaller file.</p>";
}

if ((($_FILES["userfile"]["type"] != "image/gif") || ($_FILES["userfile"]["type"] != "image/jpeg") || ($_FILES["userfile"]["type"] != "image/pjpeg") || ($_FILES["userfile"]["type"] != "image/png")) && ($_FILES["userfile"]["size"] > 0)) {
echo "<p>There was a problem uploading your file. The file type was not correct. You can only upload <strong>jpg</strong>, <strong>gif</strong> or <strong>png</strong>.</p>";
}

} // This one closes the main part of the script.

} // This one closes the top if statement which checks to see if the upload button was clicked or not.
?>
<form action="" method="post" enctype="multipart/form-data" name="uploadform">
  <table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
    <tr> 
      <td width="246">
	    <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
		<input name="userfile" type="file" class="box" id="userfile" size="100">
	  </td>
      <td width="80">
	  <br><br>
	    <input name="upload" type="submit" class="box" id="upload" value="  Upload  ">
	  </td>
    </tr>
  </table>
</form>
</body>
</html>

Just a little update for anyone willing to help. I changed the IF statement to check is the file size is over 20 bytes. Here's some results:

PSD
1.00Mb
I get both an error message for wrong file type and that size is too big.

MP3
2.26Mb (Bear in mind that PHP is set to over 20 bytes but the html has still got MAX_FILE_SIZE set to 2000000)
I get wrong file type but i get the zero file size message.

My conclusion is that for some reason, if the file size is over 2mb, it's not even getting uploaded properly and the resulting file size is of course zero.

Any ideas?

Thanks,

Anthony

Actually the problem here is your PHP script doesn't allows you to upload more than 2MB file. if the size exceeds over 2MB it will not get uploaded.

if you want to show error regarding file size just use $_FILES.
if($_FILES==2) then it means the file size get exceeded.

Hi and thanks for the reply.

You're right, I looked at the print_r($_FILES) and the file size on something that is too big is 0, which means it's not getting uploaded. I'll just use the if err==2 statement and make a generic message about file size.

Thanks!

I think you should bring some changes on your php.ini file, because be default php does not allow to post more than 2MB for uploading, so you need to search for the below line in php.ini:
; Maximum size of POST data that PHP will accept.
post_max_size = 2M

and change the size as you like, hope it is ok

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.