Link to home
Start Free TrialLog in
Avatar of burnedfaceless
burnedfaceless

asked on

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
Avatar of burnedfaceless
burnedfaceless

ASKER

Obviously I'm dropping the JavaScript part of the form.
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
Avatar of Dave Baldwin
'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

SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
I am going to award you full credit but I may post questions. Thanks you're the master at this.
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.
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.
I'm going to post finished code here and post individual questions. Thanks.
Sounds good -- we'll be glad to help!
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.
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.
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.
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
And if I'm not mistaken I need to do this for every string input. Within the php
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
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.
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.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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).
Y'all are awesome
Thank you, good luck with your project.
This article will help you get started in your PHP adventures:
https://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
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.
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.
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.
I'll hit the book you recommended again. I'm skeptical I will find the answers in there.
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.
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.