Jump to content

Recommended Posts

Hey guys. I have 8 image upload fields in my form and I want to put a size limit of 3MB for each of the 8 images they upload. If the image is over 3MB, I want it to say "error-file size too large", when they try and submit. I am just learning PHP, and this one has me stumped. I will include the html and the 3 relevant PHP files. Thanks

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<form action="/php_form_script2/process.php?id=1" name="ContactForm1" id="ContactForm1" onsubmit="return false;" method="post" enctype="multipart/form-data">
<table style="font-family:Arial; font-size:12px; color:#000000" bgcolor="#FFFFFF">
<tr>
<td>First Name *</td>
<td><input type='text' value='' size='30' name='field1'></td>
</tr>
<tr>
<td>Last Name *</td>
<td><input type='text' value='' size='30' name='field2'></td>
</tr>
<tr>
<td>E-mail *</td>
<td><input type='text' value='' size='30' name='field3'></td>
</tr>
<tr>
<td>image upload *</td>
<td><input type='file' value='' size='30' name='field12'></td>
</tr>
<tr>
<td>image upload</td>
<td><input type='file' value='' size='30' name='field13'></td>
</tr>
<tr>
<td>image upload</td>
<td><input type='file' value='' size='30' name='field14'></td>
</tr>
<tr>
<td>image upload</td>
<td><input type='file' value='' size='30' name='field15'></td>
</tr>
<tr>
<td>image upload</td>
<td><input type='file' value='' size='30' name='field16'></td>
</tr>
<tr>
<td>image upload</td>
<td><input type='file' value='' size='30' name='field17'></td>
</tr>
<tr>
<td>image upload</td>
<td><input type='file' value='' size='30' name='field18'></td>
</tr>
<tr>
<td>image upload</td>
<td><input type='file' value='' size='30' name='field19'></td>
</tr>
<tr>
<td>Verification:</td>
<td valign="middle"><img src="/php_form_script2/captcha.php" align="absmiddle"  /><input name="captchacode" type="text" size="5" /></td>
</tr>	
<tr>
<td> </td>
<td><input type="submit" name="SubmitBtn" onclick="CheckForm1();" value="Send message" /></td>
</tr>
</table>
</form>
<script language="javascript" src='/php_form_script2/validation.php?id=1'></script>



</body>
</html>

 

Below = "process.php"

 

<?php
/*
#3.0.0 2009 05 21
# 
# Script: process.php
*/
error_reporting(0);
session_start();
include("options.php");

function xmail ($email_address, $email_cc, $email_bcc, $email_from, $subject, $msg, $attach_filepath, $want_attach){  
       $b = 0;  
       $mail_attached = "";  
       $boundary = "000XMAIL000";  
       if (count($attach_filepath)>0 && $want_attach) {  
           for ($a=0;$a<count($attach_filepath);$a++) { 
               if ($fp=fopen($attach_filepath[$a],"rb")) {  
                   $file_name=basename($attach_filepath[$a]);  
                   $content[$b]=fread($fp,filesize($attach_filepath[$a]));  
                   $mail_attached.="--".$boundary."\n"  
                       ."Content-Type: binary/octet-stream; name=\"$file_name\"\n"  
                       ."Content-Transfer-Encoding: base64\n"  
                       ."Content-Disposition: inline; filename=\"$file_name\"\n\n"  
                       .chunk_split(base64_encode($content[$b]))."\n";  
                   $b++;  
                   fclose($fp);  
               };  
           }  
           $mail_attached .= "--".$boundary."\n";  
           $add_header ="MIME-Version: 1.0\n"."Content-Type: multipart/mixed; boundary=\"$boundary\"; Message-ID: <".md5($email_from).">";  
           $mail_content="--".$boundary."\n"."Content-Type: text/plain; charset=\"UTF-8\"\n"."Content-Transfer-Encoding: 8bit\n\n".$msg."\n\n".$mail_attached;  
           return mail($email_address, $subject, $mail_content, "From: ".$email_from."\nCC: ".$email_cc."\nBCC: ".$email_bcc ."\nErrors-To: ".$email_from."\n".$add_header);  
       } else {  
           return mail($email_address, $subject, $msg, "From: ".$email_from."\nCC: ".$email_cc."\nBCC: ".$email_bcc ."\nErrors-To: ".$email_from); 
       }  
} 

