Log in

View Full Version : PHP Form Validation



Rockonmetal
08-28-2007, 04:16 AM
Ok I know I have I think posted this everywhere except for on my own site, but I really need some help with this... I only got 10 days to get my site finished...
Ok, I need someone to help me make a validation script or something that will help make sure people won't send in blank forms...

<form action="uploader.php" method="post" enctype="multipart/data">
<input type="hidden" name="3p42r3ad3a4than32" value="329r8g" />
<div class="pureadd">
<br>
<br>Your Name:
<br><input type="text" name="Name" class="input" />
<br>Your Email:
<br><input type="text" name="Email" class="input"/>
<br>
<script type="text/javascript">
var d = new Date()
document.write("<input type='hidden' value='"+Date()+"' name='time' />")
</script>
<br>
<br>Agree To Terms of Service
<br><input type="checkbox" name="TermsOfService" value="Agreed" /> Yes I Agree To the Terms of Service
<br>

File Description:
<br>
<textarea rows="5" cols="40" name="description" id="maxcharfield" onKeyDown="textCounter(this,'progressbar1',200)" onKeyUp="textCounter(this,'progressbar1',200)" onFocus="textCounter(this,'progressbar1',200)" class="textarea"></textarea><br />
<div id="progressbar1" class="progress"></div>

<input type="submit" class="input">


</div>
</form>

I would like it so either that the form won't submit till the user has filled in all the fields. or some other way that you can do it I would be glad. please someone help me i'm very desperate, I swear if I don't get an answer to this I will have to cancel my site... no kidding... cancel it... PLEASE!!!!!!!!!!!!!!!!!!!!!!!!!!!

djr33
08-28-2007, 05:06 AM
http://www.dynamicdrive.com/dynamicindex16/requiredcheck.htm


And/or you could do this server side.


<?php

