TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
Advertisement
Associates
Associates
techtuts Darkmindz
CSS Tutorials Tutorialsphere.com - Free Online Tutorials
Boston PHP SurfnLearn
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 11-15-2007, 01:42 AM   #1 (permalink)
The Contributor
Upcoming Programmer 
 
Matt83's Avatar
 
Join Date: Oct 2007
Location: Argentina
Posts: 72
Thanks: 18
Matt83 is on a distinguished road
Default Contact Form Script (update 3)

Hi guys, this is a simple script to manage contact forms, just thougth of giving it away in case someone needs one. Any critics or comments are welcome.

sendmail.php: (update 3) // Thanks Wildhoney

PHP Code:
<?php
# ------------------------------------------------------------
// General Configuration
# ------------------------------------------------------------

// Name of the website. 
$szFrom "My Website";

// Your email, (the recipient email address).
$szRecipient "youremail@somedomain.com"

// Sender's email address.
$szFromEmail "noreply@somedomain.com"

/* Title comes from the form. this gives the possibility  
 to set up more than one form and still use this same script.*/
$szTitle $_POST['title']; 

// This sets up the subject.
$szSubject $szFrom.": ".$szTitle

/* All input fields coming from the form should go here. 
The first value is the name attribute we used on the form 
and the second value on the right the name we want to display 
on the final email.*/

$aPosted = array( 
    
"name" => "Name",
    
"telephone" => "Telephone Number",
    
"email" => "Email Address",
    
"comments" => "Comments",
    
// add here your fields
);

# ------------------------------------------------------------
// Email Content
# ------------------------------------------------------------

$szEmailContent ='<table border="0" width="100%" border="0">';
$szEmailContent.='<tr><td colspan="2" align="center" style="color:#fff; background-color:#000"><b>".$szTitle."</b></td></tr>';
$szEmailContent.= '</tr><tr><td colspan="2">&nbsp;</td>';

$last "";

foreach(
$aPosted as $value => $szReal)
{
    if(isset(
$_POST['value']))
    {
        
$szEmailContent.= '<tr><td width="50%" align="right"><b>';
        
        if(
$last != $szReal)
        {
            
$szEmailContent.= $szReal.":";
            
$last $szReal;
        }
        
        
$szEmailContent.= "</b></td><td>".$_POST['value']."</td></tr>\n";
    }
}

$szEmailContent.= "</table>";

# ------------------------------------------------------------
// Declare Email headers
# ------------------------------------------------------------

$szHeaders  "MIME-Version: 1.0\n";
$szHeaders .= "Content-type: text/html; charset=iso-8859-1\n";
$szHeaders .= "From: \"$szFrom\" <$szFrom>\n";    
$szHeaders .= "Return-Path: <$szFrom>\n";    
$szHeaders .= "X-Sender: <$szFrom>\n";
$szHeaders .= "X-Mailer: PHP\n"
$szHeaders .= "X-Priority: 3\n"

# ------------------------------------------------------------
// Output 
# ------------------------------------------------------------

if(mail($szRecipient$szSubject$szEmailContent$szHeaders))
    
// go to previous page ($lasturl) with action=1 (could be a succes message).
    
header'Location: '.html_entity_decode($_POST['lasturl']).'?action=1');  
else
    
// go to previous page ($lasturl) with action=2 (could be a failure message).
    
header'Location: '.html_entity_decode($_POST['lasturl']).'?action=2');      
        
?>
contact_form.php (example):


PHP Code:

<form action="sendmail.php" method="post">
<input type="hidden" name="title" value="My Contact Form Title"/>
<input type="hidden" name="lasturl" value="<?php echo $_SERVER['REQUEST_URI']; // this is important ?>"/> 

    <p><label>Name:</label><br/>
    <input type="text" name="name" value=""/>    
    </p>
    
    <p><label>Telephone Number:</label><br/>
    <input type="text" name="telephone" value=""/>    
    </p>
    
    <p><label>Email:</label><br/>
    <input type="text" name="email" value=""/>    
    </p>

    <p><label>Comments:</label><br/>
    <textarea name="comments" rows="8" cols="40"></textarea>
    </p>

    <p><input type="submit" value="Continue &rarr;"></p>
</form>
I think that the overall concept is pretty simple but let me know if you have any questions.
ps: sorry for bad english.

Matt
Attached Files
File Type: php sendmail.php (3.0 KB, 135 views)
File Type: php contact_form.php (690 Bytes, 122 views)
__________________
http://www.mattvarone.com

