• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 312
  • Last Modified:

Server side validation (retaining variables)

Here's what I'm going for...some text (that should be easy) but assuming we have to reload the page how do we keep variables for customer.

<?php
   
$result=TRUE;      
   
 function check_email($email)
      {
      
            if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
            $result = FALSE; //enter text here
      }
//  return $result; probably unnecessary to return variable if can write within the function
}

      

      if (strlen($first) > 0)
      {
            $result = FALSE;//enter text
      }
      if (strlen($last) > 0)
      {
            $result = FALSE;//enter text
      }
      if (strlen($from) > 0)
      {
            $result = FALSE;//enter text
      }
      if (strlen($addy) > 0)
      {
            $result = FALSE;
      }
      if (strlen($reason) > 0)
      {
            $result = FALSE;
      }
      if (strlen($message) > 0)
      {
            $result = FALSE;
      }
      
      
      
?>

<form name = "contact" id = "contact" method = "post" action = "php/mailer.php" onSubmit = "return validate ();">      
      <fieldset id = "contactinformation">            
      <legend>Your Information</legend>            
      <label class = "blocklabel">            
            First Name:      <input type = "text" id = "fname" name = "fname" /><br/>            
      </label>            
      <label class = "blocklabel">            
            Last Name: <input type = "text" id = "lname" name = "lname" /><br/>            
      </label>            
      <label class = "blocklabel">            
            Email Address: <input type = "text" id = "email" name = "email" /><br/>            
      </label>            
      <label class = "blocklabel">            
            Mailing address: <input type = "text" id = "address" name = "address">            
      </label>            
      For what reason are you contacting us?<br/>                  
      <input type = "radio" id = "complaint" name = "ts" value = "Complaint" />Complaint                  
      <input type = "radio" id = "inquiry" name = "ts" value = "Inquiry" />Inquiry                  
      <input type = "radio" id = "comment" name = "ts" value ="Comment" />Comment                  
      <input type = "radio" id = "other" name = "ts" value = "Other" />Other      
      </fieldset>      
      <fieldset id = "message">            
            <legend>Enter your message below</legend>            
            <textarea name="comments" cols="40" rows="5"></textarea><br/>      
      </fieldset>            
      <input type = "submit" value = "Submit" />      <input type = "reset" value = "Clear" />
      </form>

edited to put result variable before function
0
burnedfaceless
Asked:
burnedfaceless
  • 20
  • 5
  • 4
2 Solutions
 
burnedfacelessAuthor Commented:
Obviously I'm dropping the JavaScript part of the form.
0
 
burnedfacelessAuthor Commented:
Also I'm trying to learning something here - different form submits? I'm assuming you validate and mail in one php file.

But I will award the most points to whomever really teaches me.

Thanks
0
 
Dave BaldwinFixer of ProblemsCommented:
'eregi' is DEPRECATED as of PHP 5.3.0 and will be removed in some future version.  'preg_match' http://us3.php.net/manual/en/function.preg-match.php is probably what you should use though there is added syntax.

Here is my PHP Email demo with both javascript and basic server side checking.  Save it as "Email.php" and put your own email address in for the $toText.
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');

# some settings of POST vars
if (!isset($_POST['submit']))  $submit = ''; else $submit = $_POST['submit'];
if (!isset($_POST['subjectText'])) $subjectText = ''; else $subjectText = $_POST['subjectText'];
if (!isset($_POST['msgText'])) $msgText = ''; else $msgText = $_POST['msgText'];
if (!isset($_POST['ccText'])) $ccText = ''; else $ccText = $_POST['ccText'];
if (!isset($_POST['bccText'])) $bccText = ''; else $bccText = $_POST['bccText'];
if (!isset($_POST['nameText'])) $nameText = ''; else $nameText = $_POST['nameText'];
if (!isset($_POST['fromText'])) $fromText = ''; else $fromText = $_POST['fromText'];