function checkvals($list) {
foreach ($list as $var) {
if (!isset($_POST[$var]) { return FALSE; }
if ($_POST[$var]=='') { return FALSE; }
}
return TRUE;
}
$vals = array('myfiled1','myotherfield',.....,'mylastfieldname');
if (!checkvals($vals)) { echo 'ERROR'; }

?>

I'm not sure how all/any browsers handle blank fields, so that accounts for either an empty string or a nonexistent value.
Assuming that they do submit a blank field as blank, you could pass $_POST to the function to check if any of them are blank.

This might not work on checkboxes, etc, as that would not necessarily be an empty string if left blank. Might want to play with that.

Rockonmetal
08-28-2007, 05:08 AM
Thanks man, i'll use the javascript version since it looks unfortunitly more promising...

Twey
08-28-2007, 08:03 AM
If you use the Javascript version, people can still upload blank forms (people with Javascript disabled won't even notice that it's there). You must have server-side checking as well.

Rockonmetal
08-28-2007, 12:20 PM
Ok, then should I use a php validation then *since this thread is called "PHP Form Validation..." But what i'm going to do is have the submit button in a document write script example:

<script type="text/javascript">
document.write('<input type="submit" class="button" />')
</script>

That way inorder for the user with javascript disabled it wouldn't allow them to submit a blank or invalid form...

boogyman
08-28-2007, 12:28 PM
Ok, then should I use a php validation then *since this thread is called "PHP Form Validation..." But what i'm going to do is have the submit button in a document write script example:

<script type="text/javascript">
document.write('<input type="submit" class="button" />')
</script>

That way inorder for the user with javascript disabled it wouldn't allow them to submit a blank or invalid form...

you don't need to do that and really, your site should be accessible whether they have javascript enabled or disabled. before you do anything else with the content you would sanitize and validate it. if everything passes your would then go ahead and process the information, but if there were required fields left blank you redirect them back to the form and display some type visual means of explaining what error'd out

Rockonmetal
08-28-2007, 12:55 PM
Thats the problem, I DON'T KNOW HOW TO DO THAT... *sorry, but i felt like making it big, sudden urges, followed by doubt...* but anyways could someone write me a validation that would validate the current script no matter whether their browser doesn't support javascript... like i said I HAVE NO IDEA HOW TO DO THAT *again sudden urges to make font big followed by, regret...* but please could someone help me by writing the script or telling me how to add/remove and what most parts do...

Twey
08-28-2007, 03:55 PM
That way inorder for the user with javascript disabled it wouldn't allow them to submit a blank or invalid form...It wouldn't let them submit a form at all (from that page, anyway). If they really wanted to send invalid data they could write their own form, enable Javascript then disable the validation with bookmarklets or something, or just send raw POST data, in order of required technical expertise.
I DON'T KNOW HOW TO DO THAT...That depends on the data and what you want to do with it. If you intend to display it in HTML, it needs to be passed through htmlentities(). If you intend to store it in a database, you need to use mysql_real_escape_string(). If it needs to be filled in, you need to pass it to empty() to check it. If it needs to be a number, you need is_numeric()... &c.

Rockonmetal
08-28-2007, 04:07 PM
Quote:
I DON'T KNOW HOW TO DO THAT...

That depends on the data and what you want to do with it. If you intend to display it in HTML, it needs to be passed through htmlentities(). If you intend to store it in a database, you need to use mysql_real_escape_string(). If it needs to be filled in, you need to pass it to empty() to check it. If it needs to be a number, you need is_numeric()... &c.

Again I sort of understand but I don't know how to do that... which again, is making me nuts...

All I ask is for someone to write php code that would check to see if all the inputs aren't empty, and that either a real email address or a possible real email address is there. I am having trouble understanding why people can't understand this... maybe i am not being clear... if so... please tell me... but if you do please help or say something!

djr33
08-28-2007, 06:48 PM
The script I wrote above will do just that.

The only thing you'd need to customize is the behavior when there is an error.

For validating an email, you can use preg_match() and a regex that will check the email.

Just use this line, then:
if (!checkvals($vals) || !preg_match($_POST['email'],'/^[^@]+@[^.]+(\.[^.]+)+$/')) { echo 'ERROR'; }

Rockonmetal
08-28-2007, 07:42 PM
Unfortunitly my Patentience had run out and I learned if else statements... and I wrote a little validation process but I need some help...

<html>
<body>
<?php
$input2 = $_POST["Name"];
$input3 = $_POST["Email"];
$input4 = $_POST["time"];
$input5 = $_POST["TermsOfService"];
$input6 = $_POST["3p42r3ad3a4than32"];
$input7 = $_POST["Title"];
$input8 = $_POST["Description"];
$input9 = $_POST["file1"];
$input10 = $_POST["file2"];
$empty = '';
$agree = 'Agreed';
$a = '329r8g';

?>
<?php
$c = '1';
$d = '0';
$valid = '5';
if ($empty == $input2) {
echo "Your Name cannot be blank.<br>";
} else {
++$d;
}

if ($empty == $input3) {
echo "Your EmailAddress cannot be blank.<br>";
} else {
++$d;
}
if ($empty == $input4) {
echo "Make sure your clock is set to the correct date, we record dates so we can know exactly when you submitted your files...<br>";
} else {
++$d;
}
if ($empty == $input5) {
echo "You must agree to the Terms Of Service.<br>";
} else {
++$d;
}
if ($empty == $input6) {
echo "There is an error with our form we are sorry for this problem we will fix it tomorrow.<br>";
} else {
++$d;
}
if ($d == $valid){
$upload_dir = "submitions/";
$num_files = 2;
//the file size in bytes.
$size_bytes =20480000; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".gif",".jpg",".jpeg",".png",".bmp",".mov",".mpg",".mpeg");


//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
die ("Error: The directory <b>($upload_dir)</b> doesn't exist because we are in the process of the weekly upload.");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
die ("Error: The directory <b>($upload_dir)</b> is NOT writable, Please click contact and then contact technical support to tell them this problem.");
}


