We help IT Professionals succeed at work.

Server side validation (retaining variables)

353 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
Comment
Watch Question

Author

Commented:
Obviously I'm dropping the JavaScript part of the form.

Author

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
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
'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

Most Valuable Expert 2011
Author of the Year 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

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.

Author

Commented:
I am going to award you full credit but I may post questions. Thanks you're the master at this.

Author

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.
Most Valuable Expert 2011
Author of the Year 2014

Commented:
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.

Author

Commented:
I'm going to post finished code here and post individual questions. Thanks.
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Sounds good -- we'll be glad to help!
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
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.

Author

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.
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
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.

Author

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

Author

Commented:
And if I'm not mistaken I need to do this for every string input. Within the php

Author

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

Author

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.

Author

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.
Fixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

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).

Author

Commented:
Y'all are awesome
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
Thank you, good luck with your project.
Most Valuable Expert 2011
Author of the Year 2014

Commented:
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

Author

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.

Author

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.

Author

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.

Author

Commented:
I'll hit the book you recommended again. I'm skeptical I will find the answers in there.

Author

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.

Author

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.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.