Solved

Server side validation (retaining variables)

Posted on 2013-11-21
29
286 Views
Last Modified: 2013-11-24
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
Comment
Question by:burnedfaceless
  • 20
  • 5
  • 4
29 Comments
 

Author Comment

by:burnedfaceless
ID: 39666521
Obviously I'm dropping the JavaScript part of the form.
0
 

Author Comment

by:burnedfaceless
ID: 39666532
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
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39666641
'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
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39666752
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
 

Author Comment

by:burnedfaceless
ID: 39667079
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
 

Author Comment

by:burnedfaceless
ID: 39667104
I am going to award you full credit but I may post questions. Thanks you're the master at this.
0
 

Author Comment

by:burnedfaceless
ID: 39667180
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
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39667248
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
 

Author Comment

by:burnedfaceless
ID: 39667258
I'm going to post finished code here and post individual questions. Thanks.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39667268
Sounds good -- we'll be glad to help!
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39667329
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
 

Author Comment

by:burnedfaceless
ID: 39667376
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
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39667445
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
 

Author Comment

by:burnedfaceless
ID: 39667463
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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:burnedfaceless
ID: 39667468
And if I'm not mistaken I need to do this for every string input. Within the php
0
 

Author Comment

by:burnedfaceless
ID: 39667486
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
 

Author Comment

by:burnedfaceless
ID: 39667675
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
 

Author Comment

by:burnedfaceless
ID: 39667676
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
 
LVL 82

Accepted Solution

by:
Dave Baldwin earned 250 total points
ID: 39667731
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
 

Author Comment

by:burnedfaceless
ID: 39667758
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
 

Author Closing Comment

by:burnedfaceless
ID: 39667762
Y'all are awesome
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39667777
Thank you, good luck with your project.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39667903
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
 

Author Comment

by:burnedfaceless
ID: 39667921
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
 

Author Comment

by:burnedfaceless
ID: 39667923
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
 

Author Comment

by:burnedfaceless
ID: 39667935
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
 

Author Comment

by:burnedfaceless
ID: 39667944
I'll hit the book you recommended again. I'm skeptical I will find the answers in there.
0
 

Author Comment

by:burnedfaceless
ID: 39671961
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
 

Author Comment

by:burnedfaceless
ID: 39673097
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

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now