//if the form has been submitted, then do the upload process
//infact, if you clicked on (Upload Now!) button.
if (isset($_POST['upload_form'])){

echo "<h3>Upload results:</h3>";

//do a loop for uploading files based on ($num_files) number of files.
for ($i = 1; $i <= $num_files; $i++) {

//define variables to hold the values.
$new_file = $_FILES['file'.$i];
$file_name = $new_file['name'];
//to remove spaces from file name we have to replace it with "_".
$file_name = str_replace(' ', '_', $file_name);
$file_tmp = $new_file['tmp_name'];
$file_size = $new_file['size'];

#-----------------------------------------------------------#
# this code will check if the files was selected or not. #
#-----------------------------------------------------------#

if (!is_uploaded_file($file_tmp)) {
//print error message and file number.
echo "File $i: Not selected.<br>";
}else{

$ext = strrchr($file_name,'.');
if (!in_array(strtolower($ext),$limitedext)) {
echo "File $i: ($file_name) Wrong file extension. <br>";
}else{


if ($file_size > $size_bytes){
echo "File $i: ($file_name) Faild to upload. File must be <b>". $size_bytes / 1024 ."</b> KB. <br>";
}else{


if(file_exists($upload_dir.$file_name)){
echo "File $i: ($file_name) already exists.<br>";
}else{

if (move_uploaded_file($file_tmp,$upload_dir.$file_name)) {
echo "File $i: ($file_name) Uploaded.<br>";
}else{
echo "File $i: Faild to upload.<br>";
}#end of (move_uploaded_file).

}#end of (file_exists).

}#end of (file_size).

}#end of (limitedext).

}#end of (!is_uploaded_file).

}#end of (for loop).
# print back button.
echo "»<a href=\"$_SERVER[PHP_SELF]\">back</a>";
////////////////////////////////////////////////////////////////////////////////
//else if the form didn't submitted then show it.
}else{
echo " <h3>Select files to upload!.</h3>
Max file size = ". $size_bytes / 1024 ." KB";
echo " <form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form-data\">";
// show the file input field based on($num_files).
for ($i = 1; $i <= $num_files; $i++) {
echo "File $i: <input type=\"file\" name=\"file". $i ."\"><br>";
}
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
<input type=\"submit\" name=\"upload_form\" value=\"Upload Now!\">
</form>";
}
$data = "<table border='1'>
<tr><td>User IP Address:</td><td>$input1</td></tr>
<tr><td>Name:</td><td>$input2</td></tr>
<tr><td>Email Address:<td>$input3</td></tr>
<tr><td>Date Submitted:</td><td>$input4</td></tr>
<tr><td>Description</td><td><textarea cols='50' rows='5'>$input6</textarea></td></tr>
<tr><td>File 1 Location:</td><td>$file1</td></tr>
<tr><td>File 2 Location:</td><td>$file2</td></tr></table>";


if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

// Write $somecontent to our opened file.
if (fwrite($handle, $data) === FALSE) {
echo "Cannot write to file";
exit;
}

echo "Success your information has been submitted! Now please submit your files...";

fclose($handle);

}
} else{
echo "You must fill out all fields properly";
}

What happens is even though all the input are valid the upload form does not show if someone could just help me with that, it would be fantastic THANKS!

boogyman
08-28-2007, 08:19 PM
give me an hour and ill write up something. i get out in 30min and when i get home ill write you up a generic one that will
sanitize / validate and redisplay w/ errors or process. and you will just need to fill in your code.

djr33
08-28-2007, 08:30 PM
I wrote a very easy function to use. I have no idea why you need something else. All you do is fill in the array, and you're done.
You could also include in the function an echo "$val cannot be left blank.".

If you do need to have a custom message for each field, then you will just need to use if statements. Or you could setup a multidimensional array for the function I wrote and use [0] as the name and [1] as the error message. //shrug