Last edited by Matt83 : 12-05-2007 at 09:07 PM. Reason: CSS support in emails / Quotes in Html / Added Attachment / Better Styling
Matt83 is offline  
Reply With Quote
The Following User Says Thank You to Matt83 For This Useful Post:
Rendair (12-10-2007)
Old 11-15-2007, 02:41 AM   #2 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,655
Thanks: 74
Wildhoney is on a distinguished road
Default

The script looks rather good, thanks for sharing! As for your English, I thought you were English from the language you used, I had to scroll back up when I read your apology as I was confused :) !

Allow me to the comment on the usage of HTML, I don't know how fluent you are in HTML and so I don't know if this was intentional at all, but there are a lot of strict standards to stick to when sending out emails in HTML format. A lot of stand-alone email clients don't support CSS, Gmail doesn't support the <style> tag that you've used, only supports inline styles, whereas a few of the Lotus email clients barely support the floating of DIVs. This is where the use of tables is a life saver!

I've been spending a bit of time recently creating HTML formatted emails for another site of mine, Wired Flame. However, after some extensive reading, I came to the conclusion, as have many others, that creating W3C compliant XHTML emails is impractical because a lot of clients will crumble at the sight of them! You also have to be careful and ensure you avoid using rowspans and colspans as some stand-alone applications don't even support them.

It really is a nightmare. Nevertheless, I found this website a godsend if anybody else is contemplating using HTML formatted emails!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is online now  
Reply With Quote
The Following User Says Thank You to Wildhoney For This Useful Post:
Matt83 (12-07-2007)
Old 11-15-2007, 03:16 AM   #3 (permalink)
The Contributor
Upcoming Programmer 
 
Matt83's Avatar
 
Join Date: Oct 2007
Location: Argentina
Posts: 72
Thanks: 18
Matt83 is on a distinguished road
Default

thank you for the comments Wildhoney, i wasnt aware of the css/xhtml problems in emails so im glad to know now. Found the linked article very interesting. I have updated the script based on that, so now it should be displayed correctly in most common mail readers. thanks again,

Matt
__________________
http://www.mattvarone.com
Matt83 is offline  
Reply With Quote
Old 11-15-2007, 01:57 PM   #4 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,655
Thanks: 74
Wildhoney is on a distinguished road
Default

It's an utter nightmare, I tell you. You may also wish to invert your quotes around the HTML to the single ones and the inner single ones to double ones, like this:

html4strict Code:
'<table border="0" width="100%" border="0">';

Although you don't technically need them around integers, and the single quotes work in every browser I've seen them in, you can't be too sure how email applications, such as the Lotus range, will behave with single quotes, and no quotes around integers. It really is like treading on egg shells!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is online now  
Reply With Quote
Old 11-15-2007, 02:24 PM   #5 (permalink)
The Contributor
Upcoming Programmer 
 
Matt83's Avatar
 
Join Date: Oct 2007
Location: Argentina
Posts: 72
Thanks: 18
Matt83 is on a distinguished road
Default

Quote:
Originally Posted by Wildhoney View Post
It really is like treading on egg shells!
:D thanks for the comments and the tip Wildhoney, much appreciated. Ill use double quotes from now on in this cases.

Ps: updated script and added the files as an attachment.
__________________
http://www.mattvarone.com
Matt83 is offline  
Reply With Quote
Old 11-19-2007, 11:11 AM   #6 (permalink)
The Wanderer
PHP Guru Advanced Programmer Zend Certified 
 
DragonBe's Avatar
 
Join Date: Nov 2007
Location: according to my wife: on the Net
Posts: 19
Thanks: 0
DragonBe is on a distinguished road
Default

Hi Matt,


This is a good example form submission script, but I would like to suggest you use both HTML and TEXT e-mails, since I know that many companies disable receiving html-rich mails. By providing a text-based alternative, these recipients will be grateful.

As a paranoid developer, I always check input fields on their types and lenghts, so in case of your name field I check the lenght is between 2 and 50 (max size db field), that the field is alphanumeric (no one calls his son or daughter example_123) and that no html or db scripts can be run.

Most of the time I use Zend Framework to check this, but a simple class can do this job for you:

Code:
<?php
/**
 * Simple class to validate form input.
 */
class formValidator
{
	/**
	* Check wether a value is alpha-numeric, if it consists only of
	* characters.
	*
	* @param mixed $value
	* @return boolean
	*/
	public function isAlpha($value)
	{
		return ctype_alpha($value);
	}
  
