homepage Welcome to WebmasterWorld Guest from 54.166.105.24
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Not sure of proper syntax
new to PHP
CSS_Kidd




msg:3891564
 6:31 pm on Apr 13, 2009 (gmt 0)

So I am new to php and I have only used downloaded scripts to create simple contact forms. However, I have a contact form that my employer wants to be more detailed. My problem is that looking around at tutorials I havent found anything but simple php forms that are not consistent with others. They all seem to have there own way of doing it. So I kind of made one up on my own. I am not to sure if I got the syntax just right. I cant test it completely with out putting it out on our server and my employer will not do that until its complete. So just for argument sake lets say that option doesnt even exist. Anyways here is my form and php code...

FORM:

<form name="form1" method="post" action="process.php">
<input name="firstname" type="text" id="firstname" size="50">
<br />
<input name="lastname" type="text" id="lastname" size="50">
<br />
<input name="address1" type="text" id="address1" size="50">
<br />
<input name="address2" type="text" id="address2" size="50">
<br />
<input name="city" type="text" id="city" size="50">
<br />
<select name="state" id="state">
<option selected>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<br />
<input name="zip" type="text" id="zip" size="50">
<br />
<input name="email" type="text" id="email" size="50">
<br />
<input name="phone" type="text" id="phone" size="22" maxlength="12">
<br />
<input type="submit" name="submit" id="submit" value="Submit">
<input type="reset" name="reset" id="reset" value="Reset">
</form>

PROCESS.PHP

<?php

if (isset($_POST[Submit])){

// Begin Form Input Variables
$firstname = stripslashes($_POST['firstname']);
$lastname = stripslashes($_POST['lastname']);
$address1 = stripslashes($_POST['address1']);
$address2 = stripslashes($_POST['address2']);
$city = stripslashes($_POST['city']);
$state = stripslashes($_POST['state']);
$zip = stripslashes($_POST['zip']);
$email = stripslashes($_POST['email']);
$phone = stripslashes($_POST['phone']);
// End Form Input Variables

//Message Body
$body = "Contact Information:<br />";
$body .= "<p>First Name: ".$firstname."";
$body .= "Last Name: ".$lastname."</p>";
$body .= "Address: ".$address1."<br />";
$body .= "Apt. or Suite: ".$address2."<br />";
$body .= "City: ".$city."<br />";
$body .= "State: ".$state."<br />";
$body .= "Zip: ".$zip."<br />";
$body .= "Email Address: ".$email."<br />";
$body .= "Phone: ".$phone."<br />";
//End Message Body

//Send
$to='me@someplace.com';
$subject="Contact Info";
//$header= (would like to have the contacts' email address in the "from" field for quick replies)
$message="$body";
mail($to,$subject,$message,$header);

if($send_contact){
echo "Contact Info Sent";
}
else {
echo "ERROR message";
}

}

?>

Just two things I need to know right now. Is it formed correctly? And Will the $body work for the $message input, or does it need to be formed a different way? Also later I want to do some validation. So any tips on that would be helpful. Remember I am new to php, so please keep it simple as can be.

Thanks

 

BenjArriola




msg:3891610
 7:47 pm on Apr 13, 2009 (gmt 0)

Since you have no email headers stating that this is in an HTML format, I believe you will have some trouble with the <br>. If you have a plain email sent out, you new lines should be \r\n

As for validation, I think most people today like JavaScript validation than PHP validation since they do not need to wait for the page to reload to find out they did something wrong on the form.

CSS_Kidd




msg:3891614
 7:51 pm on Apr 13, 2009 (gmt 0)

Gottcha... But is this ok to do and will this work:

$message="$body";

BenjArriola




msg:3891628
 8:43 pm on Apr 13, 2009 (gmt 0)

This would work:

$message="$body";
mail($to,$subject,$message,$header);

This would work too:

$message=$body;
mail($to,$subject,$message,$header);

Or you can do this:

mail($to,$subject,$body,$header);

CSS_Kidd




msg:3891630
 8:50 pm on Apr 13, 2009 (gmt 0)

And was I right in guessing it would group together all the $body s into the message area:

$body = "Contact Information:\n\n";
$body .= "First Name: ".$firstname."\n";
$body .= "Last Name: ".$lastname."\n";
and so on

BenjArriola




msg:3891690
 11:12 pm on Apr 13, 2009 (gmt 0)

Yes

rocknbil




msg:3891744
 12:44 am on Apr 14, 2009 (gmt 0)