Rockonmetal
08-28-2007, 09:01 PM
Ok, thanks boogyman i really appreciate it!

boogyman
08-28-2007, 11:24 PM
<?php
$usremail = ""; // the name attribute of the users email. eg <input name="email"> would be email
$submit = "" // the name attribute of the submit input button. <input type="submit" name="submit" would be submit

if (isset($_REQUEST[$submit])) {
$err_list = validate_form();
if ($err_list) ? display_form($err_list) : process_form();
}
else {
display_form();
}

function validate_form() {
$err_list = array();
foreach($_REQUEST as $key => $value) {
if( !isset($value) || $value === '')
$err_list[] = "The {$key} field is required!";
}
if( !preg_match("/^[A-z0-9_\-.]+[@][A-z0-9_\-.]+([.][A-z0-9_\-]+)+[A-z]{2,4}$/", $_REQUEST[$usremail]) )
{
$err_list[] = "Your email is not valid";
}
// your other individual sanitation
}
return $err_list;
}

function display_form($err_list = "") {
if ($err_list) {
print "<p>Please correct these errors and try again\n<ul>";
foreach ($err_list as $err) {
print "<li>{$err}</li>";
}
print "</ul></p>";
}
?>
<!--
********************************
** YOUR FORM CONTENT **
********************************
-->
<form name="something" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<!-- blah blah -->
</form>

<?php
}


function process_form() {
/**
**
** YOUR ACTUAL PROCESS CODE
**
**/
}

?>


if you have any questions about something let me know

Rockonmetal
08-29-2007, 12:03 AM
I think I might have messed up something because I only got a blank page...
Theres the code below... if you got any advice on how to fix this let me know

<html>
<head>
<script type="text/javascript" src="script.js" /></script>
<style type="text/css">
.input{
background: url(input.png) no-repeat;
width: 184px;
color: #000000;
font-family: Tahoma;
height: 24px;
border: none;
padding: 4px 4px 4px 4px;
font-size: 12px;
}
.textarea{
background: url(textarea.png) no-repeat;
border: none;
width: 250px;
height: 200px;
padding: 3px 3px 3px 3px;
overflow: hidden;
font-family: Tahoma;
font-size: 11px;
}
.progress{
width: 50px;
height: 24px;
color: white;
font-size: 12px;
font-family: Tahoma;
background: #000000 url(loader.gif) x-repeat;
overflow: hidden;
padding-left: 5px;


}

</style>

<script type="text/JavaScript" src="textprogress.js"></script>
</style>
</head>
<body>
<?php
$usremail = "Email"; // the name attribute of the users email. eg <input name="email"> would be email
$submit = "Submit" // the name attribute of the submit input button. <input type="submit" name="submit" would be submit

if (isset($_REQUEST[$submit])) {
$err_list = validate_form();
if ($err_list) ? display_form($err_list) : process_form();
}
else {
display_form();
}

function validate_form() {
$err_list = array();
foreach($_REQUEST as $key => $value) {
if( !isset($value) || $value === '')
$err_list[] = "The {$key} field is required!";
}
if( !preg_match("/^[A-z0-9_\-.]+[@][A-z0-9_\-.]+([.][A-z0-9_\-]+)+[A-z]{2,4}$/", $_REQUEST[$usremail]) )
{
$err_list[] = "Your email is not valid";
}
// your other individual sanitation
}
return $err_list;
}