if ($submit == "") {
    $title="Test Email Page";
    $announce="---";
}
else {
	if($fromText === "") die("No name!");
  $toText="youremail@yourdomain.com";
	$title="Test Email Page";
  $announce="Your Message has been Sent!";
	$header = "From: ".$fromText."\r\n";
//	$header .= "Cc: ".$ccText."\n";
	$header .= "Reply-To : ".$fromText."\r\n";
	$header .= "Return-Path : ".$fromText."\r\n";
	$header .= "X-Mailer: PHP\r\n";
	$header .= "MIME-Version: 1.0\r\n";
	$header .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
//	ini_set(sendmail_from,$fromText);  
	mail($toText, $subjectText, $msgText, $header, '-f'.$fromText);
//	ini_restore(sendmail_from);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title><?php echo($title)?></title>
<style type="text/css">
<!-- 
A:link { color: #999999; }
A:visited { color: #999999; }
A:hover {color: #0099ff;}
-->
</style>
<script type="text/javascript">
<!--
function check()
{
var at=document.getElementById("fromText").value.indexOf("@");
var eml=document.getElementById("fromText").value;
var nam=document.getElementById("nameText").value;
var alerttxt="";
var submitOK="true";

if (eml.length < 5 || at == -1)
    {
    alerttxt=alerttxt+"Please enter a valid e-mail address!\r\n";
    submitOK="false"
    //return false;
    }
if (nam.length < 3)
    {
    alerttxt=alerttxt+"Please enter your name.\r\n";
    submitOK="false"
    //return false;
    }
if (submitOK=="false")
    {
    alert(alerttxt);
    return false;
    }

}
// -->
</script>
</head>

<body bgcolor="#ddeedd">
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" summary="" width="580">
<tr><td align="center">

<?php
if ($submit != "") {
   	echo ("To: ".$toText."<br>\r\nSubject: ".$subjectText."<br>\r\n".$msgText."<br>\r\n".$header);
		}
?>

<p><b><font color="#000000" size="5">Test Email</font></b></p>
<font size="4" color="#000000">

<form method="POST" action="Email.php" onsubmit="return check();">
    <p><font size="3"><b>Name: <input type="text" name="nameText" id="nameText" size="46"></b></font></p>
    <p><font size="3"><b>Email: <input type="text" name="fromText" id="fromText" size="46"></b></font></p>
    <input type="hidden" name="subjectText" value="Web Mail">
    <p><font face="Arial" size="3"><b>Message Text:</b></font></p>
    <p><font face="Arial" size="3"><b><textarea rows="6" name="msgText" cols="60"></textarea></b></font></p>
    <p><font size="3"><b><input type="submit" value="submit" name="submit" style="font-family: Arial; font-size: 12pt; font-weight: bold"></b></font></p>
    <input type="hidden" name="state" value="1">
  </form>
  <b><font face="Arial" size="4" color="#e00000"><?php echo($announce)?></font></b><br><br>

</font>
</td></tr>
</table> 
</div>

</body>
</html>

Open in new window

0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
Ray PaseurCommented:
Throw away the check_email() function!  That looks like something from 1998.  You want to learn about PHP filter_var() that can handle all kinds of filtering and sanitizing of the external data.  You also want to read the PHP manual on security and dealing with external data, because all external data is tainted and a potential attack vector.
http://php.net/manual/en/tutorial.forms.php
http://php.net/manual/en/language.variables.external.php
http://php.net/manual/en/security.php

Here is my teaching example showing the general design pattern for handling client input.  It preserves any of the input that is valuable, rejects the input that is unusable, and gives the client a good visual indicator of success or failure.

Please see: http://www.laprbass.com/RAY_form_highlight_errors.php

<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// WE TURN THE FORM BORDER RED
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

HTH, ~Ray
0
 
burnedfacelessAuthor Commented:
Ray is it required to have the html form embedded in the php or is this your example?

Is it desirable?

edit: sorry adhd have to read a few times

please let me know about form inside php and i'll read your links.
0
 
burnedfacelessAuthor Commented:
I am going to award you full credit but I may post questions. Thanks you're the master at this.
0
 
burnedfacelessAuthor Commented:
I actually noticed Dave's comment too. Let me try to do something and I will divide points. I plan to post what I code, however long that takes.
0
 
Ray PaseurCommented:
required to have the html form embedded in the php
Not required, but I find it very, very useful.  It lets you create templates in the PHP code where variable substitution happens easily.
Is it desirable?
I think so. Especially with forms and action scripts, keeping the two together in a single script file helps keep my work organized.
0
 
burnedfacelessAuthor Commented:
I'm going to post finished code here and post individual questions. Thanks.
0
 
Ray PaseurCommented:
Sounds good -- we'll be glad to help!
0
 
Dave BaldwinFixer of ProblemsCommented:
Especially for a demo, it's easier to keep it all in one page.  In practice, it depends on what you need.  I've done a lot of form pages where all the user ever sees is HTML pages. The PHP page is essentially invisible because it doesn't display anything.  When it's done, it redirects to another HTML page.  But for a demo, that's a lot of files and explaining.
0
 
burnedfacelessAuthor Commented:
OK here's what I'm trying to do. I'm working out of bootstrap which, while it has limitations is probably the best for consistent display.

The form is nothing complex. It's a means for customers to contact us. But I want it to be secure.

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
 
The above code- would that have to be with php embedded on the page? I do know a little about hiding extensions, l can find my book.

Right now I'm concerned about functionality and security. I don't want JavaScript popups.

This site is a great resource and I appreciate your help very much.
0
 
Dave BaldwinFixer of ProblemsCommented:
I don't know why hiding extension would make any difference here or anywhere for that matter.  It doesn't increase your security in any way that I know of.

As you were told before, javascript on the form page on the client is not for security.  It is to help get the form filled out correctly.  It is better to have a pop-up to remind them to fill in their email address than it is to reject it on the server because they forgot.  If it starts with "<?php", then it must be a '*.php' page / file or the server will not run it thru the interpreter.

On the server side in addition to making sure that all the variables are initialized, I often make sure they are between a minimum and a maximum length.  I started doing that when people would dump a whole web page into my forms.  I also check to see if there are unwanted links in the message.
0
 
burnedfacelessAuthor Commented:
If I am not mistaken html special chars prevents html code from being inserted. I need to get the syntax down. Not sure if I'll use one page or two.

edit: isn't limited to embedded if i'm correct
0
 
burnedfacelessAuthor Commented:
And if I'm not mistaken I need to do this for every string input. Within the php
0
 
burnedfacelessAuthor Commented:
So I will write out an algorithm for verification.

1. Store all form inputs to variables. The isset David posted would prevent php errors.
2. Run them through html special chars
3. Then make sure all fields are entered
4. Validate email
5. Write desired errors with css

Please correct if wrong

edit: the confusing part is passing variables onto the next page i'll start coding and assume no response means that this is a start
0
 
burnedfacelessAuthor Commented:
Here's what I've got. I deviated from the algorithm a little. Is there a problem with using string length?

We don't have a database so we shouldn't be worried about mysql, correct?

Anything to make this better would be awesome. I'm going to work on something else before I try to tackle loading the page with an invalid submission. Let me know if this is sufficient.

I realize this is a lot of work for one question.
0
 
burnedfacelessAuthor Commented:
ehh it didn't attach

<?php


      $flag = TRUE;
      
      $first = htmlspecialchars($_POST['fname']);
      $last = htmlspecialchars($_POST['lname']);
      $from = htmlspecialchars($_POST['email']);
      $addy = htmlspecialchars($_POST['address']);
      $reason = htmlspecialchars($_POST['ts']);
      $message = htmlspecialchars($_POST['comments']);
      
            if (filter_var($from, FILTER_VALIDATE_EMAIL))
                  {$flag = TRUE; }
            else
                  {$flag = FALSE;}
            
            if (strlen($first) == 0)
            {
                  $flag = FALSE;
            }
            if (strlen($last) == 0)
            {
                  $flag = FALSE;
            }
            if (strlen($from) == 0)
            {
                  $flag = FALSE;
            }
            if (strlen($addy) == 0)
            {
                  $flag = FALSE;
            }
            if (strlen($reason) == 0)
            {
                  $flag = FALSE;
            }
            if (strlen($message) == 0)
            {
                  $flag = FALSE;
            }
            
            if ($flag == TRUE)
            {
                  echo "valid form submission";
            }
            else
            {
                  echo "invalid form submission";
            }
            
                  
            
            
            
?>

edit: In my opinion the boolean and my goal of giving individual messages may have been poorly thought out.
0
 
Dave BaldwinFixer of ProblemsCommented:
The reason for using 'isset' is partly lazy so I don't have to think about it and partly practical because checkboxes and radiobuttons do not send any data if they aren't checked on the form.  Using my method to check 'isset' and give them a default value prevents errors due to missing array indexes in the $_POST array.

The thing about string length is to limit the length when people post long irrelevant text like complete web pages into your forms.  Yes they do that.

For dates and states, I use <select> statements with dropdowns to make sure I get the data in the correct format.  You can put examples on the form page and people will still do something different.

After you've done and fixed 40 or 50 forms with PHP pages, you'll have a better sense of what works for you.  I have code that I use that will automatically generate all those "if(!isset..." statements from a form page.  Then I just copy and paste it into my PHP page.
0
 
burnedfacelessAuthor Commented:
Thanks for your response David. I will award points soon.

Based on the relative rather than absolute positioning where would I display my error messages? Well it seems to be structured on generic elements so I will award you and Ray and keep trucking. Java and cigarettes (and some beer to reward myself).
0
 
burnedfacelessAuthor Commented:
Y'all are awesome
0
 
Dave BaldwinFixer of ProblemsCommented:
Thank you, good luck with your project.
0
 
Ray PaseurCommented:
This article will help you get started in your PHP adventures:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

Thanks for using EE, ~Ray
0
 
burnedfacelessAuthor Commented:
I've read through a lot of that. I've worked through books. It's not a hard language. It's C based for Christ sake. It's more how it interacts with html etc.

I'll read the security stuff in detail.
0
 
burnedfacelessAuthor Commented:
See these books give examples but they don't give me what I need. It's watered down.

I've studied C based languages formally. It's the interaction thing.
0
 
burnedfacelessAuthor Commented:
Yea we don't run a database I'm not sure how this would apply to us.

Case 1 not relevant
Case 2 good information but i believe you can't access a .php file by default (on our server)
case 3 very relevant kind of paranoid might look into that
case 4 not going to do that

This is a limited use of PHP. I'm trying to get this done and as we store nothing on a database I'm trying to just get the form without the annoying popups.
0
 
burnedfacelessAuthor Commented:
I'll hit the book you recommended again. I'm skeptical I will find the answers in there.
0
 
burnedfacelessAuthor Commented:
I am going to work through Build your own database driven web site using php & mysql again.

I've forgotten some of it and didn't feel it desirable to integrate it into the pages. But it will probably be desirable.

Unfortunately he no longer has his scripts available online.
0
 
burnedfacelessAuthor Commented:
Yea going back to the books helped, it really has been two years. Thanks for the security good information.

There is a lot you can do with php it really is amazing.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 20
  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now