if(strtoupper($_POST['captchacode']) !== strtoupper($_SESSION['captcha_id'])) {
echo "<center><br><br><br>Incorrect verification code. <A HREF='javascript:history.go(-1)'>Go back</a></center>.";
} else {

$sql = "SELECT * FROM ".$TABLES["FORMS"]." WHERE ID ='".$_REQUEST["id"]."'";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
$OPTIONS = mysql_fetch_assoc($sql_result);
$TO = $OPTIONS["SEND_TO"];
$FROM = $OPTIONS["SEND_TO"];
$subject = $OPTIONS["SUBJECT"];
$redirect = $OPTIONS["THANK_YOU_PAGE"];

$MESSAGE_BODY = "";
$regexp='/^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/';  

$sql = "SELECT * FROM ".$TABLES["FORM_FIELDS"]."
         	WHERE FORM_ID = '".$_REQUEST["id"]."' 
        ORDER BY FIELD_ORDER ASC";
$sql_resultF = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
while ($FIELD = mysql_fetch_assoc($sql_resultF)) {
	$temp = 'field'.$FIELD["ID"];
	if($FIELD["FIELD_TYPE"]=="FileBox"){
		$Files[] = 	'field'.$FIELD["ID"];
		$MESSAGE_BODY .= str_replace('"','"',stripslashes(utf8_decode($FIELD["TITLE"]))).": ".$_FILES['field'.$FIELD["ID"]]['name']."<br />\r\n";
	} else {
		$MESSAGE_BODY .= str_replace('"','"',stripslashes(utf8_decode($FIELD["TITLE"]))).": ".stripslashes(($_REQUEST[$temp]))."<br />\r\n";
		if (preg_match($regexp, trim($_REQUEST[$temp]))) {
			$FROM = trim($_REQUEST[$temp]);
		};
	}	
};

$MESSAGE_FOOTER ="\r\n\r\n<br><br>---------------------------------------<br>\r\n";
$access_ip = (getenv(HTTP_X_FORWARDED_FOR)) ?  getenv(HTTP_X_FORWARDED_FOR) :  getenv(REMOTE_ADDR);
$MESSAGE_FOOTER .="IP address: $access_ip\r\n<br>";
$MESSAGE_FOOTER .="Server time: ".date("F j, Y, g:i a")."\r\n<br>";


if(count($Files)>0){
	foreach($Files as $filename){
		if (is_uploaded_file($_FILES[$filename]['tmp_name']))  {  
			if(move_uploaded_file($_FILES[$filename]['tmp_name'], $SETTINGS["uploadDir"].$_FILES[$filename]['name'])) {
				chmod($SETTINGS["uploadDir"].$_FILES[$filename]['name'],0777); 
				$attach_filepath[] = $SETTINGS["uploadDir"].$_FILES[$filename]['name'];
			};
		};
	}	
	$MESSAGE_BODY .= $MESSAGE_FOOTER;
	xmail ($TO, '', '', $FROM, $subject, $MESSAGE_BODY, $attach_filepath, true);
	header("Location: $redirect");

} else {
	$mailheader = "From: $FROM\r\n";
	$mailheader .= "Reply-To: $FROM\r\n";
	$mailheader .= "Content-type: text/html; charset=UTF-8\r\n";

	$MESSAGE_BODY .= $MESSAGE_FOOTER;
	mail($TO, $subject, $MESSAGE_BODY, $mailheader) or die ("Failure");
	header("Location: $redirect");
}
};
?>

 

Below = "options.php"

 