function display_form($err_list = "") {
if ($err_list) {
print "<p>Please correct these errors and try again\n<ul>";
foreach ($err_list as $err) {
print "<li>{$err}</li>";
}
print "</ul></p>";
}
?>
<form name="something" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<input type="hidden" name="3p42r3ad3a4than32" value="329r8g" />
<div class="pureadd">
<br>
<br>Your Name:
<br><input type="text" name="Name" class="input" value=""/>
<br>Your Email:
<br><input type="text" name="Email" class="input" value=""/>
<br>
<br>Your File's Title:
<br><input type="text" name="Title" class="input" value=""/>
<br>
<script type="text/javascript">
var d = new Date()
document.write("<input type='hidden' value='"+Date()+"' name='time' />")
</script>
<br>
<br>Agree To Terms of Service
<br><input type="checkbox" name="TermsOfService" value="Agreed" /> Yes I Agree To the Terms of Service
<br>

File Description:
<br>
<textarea rows="5" cols="40" name="Description" id="maxcharfield" onKeyDown="textCounter(this,'progressbar1',200)" onKeyUp="textCounter(this,'progressbar1',200)"

onFocus="textCounter(this,'progressbar1',200)" class="textarea"></textarea><br />
<div id="progressbar1" class="progress"></div>

<input type="submit" class="input">
</form>

<?php
}


function process_form() {
<html>
<body>
$input2 = $_POST["Name"];
$input3 = $_POST["Email"];
$input4 = $_POST["time"];
$input5 = $_POST["TermsOfService"];
$input6 = $_POST["3p42r3ad3a4than32"];
$input7 = $_POST["Title"];
$input8 = $_POST["Description"];
$input9 = $_POST["file1"];
$input10 = $_POST["file2"];
$empty = '';
$agree = 'Agreed';
$a = '329r8g';
$c = '1';
$d = '0';
$valid = '5';
if ($empty == $input2) {
echo "Your Name cannot be blank.<br>";
} else {
++$d;
}

if ($empty == $input3) {
echo "Your EmailAddress cannot be blank.<br>";
} else {
++$d;
}
if ($empty == $input4) {
echo "Make sure your clock is set to the correct date, we record dates so we can know exactly when you submitted your files...<br>";
} else {
++$d;
}
if ($empty == $input5) {
echo "You must agree to the Terms Of Service.<br>";
} else {
++$d;
}
if ($empty == $input6) {
echo "There is an error with our form we are sorry for this problem we will fix it tomorrow.<br>";
} else {
++$d;
}
if ($d == $valid){
$upload_dir = "submitions/";
$num_files = 2;
//the file size in bytes.
$size_bytes =20480000; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".gif",".jpg",".jpeg",".png",".bmp",".mov",".mpg",".mpeg");


//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
die ("Error: The directory <b>($upload_dir)</b> doesn't exist because we are in the process of the weekly upload.");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
die ("Error: The directory <b>($upload_dir)</b> is NOT writable, Please click contact and then contact technical support to tell them this problem.");
}


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

echo "<h3>Upload results:</h3>";