Couple things.

if($send_contact){
echo "Contact Info Sent";
}
else {
echo "ERROR message";
}

Nowhere in your script do I see where "$send_contact" is set. So whatever happens, it's always going to output "ERROR MESSAGE" when it's done.

Second, you can do more with the "contact sent" by using some of the input variables for a better message (You're probably planning on this . . . ) As for error, I don't see any error checking, so hopefully that's also for later.

Third, don't give up on HTML email, but don't use <br/>. That's XHTML, and a break tag, even in email, is a "stupid web trick" when you don't know any better. Use standard html elements, and simplify your code - note the line by line concatenation is not necessary with scalar variables.

Sticking with HTML will allow you to do this (and wow your boss)

$home='http://example.com';

$foot = "
<hr>
<p style=\"text-align:center\"><a href=\"$home\">$home</a>
<hr>
";

$body = "
<h4>Contact Information:</h4>
<p>First Name $firstname</p>
<p>Last Name: $lastname</p>
<p>Address: $address1</p>
<p>Apt. or Suite: $address2</p>
<p>City: $city</p>
<p>State: $state</p>
<p>Zip: $zip</p>
<p>Email Address: $email</p>
<p>Phone: $phone</p>
<p>&nbsp;</p>
$foot
";

In truth, since it's a list, a <ul> styled with no dots is better but the above will get you started.

Outputting HTML is easy. In the header below, the mime and content type are most important.

//Send
$to='me@someplace.com';
$subject="Contact Info";
$message="$body";

$from = '"' . "$firstname $lastname" . '" <' . $email . '>';
// The above sends "John Smith" <test@example.com>
// Boss is twice impressed . . .

$header = "From: $from\r\n";
$header .= 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

mail($to,$subject,$message,$header);

I think most people today like JavaScript validation than PHP validation since they do not need to wait for the page to reload to find out they did something wrong on the form.

Use both. A spammer/hacker sends data directly to a form processor and never sees the form, opening a hole for you. Whatever you do in Javascript, duplicate in your PHP script.

Although it's too early to introduce this, where you have "else error" - this should be a copy of your form, with the input values prepopulated, if there's any error.

CSS_Kidd




msg:3892021
 1:21 pm on Apr 14, 2009 (gmt 0)

Wow thanks Rockinbil and BenjArriola. This is all pretty much the idea I had. My only problem this:

if($send_contact){
echo "Contact Info Sent";
}

it was part of one tutorial that I found but it never had the $send_contact set either. So I am really not sure what should go there instead. That would be the last part of this whole thing.

CSS_Kidd




msg:3892130
 3:34 pm on Apr 14, 2009 (gmt 0)

So I completely used the the info that you gave me and re-did the form with the php on the actual page with a little validation. So hopefully I didn't mess it up. One question though... Is it ok for the form action to call the same page that it is on?

Here is the new code

<?php
$error = ''; // error message
$firstname = ''; // sender's first name
$lastname = ''; // sender's last name
$address1 = ''; // sender's address
$address2 = ''; // sender's appartment or suite
$city = ''; // sender's city
$state = ''; // sender's state
$zip = ''; // sender's zip
$email = ''; // sender's email
$phone = ''; // sender's phone

if(isset($_POST[submit]))
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$phone = $_POST['phone'];

if(trim($firstname) == '')
{
$error = '<div class="errormsg">Please enter your first name!</div>';
}
else if(trim($lastname) == '')
{
$error = '<div class="errormsg">Please enter your last name!</div>';
}
if(trim($address1) == '')
{
$error = '<div class="errormsg">Please enter your address!</div>';
}
else if(trim($city) == '')
{
$error = '<div class="errormsg">Please enter your city!</div>';
}
else if(trim($zip) == '')
{
$error = '<div class="errormsg">Please enter your zip!</div>';
}
else if(!isZip($zip))
{
$error = '<div class="errormsg">Please enter your phone number as such: #*$!-#*$!-#*$!x!</div>';
}
if(trim($email) == '')
{
$error = '<div class="errormsg">Please enter your email address!</div>';
}
else if(!isEmail($email))
{
$error = '<div class="errormsg">You have enter an invalid e-mail address. Please, try again!</div>';
}
if(trim($phone))
{
$error = '<div class="errormsg">Please enter your phone number!</div>';
}
else if(!isPhone($phone))
{
$error = '<div class="errormsg">Please enter your phone number as such: #*$!-#*$!-#*$!x!</div>';
}
if($error == '')
{
if(get_magic_quotes_gpc())
{
$message = stripslashes($message);
}

// message body
$body = "Contact Information:\n\n";
$body .= "First Name: ".$firstname."\n";
$body .= "Last Name: ".$lastname."\n";
$body .= "Address: ".$address1."\n";
$body .= "Apt. or Suite: ".$address2."\n";
$body .= "City: ".$city."\n";
$body .= "State: ".$state."\n";
$body .= "Zip: ".$zip."\n";
$body .= "Email Address: ".$email."\n";
$body .= "Phone: ".$phone."\n";

$to='me@someplace.com';
$subject="Contact Info";
$from = '"' . "$firstname $lastname" . '" <' . $email . '>';
$header = "From: $from\r\n";
$header .= 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message="$body";
mail($to,$subject,$message,$header);
?>

<!-- Message sent! (change the text below as you wish)-->
<div style="text-align:center;">
<h2>Thank You!</h2>
<p>Thank you <b><?=$name;?></b>, for your submission! One of our representatives will contact you shortly. </p>
</div>
<!--End Message Sent-->

<?php
}
}