<?php 
error_reporting(0);
$SETTINGS["installFolder"]='/php_form_script2/';
$SETTINGS["installURL"]='cinematiccorp.com/php_form_script2/';
$SETTINGS["path"]='/var/chroot/home/content/c/i/n/cinematiccorp/html/php_form_script2/';
$SETTINGS["admin_username"]='kmk16';
$SETTINGS["admin_password"]='hidden';
$SETTINGS["mysql_user"]='kmk16';
$SETTINGS["mysql_pass"]='hidden';
$SETTINGS["hostname"]='kmk16.db.5042809.hostedresource.com';
$SETTINGS["mysql_database"]='kmk16';


$SETTINGS["uploadDir"] = 'uploads/';
$SETTINGS["pageSize"] = 25;
$SETTINGS["useCookie"] = false;
//////////////////
//////////////////
//////////////////
////////////////// DO NOT CHANGE BELOW
//////////////////
//////////////////
$SETTINGS["version"] = '3.0';
$SETTINGS["scriptid"] = '16';

$TABLES["FORM_FIELDS"] = 'contact_form_fields';
$TABLES["FORMS"] = 'contact_forms';

if ($install != '1') {
$connection = mysql_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('request "Unable to connect to MySQL server."');
$db = mysql_select_db($SETTINGS["mysql_database"], $connection) or die ('request "Unable to select database."');
};

$monthnames_arr = Array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$fonts_arr = Array("Arial", "Century", "Courier New", "Serif", "Tahoma", "Times New Roman", "Verdana");
?>

 

Below = "validation.php"

 

<?php
error_reporting(0);
include("options.php");

$sql = "SELECT * FROM ".$TABLES["FORM_FIELDS"]."
		WHERE FORM_ID = '".$_REQUEST["id"]."'  
		ORDER BY FIELD_ORDER ASC";
$sql_resultF = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
while ($FIELD = mysql_fetch_assoc($sql_resultF)) {
	$field_data = unserialize($FIELD["DATA"]);
	if ($field_data["mandatory"]=='1') { 
		if ($FIELD["FIELD_TYPE"]=='EditBox' or $FIELD["FIELD_TYPE"]=='TextArea' or $FIELD["FIELD_TYPE"]=='DropDown' or $FIELD["FIELD_TYPE"]=='FileBox') {
			$MANDATORY[]="field".$FIELD["ID"];  /// build array for javascript validation 
		} elseif($FIELD["FIELD_TYPE"]=='RadioButtons'){
			$Radio_MANDATORY[]="field".$FIELD["ID"];  /// build array of radio buttons for javascript validation 
		} elseif($FIELD["FIELD_TYPE"]=='CheckBox'){
			$CheckBox_MANDATORY[]="field".$FIELD["ID"];  /// build array of radio buttons for javascript validation 
		} 
	}
}	


echo "
	function ValidateForm".$_REQUEST["id"]."(){	
		var flag = true;
		var message = 'Please fill in all mandatory fields !';

		if(http.readyState == 4)	{
			var showcheck = http.responseText;
			if (showcheck=='0') {
				message = 'Incorrect verification code!';
			  	flag = false;
			};

		";


		for ($i=0; $i<count($MANDATORY); $i++) {
echo "			
		if (document.ContactForm".$_REQUEST["id"].".".$MANDATORY[$i].".value.length==0){
		  	flag = false;
		}; \n";
		};

		for ($i=0; $i<count($CheckBox_MANDATORY); $i++) {
echo "			
		if (document.ContactForm".$_REQUEST["id"].".".$CheckBox_MANDATORY[$i].".checked==false){
			flag = false;
		}; \n";
		};

		for ($i=0; $i<count($Radio_MANDATORY); $i++) {
echo "			
		var radioBtnChecked = false;
		for (j=0; j<document.ContactForm".$_REQUEST["id"].".".$Radio_MANDATORY[$i].".length; j++) {
			if (document.ContactForm".$_REQUEST["id"].".".$Radio_MANDATORY[$i]."[j].checked==true){
				radioBtnChecked = true;	
				break;	
				}	
			}	

		if (radioBtnChecked==false){
			flag = false;
		};";
		};

echo "		
		if (flag == false) {
			alert(message);
		} else {
			document.ContactForm".$_REQUEST["id"].".submit();
		};

		};

	};";