	/**
	 * Check wether a value is numeric, if it consists only of
	 * numbers.
	 *
	 * @param mixed $value
	 * @return boolean
	 */
	public function isNum($value)
	{
		return ctype_digit($value);
	}
	
	/**
	 * A simple e-mail address validation checker, to see if the
	 * entered e-mail address is correct.
	 *
	 * @param string $value
	 * @return boolean
	 */
	public function isEmail($value)
	{
		$valid = false;
		$match = array();
		$pattern = "/^[a-zA-Z0-9\-\_\.]+\@[a-z0-9\-\_\.]+\.[a-z]{2,5}$/";
		preg_match($pattern, $value, $match);
		if (key_exists(0, $match) && strcmp($match[0], $value) === 0) {
			$valid = true;
		}
		return $valid;
	}
	
	/**
	 * Check wether a sumitted text is between a minimum length and
	 * a maximum length. Defaults are minimum 2 and maximum 50 chars.
	 *
	 * @param mixed $value
	 * @param int $min
	 * @param int $max
	 * @return boolean
	 */
	public function isBetween($value, $min = 2, $max = 50)
	{
		return strlen($value) >= $min && strlen($value) <= $max ? true : false;
	}
	
}

/*
// Example script to see it's functionality
$fv = new formValidator();
echo $fv->isAlpha("Lorum");
echo $fv->isNum("123");
echo $fv->isBetween("We ar champions!");
echo $fv->isEmail("john_123.doe@sub-domain.example.com");
*/
Send a message via ICQ to DragonBe Send a message via Skype™ to DragonBe
DragonBe is offline  
Reply With Quote
Old 11-19-2007, 06:41 PM   #7 (permalink)
The Contributor
Upcoming Programmer 
 
Matt83's Avatar
 
Join Date: Oct 2007
Location: Argentina
Posts: 72
Thanks: 18
Matt83 is on a distinguished road
Default

Quote:
Originally Posted by DragonBe View Post

This is a good example form submission script, but I would like to suggest you use both HTML and TEXT e-mails, since I know that many companies disable receiving html-rich mails. By providing a text-based alternative, these recipients will be grateful.

As a paranoid developer, I always check input fields on their types and lenghts, so in case of your name field I check the lenght is between 2 and 50 (max size db field), that the field is alphanumeric (no one calls his son or daughter example_123) and that no html or db scripts can be run.
hi DragonBe, thank you for the nice feedback. When i wrote the script i didnt took to much in count the actual difficulties that could bring the email formating so i appreciate you point that out since im not experienced in that field. i guess i should have tested more in different email readers as its also related to what wildhoney pointed. Will definitely look around and see how to implement that in the script. As for the validation, i have a little js script i like to use, but its great to see an alternative cause js could be off which would be a problem.

thanks again,
Matt
__________________
http://www.mattvarone.com
Matt83 is offline  
Reply With Quote
Old 11-20-2007, 12:15 AM   #8 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,655
Thanks: 74
Wildhoney is on a distinguished road
Default

You really will be banging your head against the wall, Matt. It's not at all easy, even for someone who would consider themselves quite experienced with the way of the web - such as me. I learnt numerous things from reading that site I've given you. Pain in the arse, really is. No better phrase for it!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is online now  
Reply With Quote
Old 11-20-2007, 12:21 AM   #9 (permalink)
The Wanderer
PHP Guru Advanced Programmer Zend Certified 
 
DragonBe's Avatar
 
Join Date: Nov 2007
Location: according to my wife: on the Net
Posts: 19
Thanks: 0
DragonBe is on a distinguished road
Default

Quote:
Originally Posted by Matt83 View Post
As for the validation, i have a little js script i like to use, but its great to see an alternative cause js could be off which would be a problem.
Sorry to be the paranoid here again, but you cannot trust client-side scripting (like Javascript). You said it, no validation occurs when someone disables javascript or uses curl to post your form.

As an example: a login screen only validates with javascript and nothing further.

The query to the database is something like:
Code:
$q = "SELECT * FROM users WHERE username='" . $_POST['username'] . "' AND password = '" . $_POST['password'] . "'";
So if I submit something like "" OR 1=1 '# I can access the site without problem.

One thing you'll learn when you're developing a long time: you cannot trust foreign sources (users, webservices, feeds or whatever that is not made by you). And of course, can you "really" trust yourself ?

Just my 2-cents,

DragonBe
Send a message via ICQ to DragonBe Send a message via Skype™ to DragonBe
DragonBe is offline  
Reply With Quote
Old 11-20-2007, 12:30 AM   #10 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,655
Thanks: 74
Wildhoney is on a distinguished road
Default