//do a loop for uploading files based on ($num_files) number of files.
for ($i = 1; $i <= $num_files; $i++) {

//define variables to hold the values.
$new_file = $_FILES['file'.$i];
$file_name = $new_file['name'];
//to remove spaces from file name we have to replace it with "_".
$file_name = str_replace(' ', '_', $file_name);
$file_tmp = $new_file['tmp_name'];
$file_size = $new_file['size'];

#-----------------------------------------------------------#
# this code will check if the files was selected or not. #
#-----------------------------------------------------------#

if (!is_uploaded_file($file_tmp)) {
//print error message and file number.
echo "File $i: Not selected.<br>";
}else{

$ext = strrchr($file_name,'.');
if (!in_array(strtolower($ext),$limitedext)) {
echo "File $i: ($file_name) Wrong file extension. <br>";
}else{


if ($file_size > $size_bytes){
echo "File $i: ($file_name) Faild to upload. File must be <b>". $size_bytes / 1024 ."</b> KB. <br>";
}else{


if(file_exists($upload_dir.$file_name)){
echo "File $i: ($file_name) already exists.<br>";
}else{

if (move_uploaded_file($file_tmp,$upload_dir.$file_name)) {
echo "File $i: ($file_name) Uploaded.<br>";
}else{
echo "File $i: Faild to upload.<br>";
}#end of (move_uploaded_file).

}#end of (file_exists).

}#end of (file_size).

}#end of (limitedext).

}#end of (!is_uploaded_file).

}#end of (for loop).
# print back button.
echo "»<a href=\"$_SERVER[PHP_SELF]\">back</a>";
////////////////////////////////////////////////////////////////////////////////
//else if the form didn't submitted then show it.
}else{
echo " <h3>Select files to upload!.</h3>
Max file size = ". $size_bytes / 1024 ." KB";
echo " <form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form-data\">";
// show the file input field based on($num_files).
for ($i = 1; $i <= $num_files; $i++) {
echo "File $i: <input type=\"file\" name=\"file". $i ."\"><br>";
}
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
<input type=\"submit\" name=\"upload_form\" value=\"Upload Now!\">
</form>";
}
$data = "<table border='1'>
<tr><td>User IP Address:</td><td>$input1</td></tr>
<tr><td>Name:</td><td>$input2</td></tr>
<tr><td>Email Address:<td>$input3</td></tr>
<tr><td>Date Submitted:</td><td>$input4</td></tr>
<tr><td>Description</td><td><textarea cols='50' rows='5'>$input6</textarea></td></tr>
<tr><td>File 1 Location:</td><td>$file1</td></tr>
<tr><td>File 2 Location:</td><td>$file2</td></tr></table>";


if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

// Write $somecontent to our opened file.
if (fwrite($handle, $data) === FALSE) {
echo "Cannot write to file";
exit;
}

echo "Success your information has been submitted! Now please submit your files...";

fclose($handle);

}
} else{
echo "You must fill out all fields properly";
}

}

?>


I really don't know what todo...

boogyman
08-29-2007, 03:17 AM
well you have used a hog poch of my code along with the code you already had.... use the template that I gave you... insert the parts into their correct location as I commented then see what you get.. if you have a question about where something belongs I will answer it... but I gave you a template, not a plug all your code in here... post...

so take the 2 minutes to sift through my code... look at the comments and apply as necessary

Rockonmetal
08-29-2007, 03:23 AM
By sanitation you mean...


// your other individual sanitation

boogyman
08-29-2007, 03:52 AM
yes... like if you wanted to check if one of the inputs was within a certain range...


if ($empty == $input3) {
echo "Your EmailAddress cannot be blank.<br>";
} else {
++$d;
}
if ($empty == $input4) {
echo "Make sure your clock is set to the correct date, we record dates so we can know exactly when you submitted your files...<br>";
} else {
++$d;
}
if ($empty == $input5) {
echo "You must agree to the Terms Of Service.<br>";
} else {
++$d;
}
if ($empty == $input6) {
echo "There is an error with our form we are sorry for this problem we will fix it tomorrow.<br>";
} else {
++$d;
}

is both redundant and breaks the template...
I already checked in the template for any values that were empty / had no contents in them... then it will store any of those into an array


function validate_form() {
$err_list = array();
foreach($_REQUEST as $key => $value) {
if( !isset($value) || $value === '')
{
$err_list[] = "The {$key} field is required!";
}
if( !preg_match("/^[A-z0-9_\-.]+[@][A-z0-9_\-.]+([.][A-z0-9_\-]+)+[A-z]{2,4}$/", $_REQUEST[$usremail]) )
{
$err_list[] = "Your email is not valid";
}
// your other individual sanitation
}
return $err_list;
}

is the only place you should be looking to grab something from the client side..
I did have a typo in there... though which would break the script

however if you look closely the part in blue is checking everything that is sent to the server to process. If it is empty / has no value then its put into the $errr_list Array and the form will be redisplayed to the user with the errors at the top...

you printing out the errors is really not being constructive.

let me go thru and see if i can be a little bit more clearer than i was before





if (isset($_REQUEST[$submit])) {
}
else {
display_form();
}


checks if form has been submitted... if not its the first time there so print out the form