?>
function createRequestObject(){
try	{
	xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
}	catch(e)	{
	alert('Sorry, but your browser doesn\'t support XMLHttpRequest.');
};
return xmlhttp;
};

var http = createRequestObject();

function CheckForm<?php echo $_REQUEST["id"]; ?>() {
var captchacheck = document.ContactForm<?php echo $_REQUEST["id"]; ?>.captchacode.value;
var url = '<?php echo $SETTINGS["installFolder"]; ?>captcha-process.php?captcha=' + captchacheck;
http.open('GET', url, true);
http.onreadystatechange = ValidateForm<?php echo $_REQUEST["id"]; ?>;
http.send(null);
};

In the $_FILES superglobal array there is an index with the file size in bytes. you could do the following

//get the size
$size = $_FILES['size'];
$size *= 1024;//now size is in kilobytes
$size *= 1024;//now its in megabytes
$max (1024)*(1024)*8;//1024 bytes in a kilobyte, 1024 kilobytes in a megabyte, then times 8 for 8 megabytes

//you could do the following conditional to test if the file is too big
if ($size < $max){
//upload the file
}
else {
echo "File too large!";
exit();
}
// other stuff

if(count($Files)>0){
	foreach($Files as $filename){
		if (is_uploaded_file($_FILES[$filename]['tmp_name']))  {  
			if(move_uploaded_file($_FILES[$filename]['tmp_name'], $SETTINGS["uploadDir"].$_FILES[$filename]['name'])) {
				chmod($SETTINGS["uploadDir"].$_FILES[$filename]['name'],0777); 
				$attach_filepath[] = $SETTINGS["uploadDir"].$_FILES[$filename]['name'];
			};
		};
	}

 

this area

Thanks again for the reply. I put it in like this:

 

if(count($Files)>0){
	foreach($Files as $filename){
		if (is_uploaded_file($_FILES[$filename]['tmp_name']))  {  
			if(move_uploaded_file($_FILES[$filename]['tmp_name'], $SETTINGS["uploadDir"].$_FILES[$filename]['name'])) {
				chmod($SETTINGS["uploadDir"].$_FILES[$filename]['name'],0777); 
				$attach_filepath[] = $SETTINGS["uploadDir"].$_FILES[$filename]['name'];
				$size = $_FILES['size'];
$size *= 1024;//now size is in kilobytes
$size *= 1024;//now its in megabytes
$max (1024)*(1024)*8;//1024 bytes in a kilobyte, 1024 kilobytes in a megabyte, then times 8 for 8 megabytes

//you could do the following conditional to test if the file is too big
if ($size < $max){
//upload the file
}
else {
echo "File too large!";
exit();
}
			};
		};
	}	

 

It try to test it by uploading a 4MB image, and when I submit, it just goes to a blank white page. It did not go to my server or my email address though. Seems like it is not displaying the error "file to large" message. The script is located here: http://cinematiccorp.com/php_form_script2/cinematicform.html

um, you werent supposed to just copy and paste in in there.

if(count($Files)>0){
	foreach($Files as $filename){
		if (is_uploaded_file($_FILES[$filename]['tmp_name']))  {  
$size *= 1024;//now size is in kilobytes
$size *= 1024;//now its in megabytes
$max (1024)*(1024)*8;//1024 bytes in a kilobyte, 1024 kilobytes in a megabyte, then times 8 for 8 megabytes

//you could do the following conditional to test if the file is too big
if ($size < $max){//upload the file
if(move_uploaded_file($_FILES[$filename]['tmp_name'], $SETTINGS["uploadDir"].$_FILES[$filename]['name'])) {
//stuff below
}//end if(move_uploaded
}//end if($size < $max)				
else {
echo "File too large!";
exit();

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.