Couldn't agree more. Have yourself a read over this article, and then construct yourself a safe MySQL parse value function to take into consideration the annoyance of GPC, and then add slashes and throw the values through mysql_real_escape_string().
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is online now  
Reply With Quote
Old 11-20-2007, 09:45 PM   #11 (permalink)
The Contributor
Upcoming Programmer 
 
Matt83's Avatar
 
Join Date: Oct 2007
Location: Argentina
Posts: 72
Thanks: 18
Matt83 is on a distinguished road
Default

Quote:
Originally Posted by Wildhoney View Post
You really will be banging your head against the wall, Matt. It's not at all easy, even for someone who would consider themselves quite experienced with the way of the web - such as me. I learnt numerous things from reading that site I've given you. Pain in the arse, really is. No better phrase for it!
oh boy i should consider going back to mailto: haha :D

Thanks for the advice guys, i appreciate your feedback. I have to say that i always validate and escape all data when its going to a database, but since this is a contact form i didnt care much here to know if the data was inadequate, as long as all the required fields where complete i was ok.
Anyways, this could make the script more solid, possibly against spam and stuff, so ill see what i can do and update it.


Quote:
Originally Posted by DragonBe View Post
This is a good example form submission script, but I would like to suggest you use both HTML and TEXT e-mails, since I know that many companies disable receiving html-rich mails. By providing a text-based alternative, these recipients will be grateful.
Now i couldn't figure out how to send an alternative version of the email in plain text. Should i send the email two times? or theres a way to specify in the headers that it should ship out with a plain text alternative version. Any help/link/guidance on that would be much appreciated.


thanks again.

Quote:
Originally Posted by Wildhoney View Post
Have yourself a read over this article, and then construct yourself a safe MySQL parse value function to take into consideration the annoyance of GPC, and then add slashes and throw the values through mysql_real_escape_string().
great tut WH, helped me a lot.
__________________
http://www.mattvarone.com
Matt83 is offline  
Reply With Quote
Old 11-27-2007, 12:00 AM   #12 (permalink)
The Gregarious
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 532
Thanks: 26
sketchMedia is on a distinguished road
Default

Being paranoid is the only way that you will ever create a script that is secure (although some may argue that nothing can be truly secure for many reasons), you just have to remember that there are alot of little childish 'script kiddies' out there who like to show off there 'l33t haxOr skilz LoLz rOfl', so you really cant let your guard down.

And as for the email HTML issues, i think a pain in the arse is as good a description your going to get without swearing and smashing your head into the monitor repeatedly until you pass out.

Anyway with that little rant over, nice script
__________________
sketchMedia is offline  
Reply With Quote
Old 11-27-2007, 12:37 AM   #13 (permalink)
The Contributor
Upcoming Programmer 
 
Matt83's Avatar
 
Join Date: Oct 2007
Location: Argentina
Posts: 72
Thanks: 18
Matt83 is on a distinguished road
Default

thanks sketchMedia, i appreciate your comment. I think i might have stepped into a complex direction with this script as this problems are way out of my league. Theres is still a bunch of other things i feel i have to learn first so i better drop it as it is and keep on with my studies. Just got my copy of Advanced PHP programming by George Schlossnagle (recomended here) so im totally wrapped into that. i do hope at some point to get back on this script and improve it as much as i can,

Thanks for the help guys
__________________
http://www.mattvarone.com
Matt83 is offline  
Reply With Quote
Old 11-27-2007, 12:46 AM   #14 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,655
Thanks: 74
Wildhoney is on a distinguished road
Default

No, no, thank you for the script :) I'm sure you have learnt a great deal from being kind enough to release the script in the first place. It really is much appreciated, and so please do feel free to release any others you do in the future! The advanced PHP book, although it is a beauty, does take some reading through to comprehend. I've had to read through each chapter as many as 3 times! It's also a fantastic reference book in that it sits on my desk, and has at least 4 bookmarks in it that my sister made me that relate to what I'm currently working on :) !
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is online now  
Reply With Quote
Old 11-27-2007, 06:31 AM   #15 (permalink)
The Gregarious
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 532
Thanks: 26
sketchMedia is on a distinguished road
Default

Yes idd, thanks. Often i find the best way to truly learn something is to build and release scripts and then get feedback from other developers.
Oh and thanks Wildhoney, i actualy managed to read through that site you mentioned in one of your earlier posts, I found it really interesting, a good resource for future problems I think.
I may acquire a copy of that book, it looks like a good read.
__________________
sketchMedia is offline  
Reply With Quote