$err_list = validate_form();


defines the $err_list variable .... and sanitizes the data...



if ($err_list) ? display_form($err_list) : process_form();

checks to see if there are any errors... if yes redisplay the original form with the errors, if not process the form and continue on with the script.





function validate_form() {
$err_list = array();
foreach($_REQUEST as $key => $value) {
if( !isset($value) || $value === '')
$err_list[] = "The {$key} field is required!";
}
if( !preg_match("/^[A-z0-9_\-.]+[@][A-z0-9_\-.]+([.][A-z0-9_\-]+)+[A-z]{2,4}$/", $_REQUEST[$usremail]) )
{
$err_list[] = "Your email is not valid";
}
// your other individual sanitation
}
return $err_list;
}

takes everything passed to and checks if its empty or contains nothing. if so write an error.
the next part is checking the email itself, because that has some special sanitation that needs to be performed on it.
then you can use the format above to check something else(this would be a good point to check if the file is a supported type)

after all that is done, the $err_list array is returned.... now it is defaulted as empty, and will only be populated when an error occurs above. on your page you were checking each individual post sent to the server, which is fine, but unless you are checking for something other than whether its empty there is no point in creating a custom error message for each of them... hence the foreach loop




function display_form($err_list = "") {
if ($err_list) {
print "<p>Please correct these errors and try again\n<ul>";
foreach ($err_list as $err) {
print "<li>{$err}</li>";
}
print "</ul></p>";
}
?>
<!--
********************************
** YOUR FORM CONTENT **
********************************
-->
<form name="something" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<!-- blah blah -->
</form>

<?php
}


this will check if there is anything inside the $err_list array, if there is then it will display them at the top and the rest of the form gets parsed next, regardless.

with the exception of the (action="<?php $_SERVER[PHP_SELF] ?>") this should contain ONLY html code... NOTHING ELSE





function process_form() {
/**
**
** YOUR ACTUAL PROCESS CODE
**
**/
}



this is where you would upload / do whatever you need to do with the script to get it to do what you want, but you shouldn't be trying to sanitize it in any way..

now as a side note... you still check for errors in processing, however you should collect those errors into an array and then go back and display the errors all at once.


there, now i think i have steered you in a better direction...

Rockonmetal
08-30-2007, 04:13 PM
I'm sorry boogyman but I am just really busy and my original question was for someone to tell me what is wrong with this code I have right here...


<html>
<body>
<?php
$input2 = $_POST["Name"];
$input3 = $_POST["Email"];
$input4 = $_POST["time"];
$input5 = $_POST["TermsOfService"];
$input6 = $_POST["3p42r3ad3a4than32"];
$input7 = $_POST["Title"];
$input8 = $_POST["Description"];
$input9 = $_POST["file1"];
$input10 = $_POST["file2"];
$empty = '';
$agree = 'Agreed';
$a = '329r8g';

?>
<?php
$c = '1';
$d = '0';
$valid = '5';
if ($empty == $input2) {
echo "Your Name cannot be blank.<br>";
} else {
++$d;
}

if ($empty == $input3) {
echo "Your EmailAddress cannot be blank.<br>";
} else {
++$d;
}
if ($empty == $input4) {
echo "Make sure your clock is set to the correct date, we record dates so we can know exactly when you submitted your files...<br>";
} else {
++$d;
}
if ($empty == $input5) {
echo "You must agree to the Terms Of Service.<br>";
} else {
++$d;
}
if ($empty == $input6) {
echo "There is an error with our form we are sorry for this problem we will fix it tomorrow.<br>";
} else {
++$d;
}
if ($d == $valid){
$upload_dir = "submitions/";
$num_files = 2;
//the file size in bytes.
$size_bytes =20480000; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".gif",".jpg",".jpeg",".png",".bmp",".mov",".mpg",".mpeg");


