Check 'X of 5' uploaded files for max size and type...NEWBIE

Disclaimer: I don’t know PHP. I stitch together what I can find and figure out.
So far I can capture user’s information from a form, validate user’s email, upload any files from the form, create and attach the files to an email. I’ve even managed to hack together error messages if the user’s email is missing or invalid.

Note: I have searched for, read through, and tried the suggestions in this forum but I’m not getting it to work. Your help is greatly appreciated.

Need help with:

  • checking that each image is of the correct type
  • checking that each image doesn’t exceed max size.

Q:

  • If the file fails either size or type validation does imagedestroy have to be run on the temp files?
  • Is there any way to not upload 0 byte images for any input files not attached in the html form?
  • Why am I having to include the $mail->addAttachment(‘includes/spacer.gif’); line above the ‘for’ in order to have $mail->addAttachment($uploadfile, $filename); that’s in the ‘for’ work

Here’s what I have thus far. What code is needed in order to achieve the desired steps and resolve the issue listed above (in a SAFE manner)?

<?php

$msg = '';
require 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['youremail'])){
	// Get person's information.
    $yourname = $_POST['yourname'];
    $youremail = $_POST['youremail'];
    $yourphone = $_POST['yourphone'];
    $content = $_POST['yourmessage'];
    $results_messages = array();

if(!PHPMailer::validateAddress($youremail)) {
  	$results_messages[] = "<p>UNSUCCESSFUL: Please go back and enter a valid email</p>";
} else {
   
	$bodytext = "Person's name: " . $yourname . "<br>Person's email: " . $youremail . "<br>Person's phone number: " . $yourphone . "<br>Person's message: <br>" . $content ;
 
	$mail = new PHPMailer(true);
	$mail->CharSet = 'utf-8';
	ini_set('default_charset', 'UTF-8');
 
	class phpmailerAppException extends phpmailerException {}
 
	try {
		$to = '<<MY EMAIL>>';
		$mail->isSMTP();
		// $mail->SMTPDebug  = 2;
		$mail->Host       = "xxx.secureserver.net"; // Yes, Godaddy. PIA but I got it to work!
		$mail->Port       = "465";
		$mail->SMTPSecure = "ssl";
		$mail->SMTPAuth   = true;
		$mail->Username   = "<<MY EMAIL>>";
		$mail->Password   = "<<MY PASSWORD>>";
		$mail->setFrom("<<MY EMAIL>>", "Website Contact Form");
		$mail->addAddress("<<MY EMAIL>>", "<<MY NAME>>");
		$mail->Subject  = "Inquiry (v31)";
		$body = $bodytext;
		$body .= <<<'EOT'
<br><br>
Pictures from user.<br>
EOT;
		$mail->WordWrap = 78;
		$mail->msgHTML($body, dirname(__FILE__), true);
		$mail->addAttachment('includes/spacer.gif'); 
		for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
        	$uploadfile = tempnam("uploads/", sha1($_FILES['userfile']['name'][$ct]));
        	$filename = $_FILES['userfile']['name'][$ct];
        	if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
            	$mail->addAttachment($uploadfile, $filename);
        	} else {
            	$msg .= 'Failed to move file to ' . $filename;
        	}
    	}

		try {
  			$mail->send();
  			$results_messages[] = "<p>Thank you.<br>Your message has been sent.<br>We will respond shortly.</p>";
		}
		catch (phpmailerException $e) {
  			throw new phpmailerAppException('Unable to send to: ' . $to. ': '.$e->getMessage());
		}
	}
	catch (phpmailerAppException $e) {
  		$results_messages[] = $e->errorMessage();
	}

}
} else {
	$results_messages[] = "<p>UNSUCCESSFUL: Please go back and enter a valid email</p>";
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="container">
	<p>
	<?php
			if (count($results_messages) > 0) {
				//  echo "<h2>Run results</h2>\n";
				echo "<ul>\n";
			foreach ($results_messages as $result) {
				echo "<li>$result</li>\n";
			}
				echo "</ul>\n";
			}
	?>
	</p>					
</div>
</body>
</html>

Need help with:

  • checking that each image is of the correct type
  • checking that each image doesn’t exceed max size.

I used this successfully:

<?php
// File types allowed on upload:
$allowed_exts = 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”] < 100000)
&& in_array($extension, $allowed_exts)) {
if ($_FILES[“file”][“error”] > 0) {
echo “Not allowed 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 filename: ” . $_FILES[“file”][“tmp_name”] . “<br>”;

Does this check each file from the html form?
Is 100000 in B or KB?
Forgive me, but isn’t your code missing a trailing } for the else?

If the answers to the questions above are – Yes, B, Yes – in theory I could do something like the following ???

<?php

// File types & size allowed on upload:
$allowed_exts = array('gif', 'jpeg', 'jpg', 'png', 'bmp');
$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/bmp')
|| ($_FILES['file']['type'] == 'image/png'))
&& ($_FILES['file']['size'] < 2100000)
&& in_array($extension, $allowed_exts)) {
if ($_FILES['file']['error'] > 0) {
	echo "Image too big or wrong type: " . $_FILES['file']['error'] . "<br>";
}
else {

// The rest of my code starting at $bodytext = ...

}

I gave the part I thought might pertain to your use case.I can give you the whole thing if you like.

If you don’t mind. I can’t seem to get it to work.
And, does the code check each file in the $_FILES array or is there a loop that’s needed?

Cheers!

Now that I think about it, since you are a PHP newbie, this might not make any sense to you at all. It’s from an article I wrote on my website on shooting a picture in your mobile device and uploading it to a server. This is a file on the server. I can’t tell you where all the instructions are lest it come across as spamming this site.

This is assuming one is uploading one photo.

<!- ********************* upload.php begin *********************** ->

<?php
// File types allowed on upload:
$allowed_exts = 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"] < 100000)
&& in_array($extension, $allowed_exts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Not allowed 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 filename: " . $_FILES["file"]["tmp_name"] . "<br>";

/**
CUSTOMIZE THE NAME OF THE FOLDER THAT THIS PHP UPLOAD.PHP SCRIPT RESIDES IN. Photos will be uploaded here.
uploads/
*/
if (file_exists("uploads/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
$timestamp = time();
move_uploaded_file($_FILES["file"]["tmp_name"],
$timestamp . "_" . $_FILES["file"]["name"]); // Add time to filename to minimize overwriting.
/**
CUSTOMIZE THE NAME OF THE FOLDER THAT THIS PHP UPLOAD.PHP SCRIPT RESIDES IN.
uploads/
*/
echo "Stored in: uploads/" . $_FILES["file"]["name"];
}
}
}
else {
echo "Sorry, invalid file upload (this is from upload.php).";
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8″ />
<title>Image Upload Page</title>
<style type="text/css">
li { font-size:1.5em; padding: .5em; }
</style>
</head>
<body>
<h2>Contents of the image file upload folder (this is from upload.php).</h2>
<h2>
<!- REMOVE NEXT THREE LINES FOR PRODUCTION. NOT FOR PUBLIC. ->
<?php
print_r($_FILES);
?>
</h2>
</body>
</html>

there is an excellent example in the manual of how to properly verify uploaded images:

http://php.net/manual/en/features.file-upload.php#114004

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.