if(!isset($_POST['send']) $error != '')
{
?>
<?=$error;?>

<form name="form1" method="post" action="contact.php">
<input name="firstname" type="text" id="firstname" size="50" value="<?=$firstname;?>">
<br />
<input name="lastname" type="text" id="lastname" size="50" value="<?=$lastname;?>">
<br />
<input name="address1" type="text" id="address1" size="50" value="<?=$address1;?>">
<br />
<input name="address2" type="text" id="address2" size="50" value="<?=$address2;?>">
<br />
<input name="city" type="text" id="city" size="50" value="<?=$city;?>">
<br />
<select name="state" id="state" value="<?=$state;?>">
<option selected>Alabama</option>
<option>Arkansas</option>
<option>so on</option>
</select>
<br />
<input name="zip" type="text" id="zip" size="50" value="<?=$zip;?>">
<br />
<input name="email" type="text" id="email" size="50" value="<?=$email;?>">
<br />
<input name="phone" type="text" id="phone" size="22" maxlength="12" value="<?=$phone;?>">
<br />
<input type="submit" name="submit" id="submit" value="Submit">
<input type="reset" name="reset" id="reset" value="Reset">
</form>

<?php
}

function isZip($zip)
{
return(preg_match("/^[0-9]{5}$/i", $zip));
}

function isPhone($phone)
{
return(preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone));
}

function isEmail($email)
{
return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]][[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(adaeaeroafagaialamanaoaqararpaasatauawazbabbbdbe bfbgbhbibizbjbmbnbobrbsbtbvbwbybzcacccdcfcgchcickclcmcnco comcoopcrcscucvcxcyczdedjdkdmdodzecedueeegehereseteufifjfkfm fofrgagbgdgegfghgiglgmgngovgpgqgrgsgtgugwgyhkhmhnhrhthuidie ilininfointioiqirisitjmjojpkekgkhkikmknkpkrkwkykzlalblclilk lrlsltlulvlymamcmdmgmhmilmkmlmmmnmompmqmrmsmtmumuseummvmwmxmy mznanamencnenetnfngninlnonpnrntnunzomorgpapepfpgphpkplpmpnpr propsptpwpyqarerorurwsasbscsdsesgshsisjskslsmsnsosrstsusvsy sztctdtftgthtjtktmtntotptrtttvtwtzuaugukumusuyuzvavcvevgvi vnvuwfwsyeytyuzazmzw)$(([0-9][0-9]?[0-1][0-9][0-9][2][0-4][0-9] [2][5][0-5])\.){3}([0-9][0-9]?[0-1][0-9][0-9][2][0-4][0-9][2][5][0-5]))$/i"
,$email));
}
?>

BTW rocknbil...
Even though it is not needed for this form... I love that footer idea. Thanks.

[edited by: eelixduppy at 4:18 pm (utc) on April 14, 2009]
[edit reason] fixed side scroll [/edit]

rocknbil




msg:3892308
 6:27 pm on Apr 14, 2009 (gmt 0)

Whoah you've been busy! I think I get the gist of what you're doing, but try to remember the KISS rule (keep it simple, stupid.) There may be less complex ways of doing what you're doing here.

First, address this logic:

if($send_contact){
echo "Contact Info Sent";
}