//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
die ("Error: The directory <b>($upload_dir)</b> doesn't exist because we are in the process of the weekly upload.");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
die ("Error: The directory <b>($upload_dir)</b> is NOT writable, Please click contact and then contact technical support to tell them this problem.");
}


//if the form has been submitted, then do the upload process
//infact, if you clicked on (Upload Now!) button.
if (isset($_POST['upload_form'])){

echo "<h3>Upload results:</h3>";

//do a loop for uploading files based on ($num_files) number of files.
for ($i = 1; $i <= $num_files; $i++) {

//define variables to hold the values.
$new_file = $_FILES['file'.$i];
$file_name = $new_file['name'];
//to remove spaces from file name we have to replace it with "_".
$file_name = str_replace(' ', '_', $file_name);
$file_tmp = $new_file['tmp_name'];
$file_size = $new_file['size'];

#-----------------------------------------------------------#
# this code will check if the files was selected or not. #
#-----------------------------------------------------------#

if (!is_uploaded_file($file_tmp)) {
//print error message and file number.
echo "File $i: Not selected.<br>";
}else{

$ext = strrchr($file_name,'.');
if (!in_array(strtolower($ext),$limitedext)) {
echo "File $i: ($file_name) Wrong file extension. <br>";
}else{


if ($file_size > $size_bytes){
echo "File $i: ($file_name) Faild to upload. File must be <b>". $size_bytes / 1024 ."</b> KB. <br>";
}else{


if(file_exists($upload_dir.$file_name)){
echo "File $i: ($file_name) already exists.<br>";
}else{

if (move_uploaded_file($file_tmp,$upload_dir.$file_name)) {
echo "File $i: ($file_name) Uploaded.<br>";
}else{
echo "File $i: Faild to upload.<br>";
}#end of (move_uploaded_file).

}#end of (file_exists).

}#end of (file_size).

}#end of (limitedext).

}#end of (!is_uploaded_file).

}#end of (for loop).
# print back button.
echo "»<a href=\"$_SERVER[PHP_SELF]\">back</a>";
////////////////////////////////////////////////////////////////////////////////
//else if the form didn't submitted then show it.
}else{
echo " <h3>Select files to upload!.</h3>
Max file size = ". $size_bytes / 1024 ." KB";
echo " <form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form-data\">";
// show the file input field based on($num_files).
for ($i = 1; $i <= $num_files; $i++) {
echo "File $i: <input type=\"file\" name=\"file". $i ."\"><br>";
}
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
<input type=\"submit\" name=\"upload_form\" value=\"Upload Now!\">
</form>";
}
$data = "<table border='1'>
<tr><td>User IP Address:</td><td>$input1</td></tr>
<tr><td>Name:</td><td>$input2</td></tr>
<tr><td>Email Address:<td>$input3</td></tr>
<tr><td>Date Submitted:</td><td>$input4</td></tr>
<tr><td>Description</td><td><textarea cols='50' rows='5'>$input6</textarea></td></tr>
<tr><td>File 1 Location:</td><td>$file1</td></tr>
<tr><td>File 2 Location:</td><td>$file2</td></tr></table>";


if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

// Write $somecontent to our opened file.
if (fwrite($handle, $data) === FALSE) {
echo "Cannot write to file";
exit;
}

echo "Success your information has been submitted! Now please submit your files...";

fclose($handle);

}
} else{
echo "You must fill out all fields properly";
}


I think it happens when its right here

if ($d == $valid){

Please if someone could help me I don't need someone to write me a whole new section of code, I just need someone to tell me what is wrong and please don't get mad at me I REALLY DON'T HAVE TIME! I got till September 8th! 8th! To get this done:
3+ More forms like this *hopefully because if this one gets fixed I'll be able to do it my self*
Probably 10 more pages to write
A terms of service
Start making cellphone friendly pages...

But I also have to get back to school to so thats like only 4 days to do that... Eek!
Please If someone could just tell me what is wrong with my php code above...
And I swear to you guys I won't ever be this rude again!