Approach it differently. If all goes well (and we always hope it does) we just let the program progress normally. We only need a "hook" if there's a problem, right? So instead of "If everything's OK" I personally prefer to "hook" on the problem.

$errorMessage = '';
if ($errorMessage != '') { // do your error output; exit; }
else { // send mail, output response; }

In the above, "else" is not even needed if you exit on error as shown.
if ($errorMessage != '') { // do your error output; exit; }
// send mail, output response;

Now look at how you're compiling errors. When you have "lots and lots of lines of code" you open all sorts of doors for errors and typos. The second thing: you are using if/elsif, so if "if" returns true, it will never test the "else if" immediately following (in your example, if there's an error in address, it won't test city. You may have intended this, maybe not.)

Look at this:


var plainNames = Array (
'firstname' => 'first name',
'lastname' => 'last name',
'address1' => 'address',
'city' => 'city',
'zip' => 'zip code',
'email' => 'email address',
'phone' => 'phone'
);
var expectedValues = Array (
'firstname' => $firstname,
'lastname' => $lastname,
'address1' => $address,
'city' => $city,
'zip' => $zip,
'email' => $email,
'phone' => $phone
);


foreach ($expectedValues as $key=>$value) {
if (trim($value) == '') {
$error .= '<li>Please enter your ' . $plainNames[$key] . ".</li>\n";
}
}

We've done four things:
- Put your required fields in an easy to maintain associative array
- Converted your field form names to a "plain English" equivalent for output
- Cut the code lines into a compact set of lines by looping through repetitive checks
- Created a list in which ALL errors will display

Since it's a list of errors, a list is more appropriate - see below.

So this leaves us only with your isPhone, izZip, and isEmail functions (note you have "phone" in the isZip error:)

if(!isZip($zip)){
$error .= "<li>Please enter your zip code in the following format:12345</li>\n";
}
if(!isEmail($email)){
$error .= "You have enter an invalid e-mail address. Please, try again!<li>\n";
}
if(!isPhone($phone)){
$error .= "<li>Please enter your phone number as such: #*$!-#*$!-#*$!x!</li>\n";
}

Note I'm concatenating error. So your output could be like this (remember opening comment about the hook:)


if ($error != '') {
$content = "
<p style=\"color:red;font-weight:700;\">There are errors in your submission:</p><ul>$error</ul>\n";
// print FORM here
}

This would give the end user a list of ALL errors:

There are errors in your submission:
- You have entered an invalid email address
- Your city is blank
.... etc

Last thing, let's uncomplicate your email check. What it looks like it's doing is accepting a pattern, plus a set list of .tld extensions. If this is working for you, ignore my notes here. Really, all you need for a valid email check is a pattern and a few things to make sure they are not trying to add multiple email addresses by comma separating it, etc. Here is the one I use, modified to work in your script:


function isEmail($email) {
// Kill all white space.
$email = preg_replace("/[\s\n\r]+/",'',$email);
// Silently kill multiple addresses, so spammers "think" it's working but it's not
if ($multiples = preg_split("/[,;:]+/",$email)) { $email = $multiples[0]; }
if (! preg_match("/.*\@.*[.].*/",$email)) { unset($email); }
// You could silently kill these, but if they are
//inputting metacharacters it's probably
//better to just error.
if (preg_match("/[~`!#\$%^&*()+=\\\{}\[\]:;\"'\<\>\?\/]/",$email)) { unset($email); }
return $email;
}

In the previous, note the means a real pipe character, which is a dangerous input from forms.

PS, since you can't test this on your server when you think you've got it done, I'll take a sec and throw it on one of my servers - as long as schedule is not pressing, I'm a busy guy. :-)

BenjArriola




msg:3892435
 9:07 pm on Apr 14, 2009 (gmt 0)

Just a small tip also... there are many ways to prevent spam, and one of the simple ways that is kind of easy to implement to prevent spam bots is creating an input box with a CSS display:none; so people normally do not see it. And if this field gets a value, most probably it is a bot. And i do not process the form.

CSS_Kidd




msg:3892459
 9:49 pm on Apr 14, 2009 (gmt 0)

Well It looks like I got some work to do. I really appreciate the help. I love figuring things out and this is actually fun for me. I will post it back up here when I complete the needed changes.

CSS_Kidd




msg:3894101
 9:41 pm on Apr 16, 2009 (gmt 0)

Ok so after looking at what you gave me and doing some searches, I have restructured my code. I have had a few Oh I get it moments, and an equal amount of I will never get this moments on a few issues. Unfortunately, most resources I have found, expect me to have a non dummy knowledge about, what I am assuming to be, the easier parts of php. So they are never well explained. So I left notes on what I really dont get. I dont want anyone to do this for me, I just want to understand it better. I also hope I am not moving backwards with this version.

<?php

// I still don't understand this
if(isset($_POST[submit]))
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$phone = $_POST['phone'];
}

// message body
$body = "Contact Information:\n\n";
$body .= "First Name: ".$firstname."\n";
$body .= "Last Name: ".$lastname."\n";
$body .= "Address: ".$address1."\n";
$body .= "Apt. or Suite: ".$address2."\n";
$body .= "City: ".$city."\n";
$body .= "State: ".$state."\n";
$body .= "Zip: ".$zip."\n";
$body .= "Email Address: ".$email."\n";
$body .= "Phone: ".$phone."\n";

//Email Sent
$to = 'me@someplace.com';
$subject = "Contact Info";
$from = '"' . "$firstname $lastname" . '" <' . $email . '>';
$header = "From: $from\r\n";
$header .= 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message="$body";
mail($to,$subject,$message,$header);

var plainNames = Array (
'firstname' => 'First Name',
'lastname' => 'Last Name',
'address1' => 'Address',
'city' => 'City',
'zip' => 'Zip Code',
'email' => 'Email Address',
'phone' => 'Phone'
);

var expectedValues = Array (
'firstname' => $firstname,
'lastname' => $lastname,
'address1' => $address,
'city' => $city,
'zip' => $zip,
'email' => $email,
'phone' => $phone
);

// Not to clear as to what this is doing (do your error output?)
$errorMessage = '';
if ($errorMessage != '') { // do your error output; exit; }

foreach ($expectedValues as $key=>$value) {
if (trim($value) == '') {
$error .= '<li>Please enter your ' . $plainNames[$key] . ".</li>\n";
}
}

if(!isZip($zip)){
$error .= "<li>Please enter your zip code in the following format:12345</li>\n";
}
if(!isEmail($email)){
$error .= "You have enter an invalid e-mail address. Please, try again!<li>\n";
}
if(!isPhone($phone)){
$error .= "<li>Please enter your phone number as such: #*$!-#*$!-#*$!x</li>\n";
}

function isZip($zip) {
return(preg_match("/^[0-9]{5}$/i", $zip));
}

function isPhone($phone) {
return(preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone));
}

function isEmail($email) {
$email = preg_replace("/[\s\n\r]+/",'',$email);
if ($multiples = preg_split("/[,;:]+/",$email)) { $email = $multiples[0]; }
if (! preg_match("/.*\@.*[.].*/",$email)) { unset($email); }
if (preg_match("/[~`!#\$%^&*()+=\\\{}\[\]:;\"'\<\>\?\/]/",$email)) { unset($email); }
return $email;
}

?>

<!--I only want this to appear, like the error messages if there are no errors and message is sent. This was coppied from a tutorial as I mentioned before but I don't think it sould be this way-->
<div style="text-align:center;">
<h2>Thank You!</h2>
<p>Thank you <b><?=$name;?></b>, for your submission! One of our representatives will contact you shortly. </p>
</div>
<!--^^^^^^^^^^^^-->

<?php
}
}
// I am not sure what this is really saying.
if(!isset($_POST['submit']) $error != '')
{
?>

<?=$error;?>

<form name="form1" method="post" action="contact.php">
<input name="firstname" type="text" id="firstname" size="50" value="<?=$firstname;?>">
<br />
<input name="lastname" type="text" id="lastname" size="50" value="<?=$lastname;?>">
<br />
<input name="address1" type="text" id="address1" size="50" value="<?=$address1;?>">
<br />
<input name="address2" type="text" id="address2" size="50" value="<?=$address2;?>">
<br />
<input name="city" type="text" id="city" size="50" value="<?=$city;?>">
<br />
<select name="state" id="state" value="<?=$state;?>">
<option selected>Alabama</option>
<option>Arkansas</option>
</select>
<br />
<input name="zip" type="text" id="zip" size="50" value="<?=$zip;?>">
<br />
<input name="email" type="text" id="email" size="50" value="<?=$email;?>">
<br />
<input name="phone" type="text" id="phone" size="22" maxlength="12" value="<?=$phone;?>">
<br />
<input type="submit" name="submit" id="submit" value="Submit">
<input type="reset" name="reset" id="reset" value="Reset">
</form>

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved