Jump to content

Cre8asiteforums Internet Marketing
and Conversion Web Design


Photo

A Nice php based form for my friends on cre8asite.


  • Please log in to reply
40 replies to this topic

#1 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 15 July 2005 - 04:16 AM

I use this "form setup" on all my websites it has served me very well.
It does not show the email address, making it vulnerable to spanbots. Just make the few changes and upload the 2 files to your server.

First up here is the form:
<form id="form" method="post" action="email.php">

        <table width="100%" border="0" cellspacing="0" cellpadding="0">

          <tr> 

            <td width="55%" height="25">Your Name</td>

          </tr>

          <tr> 

            <td><input type="text" name="Name" value="<?php echo $Name; ?>" />

            </td>

          </tr>

          <tr> 

            <td height="24">Your Email</td>

          </tr>

          <tr> 

            <td><input type="text" name="Email" value="<?php echo $Email; ?>" />

            </td>

          </tr>

          <tr> 

            <td height="25">Comments and/or Questions</td>

          </tr>

          <tr> 

            <td><textarea name="Comments" rows="5" cols="32"><?php echo $Comments; ?></textarea>

            </td>

          </tr>

        </table>

        <p> <!-- you can create custom error or success pages, otherwise remove the domain name for below-->

          <input type="submit" name="Submit" value="Submit" />

          <input type="reset" name="Reset" value="Clear Form" />

          <input type="hidden" name="subject" value="website email" />

          <input type="hidden" name="required_fields" value="Name,Comments" />

          <input type="hidden" name="required_email_fields" value="Email" />

          <input type="hidden" name="recipient_group" value="0" />

          <input type="hidden" name="error_page" value="http://www.yourdomain.co.uk/error.php" />

          <input type="hidden" name="thanks_page" value="http://www.yourdomain.co.uk/thanks.php" />

          <input type="hidden" name="send_copy" value="no" />

          <input type="hidden" name="copy_subject" value="Thanks for your Email" />

          <input type="hidden" name="copy_tomail_field" value="Email" />

          <input type="hidden" name="mail_type" value="vert_table" />

          <input type="hidden" name="mail_priority" value="3" />

          <input type="hidden" name="reply_to_field" value="Email" />

          <input type="hidden" name="return_ip" value="1" />

        </p>

      </form>
no configuration here apart from specifying the success ans error pages.

Now for the php processor:


<?php

// configuration you only neeed two changes 

	$tomail[0]="you@yourdomain.co.uk";//change this to your email address

	$cc_tomail[0]="";

	$bcc_tomail[0]="";

	$tomail[1]="";

	$cc_tomail[1]="";

	$bcc_tomail[1]="";

	$tomail[2]="";

	$cc_tomail[2]="";

	$bcc_tomail[2]="";

	$check_referrer=1;

	$referring_domains="http://yourdomain.co.uk/,http://www.yourdomain.co.uk/"; //change this in the same format

// Error and Success Page Variables

	$error_page_title="Error - Missed Fields";

	$error_page_text="Please use your browser's back button to return to the form and complete the required fields.";

	$thanks_page_title="Message Sent";

	$thanks_page_text="Thank you for your inquiry";



//don't change anything below this-----------------------------------------------

ob_start();

$required_fields=$_POST["required_fields"];

$required_email_fields=$_POST["required_email_fields"];

$recipients=$_POST["recipient_group"];

$error_page=$_POST["error_page"];

$thanks_page=$_POST["thanks_page"];

$subject=$_POST["subject"];

$send_copy=$_POST["send_copy"];

$copy_subject=$_POST["copy_subject"];

$copy_tomail_field=$_POST["copy_tomail_field"];

$mail_type=$_POST["mail_type"];

$mail_priority=$_POST["mail_priority"];

$return_ip=$_POST["return_ip"];

if($_POST["Submit"]=="Submit")

{

	if($check_referrer==1)

	{

  $ref_check=preg_split('/,/',$referring_domains);

  $ref_run=sizeof($ref_check);

  $referer=$_SERVER['HTTP_REFERER'];

  $domain_chk="no";

  for($i=0;$i<$ref_run;$i++)

  {

  	$cur_domain=$ref_check[$i];

  	if(stristr($referer,$cur_domain)){$domain_chk="yes";}

  }

	}

	else

	{

  $domain_chk="yes";

	}

	if($domain_chk=="yes")

	{

  $mail="yes";

  $req_check=preg_split('/,/',$required_fields);

  $req_run=sizeof($req_check);

  $error_message="";

  for($i=0;$i<$req_run;$i++)

  {

  	$cur_field_name=$req_check[$i];

  	$cur_field=$_POST[$cur_field_name];

  	if($cur_field=="")

  	{

    $error_message=$error_message."You are missing the ".$req_check[$i]." field<br />";

    $mail="no";

  	}

  }

  $email_check=preg_split('/,/',$required_email_fields);

  $email_run=sizeof($email_check);

  for($i=0;$i<$email_run;$i++)

  {

  	$cur_email_name=$email_check[$i];

  	$cur_email=$_POST[$cur_email_name];

  	if($cur_email=="" || !eregi("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,6}$",$cur_email))

  	{

    $error_message=$error_message."You are missing the ".$email_check[$i]." field or the email is not a valid email address.<br />";

    $mail="no";

  	}

  }

  if($mail=="yes")

  {

  	if(getenv(HTTP_X_FORWARDED_FOR))

  	{$user_ip=getenv("HTTP_X_FORWARDED_FOR");}

  	else

  	{$user_ip=getenv("REMOTE_ADDR");}

  	if($mail_type=="vert_table")

  	{

    $message="<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

      	<html>

      	<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>

      	<body>

      	<table cellpadding="2" cellspacing="0" border="0" width="600">n";

    foreach($_POST as $key=>$value)

    {

    	$value=stripslashes($value);

    	$value=preg_replace("/(http://+.[^s]+)/i",'<a href="1">1</a>', $value);

    	$value=nl2br($value);

    	if($key != "Submit" && $key != "subject" && $key != "required_fields" && $key != "required_email_fields" && $key != "recipient_group" && $key != "error_page" && $key != "thanks_page" && $key != "send_copy" && $key != "copy_subject" && $key != "copy_tomail_field" && $key != "mail_type" && $key != "mail_priority" && $key != "return_ip")

    	{

      $message=$message."<tr>n<td align="left" valign="top" style="white-space:nowrap;"><b>".$key."</b></td>n<td align="left" valign="top" width="100%">".$value."</td></tr>";

    	}

    }

    if($return_ip==1)

    {

    	$message=$message."<tr>n<td align="left" valign="top" style="white-space:nowrap;"><b>Sender IP</b></td>n<td align="left" valign="top" width="100%">".$user_ip."</td></tr>";

    }

    $message=$message."n</table></body></html>";

  	}

  	else if($mail_type=="horz_table")

  	{

    $message="<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

      	<html>

      	<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>

      	<body>

      	<table cellpadding="2" cellspacing="0" border="1">n

      	<tr>";

    foreach($_POST as $key=>$value)

    {

    	if($key != "Submit" && $key != "subject" && $key != "required_fields" && $key != "required_email_fields" && $key != "recipient_group" && $key != "error_page" && $key != "thanks_page" && $key != "send_copy" && $key != "copy_subject" && $key != "copy_tomail_field" && $key != "mail_type" && $key != "mail_priority" && $key != "return_ip")

    	{

      $message=$message."n<td align="left" valign="top" style="white-space:nowrap;"><b>".$key."</b></td>";

    	}

    }

    if($return_ip==1)

    {

    	$message=$message."<td align="left" valign="top" style="white-space:nowrap;"><b>Sender IP</b></td>";

    }

    $message=$message."</tr>n<tr>n";

    foreach($_POST as $key=>$value)

    {

    	$value=stripslashes($value);

    	$value=preg_replace("/(http://+.[^s]+)/i",'<a href="1">1</a>', $value);

    	$value=nl2br($value);

    	if($key != "Submit" && $key != "subject" && $key != "required_fields" && $key != "required_email_fields" && $key != "recipient_group" && $key != "error_page" && $key != "thanks_page" && $key != "send_copy" && $key != "copy_subject" && $key != "copy_tomail_field" && $key != "mail_type" && $key != "mail_priority" && $key != "return_ip")

    	{

      $message=$message."n<td align="left" valign="top" style="white-space:nowrap;">".$value."</td>";

    	}

    }

    if($return_ip==1)

    {

    	$message=$message."<td align="left" valign="top" style="white-space:nowrap;">".$user_ip."</td>";

    }

    $message=$message."n</tr>n</table></body></html>";

  	}

  	else

  	{

    $message="Form Results";

    foreach($_POST as $key=>$value)

    {

    	$value=stripslashes($value);

    	$value=nl2br($value);

    	if($key != "Submit" && $key != "subject" && $key != "required_fields" && $key != "required_email_fields" && $key != "recipient_group" && $key != "error_page" && $key != "thanks_page" && $key != "send_copy" && $key != "copy_subject" && $key != "copy_tomail_field" && $key != "mail_type" && $key != "mail_priority" && $key != "return_ip")

    	{

      $message=$message."n".$key.": ".$value;

    	}

    }

    if($return_ip==1)

    {

    	$message=$message."Sender IP: ".$user_ip;

    }

  	}

  	$extra="From: ".$_POST[$reply_to_field]."n";

  	$extra.="X-Priority: $mail_priorityn";

  	$cc_tomail=$cc_tomail[$recipients];

  	$bcc_tomail=$bcc_tomail[$recipients];

  	if($cc_tomail!="")

  	{

    $extra.="Cc: $cc_tomail;n";

  	}

  	if($bcc_tomail!="")

  	{

    $extra.="Bcc: $bcc_tomail[$recipients]n";

  	} 

  	if($mail_type=="horz_table" || $mail_type=="vert_table")

  	{

    $extra.="MIME-Version: 1.0nContent-type: text/html; charset=iso-8859-1n";

  	}

  	$subject=$_POST["subject"];

  	$tomail=$tomail[$recipients];

  	mail ("$tomail", "$subject", "$message", "$extra");

  	if($send_copy=="yes")

  	{

    $copy_extra="From: $Name<$Email>nX-Priority: $mail_priorityn";

    if($mail_type=="horz_table" || $mail_type=="vert_table")

    {

    	$copy_extra.="MIME-Version: 1.0nContent-type: text/html; charset=iso-8859-1n";

    }

    $copy_address=$_POST[$copy_tomail_field];

    mail ("$copy_address", "$copy_subject", "$message", "$copy_extra");

  	}

  	if($thanks_page=="")

  	{

    echo "<p>$thanks_page_title</p>";

    echo "<p>$thanks_page_text</p>";

  	}

  	else

  	{

    ob_end_clean();

    $redirect="Location: ".$thanks_page;

    header($redirect);

  	}

  }

  else

  {

  	if($error_page=="")

  	{

    echo "<p>$error_page_title</p>";

    echo $error_message;

    echo "<p>$error_page_text</p>";

  	}

  	else

  	{

    ob_end_clean();

    $redirect="Location: ".$error_page;

    header($redirect);

  	}

  }

	}

	else

	{

  echo "<p>Sorry, mailing request came from an unauthorized domain.</p>";

	}

}

else

{

	echo "<p>Error</p>";

	echo "<p>No form data has been sent to the script</p>";

}

ob_end_flush();

?>

Hope this helps yall who have trouble with php forms.

TreV

#2 usability_guy

usability_guy

    Gravity Master Member

  • Members
  • 245 posts

Posted 15 July 2005 - 04:45 AM

ohhhh!
Tx Trev for the detailed answer.
I will try and test it.
I never worked on php earlier
you always do something for the first time.
So if at all i'll working on php more or less, I 'll give a good credit to You...
(I didn't test this script yet, I'll come back after a while to let u know if worked)

Rams..

#3 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 15 July 2005 - 05:01 AM

usability_guy,

If your'e gonna use this code:

call the php form processor email.php


to check if your server supports php just create a file and insert the following
<?php phpinfo(); ?>

save this file as info.php and upload it to your server.

browse to the file you created: eg http://www.domainxyz.com/info.php


I never worked on php earlier 
you always do something for the first time. 
So if at all i'll working on php more or less, I 'll give a good credit to You


I didn't write the php processor, I merely adapted and extended it. I wish I could remember the authors' name to give credit where it is due. I just wanted to share a reasonably safe and powerful form.
TreV

#4 usability_guy

usability_guy

    Gravity Master Member

  • Members
  • 245 posts

Posted 15 July 2005 - 06:10 AM

Humm, Its gives the error as,
Fatal error: Call to undefined function: mail() in /home/www/sites/123bingo.com/htdocs/network/email.php on line 180

Let me put the email.pho file here:-
<?php
// configuration you only neeed two changes
$tomail[0]="grafix_dzyner@yahoo.com";//change this to your email address
$cc_tomail[0]="";
$bcc_tomail[0]="";
$tomail[1]="";
$cc_tomail[1]="";
$bcc_tomail[1]="";
$tomail[2]="";
$cc_tomail[2]="";
$bcc_tomail[2]="";
$check_referrer=1;
$referring_domains="http://www.123bingo.com/,http://www.123bingo.com/"; //change this in the same format
// Error and Success Page Variables
$error_page_title="Error - Missed Fields";
$error_page_text="Please use your browser's back button to return to the form and complete the required fields.";
$thanks_page_title="Message Sent";
$thanks_page_text="Thank you for your inquiry";

//don't change anything below this-----------------------------------------------
ob_start();
$required_fields=$_POST["required_fields"];
$required_email_fields=$_POST["required_email_fields"];
$recipients=$_POST["recipient_group"];
$error_page=$_POST["error_page"];
$thanks_page=$_POST["thanks_page"];
$subject=$_POST["subject"];
$send_copy=$_POST["send_copy"];
$copy_subject=$_POST["copy_subject"];
$copy_tomail_field=$_POST["copy_tomail_field"];
$mail_type=$_POST["mail_type"];
$mail_priority=$_POST["mail_priority"];
$return_ip=$_POST["return_ip"];
if($_POST["Submit"]=="Submit")
{
if($check_referrer==1)
{
$ref_check=preg_split('/,/',$referring_domains);
$ref_run=sizeof($ref_check);
$referer=$_SERVER['HTTP_REFERER'];
$domain_chk="no";
for($i=0;$i<$ref_run;$i++)
{
$cur_domain=$ref_check[$i];
if(stristr($referer,$cur_domain)){$domain_chk="yes";}
}
}
else
{
$domain_chk="yes";
}
if($domain_chk=="yes")
{
$mail="yes";
$req_check=preg_split('/,/',$required_fields);
$req_run=sizeof($req_check);
$error_message="";
for($i=0;$i<$req_run;$i++)
{
$cur_field_name=$req_check[$i];
$cur_field=$_POST[$cur_field_name];
if($cur_field=="")
{
$error_message=$error_message."You are missing the ".$req_check[$i]." field<br />";
$mail="no";
}
}
$email_check=preg_split('/,/',$required_email_fields);
$email_run=sizeof($email_check);
for($i=0;$i<$email_run;$i++)
{
$cur_email_name=$email_check[$i];
$cur_email=$_POST[$cur_email_name];
if($cur_email=="" || !eregi("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,6}$",$cur_email))
{
$error_message=$error_message."You are missing the ".$email_check[$i]." field or the email is not a valid email address.<br />";
$mail="no";
}
}
if($mail=="yes")
{
if(getenv(HTTP_X_FORWARDED_FOR))
{$user_ip=getenv("HTTP_X_FORWARDED_FOR");}
else
{$user_ip=getenv("REMOTE_ADDR");}
if($mail_type=="vert_table")
{
$message="<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>
<body>
<table cellpadding="2" cellspacing="0" border="0" width="600">n";
foreach($_POST as $key=>$value)
{
$value=stripslashes($value);
$value=preg_replace("/(http://+.[^s]+)/i",'<a href="1">1</a>', $value);
$value=nl2br($value);
if($key != "Submit" && $key != "subject" && $key != "required_fields" && $key != "required_email_fields" && $key != "recipient_group" && $key != "error_page" && $key != "thanks_page" && $key != "send_copy" && $key != "copy_subject" && $key != "copy_tomail_field" && $key != "mail_type" && $key != "mail_priority" && $key != "return_ip")
{
$message=$message."<tr>n<td align="left" valign="top" style="white-space:nowrap;"><b>".$key."</b></td>n<td align="left" valign="top" width="100%">".$value."</td></tr>";
}
}
if($return_ip==1)
{
$message=$message."<tr>n<td align="left" valign="top" style="white-space:nowrap;"><b>Sender IP</b></td>n<td align="left" valign="top" width="100%">".$user_ip."</td></tr>";
}
$message=$message."n</table></body></html>";
}
else if($mail_type=="horz_table")
{
$message="<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>
<body>
<table cellpadding="2" cellspacing="0" border="1">n
<tr>";
foreach($_POST as $key=>$value)
{
if($key != "Submit" && $key != "subject" && $key != "required_fields" && $key != "required_email_fields" && $key != "recipient_group" && $key != "error_page" && $key != "thanks_page" && $key != "send_copy" && $key != "copy_subject" && $key != "copy_tomail_field" && $key != "mail_type" && $key != "mail_priority" && $key != "return_ip")
{
$message=$message."n<td align="left" valign="top" style="white-space:nowrap;"><b>".$key."</b></td>";
}
}
if($return_ip==1)
{
$message=$message."<td align="left" valign="top" style="white-space:nowrap;"><b>Sender IP</b></td>";
}
$message=$message."</tr>n<tr>n";
foreach($_POST as $key=>$value)
{
$value=stripslashes($value);
$value=preg_replace("/(http://+.[^s]+)/i",'<a href="1">1</a>', $value);
$value=nl2br($value);
if($key != "Submit" && $key != "subject" && $key != "required_fields" && $key != "required_email_fields" && $key != "recipient_group" && $key != "error_page" && $key != "thanks_page" && $key != "send_copy" && $key != "copy_subject" && $key != "copy_tomail_field" && $key != "mail_type" && $key != "mail_priority" && $key != "return_ip")
{
$message=$message."n<td align="left" valign="top" style="white-space:nowrap;">".$value."</td>";
}
}
if($return_ip==1)
{
$message=$message."<td align="left" valign="top" style="white-space:nowrap;">".$user_ip."</td>";
}
$message=$message."n</tr>n</table></body></html>";
}
else
{
$message="Form Results";
foreach($_POST as $key=>$value)
{
$value=stripslashes($value);
$value=nl2br($value);
if($key != "Submit" && $key != "subject" && $key != "required_fields" && $key != "required_email_fields" && $key != "recipient_group" && $key != "error_page" && $key != "thanks_page" && $key != "send_copy" && $key != "copy_subject" && $key != "copy_tomail_field" && $key != "mail_type" && $key != "mail_priority" && $key != "return_ip")
{
$message=$message."n".$key.": ".$value;
}
}
if($return_ip==1)
{
$message=$message."Sender IP: ".$user_ip;
}
}
$extra="From: ".$_POST[$reply_to_field]."n";
$extra.="X-Priority: $mail_priorityn";
$cc_tomail=$cc_tomail[$recipients];
$bcc_tomail=$bcc_tomail[$recipients];
if($cc_tomail!="")
{
$extra.="Cc: $cc_tomail;n";
}
if($bcc_tomail!="")
{
$extra.="Bcc: $bcc_tomail[$recipients]n";
}
if($mail_type=="horz_table" || $mail_type=="vert_table")
{
$extra.="MIME-Version: 1.0nContent-type: text/html; charset=iso-8859-1n";
}
$subject=$_POST["subject"];
$tomail=$tomail[$recipients];
mail ("$tomail", "$subject", "$message", "$extra");
if($send_copy=="yes")
{
$copy_extra="From: $Name<$Email>nX-Priority: $mail_priorityn";
if($mail_type=="horz_table" || $mail_type=="vert_table")
{
$copy_extra.="MIME-Version: 1.0nContent-type: text/html; charset=iso-8859-1n";
}
$copy_address=$_POST[$copy_tomail_field];
mail ("$copy_address", "$copy_subject", "$message", "$copy_extra");
}
if($thanks_page=="")
{
echo "<p>$thanks_page_title</p>";
echo "<p>$thanks_page_text</p>";
}
else
{
ob_end_clean();
$redirect="Location: ".$thanks_page;
header($redirect);
}
}
else
{
if($error_page=="")
{
echo "<p>$error_page_title</p>";
echo $error_message;
echo "<p>$error_page_text</p>";
}
else
{
ob_end_clean();
$redirect="Location: ".$error_page;
header($redirect);
}
}
}
else
{
echo "<p>Sorry, mailing request came from an unauthorized domain.</p>";
}
}
else
{
echo "<p>Error</p>";
echo "<p>No form data has been sent to the script</p>";
}
ob_end_flush();
?>


and feedback_form.php as

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<link href="styles.css" rel="stylesheet" type="text/css">
<head>
</head>
<body>
<table width="450" border="0" align="center" cellpadding="1" cellspacing="0" bgcolor="#333333">
<tr>
<td><table width="450" border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td align="center"><img src="../images/network_sites.jpg" width="451" height="102"></td>
</tr>
<tr>
<td height="1" bgcolor="#000000"></td>
</tr>
<tr>
<td align="center" class="titulo">Player's Feedback </td>
</tr>
<tr>
<td class="text">
<form id="form" method="post" action="email.php">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="55%" height="25" class="text">Your Name</td>
</tr>
<tr>
<td><input type="text" name="Name" value="<?php echo $Name; ?>" />
</td>
</tr>
<tr>
<td height="24" class="text">Your Email</td>
</tr>
<tr>
<td><input type="text" name="Email" value="<?php echo $Email; ?>" />
</td>
</tr>
<tr>
<td height="25" class="text">Comments and/or Questions</td>
</tr>
<tr>
<td><textarea name="Comments" rows="5" cols="32"><?php echo $Comments; ?></textarea>
</td>
</tr>
</table>
<p> <!-- you can create custom error or success pages, otherwise remove the domain name for below-->

<input type="submit" name="Submit" value="Submit" />
<input type="reset" name="Reset" value="Clear Form" />
<input type="hidden" name="subject" value="website email" />
<input type="hidden" name="required_fields" value="Name,Comments" />
<input type="hidden" name="required_email_fields" value="Email" />
<input type="hidden" name="recipient_group" value="0" />
<input type="hidden" name="error_page" value="http://www.123bingo.com/network/error.php" />
<input type="hidden" name="thanks_page" value="http://www.123bingo.com/network/thanks.php" />
<input type="hidden" name="send_copy" value="no" />
<input type="hidden" name="copy_subject" value="Thanks for your Email" />
<input type="hidden" name="copy_tomail_field" value="Email" />
<input type="hidden" name="mail_type" value="vert_table" />
<input type="hidden" name="mail_priority" value="3" />
<input type="hidden" name="reply_to_field" value="Email" />
<input type="hidden" name="return_ip" value="1" />
</p>

</form></td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>


I have two files as trhanks.php ans error.php
(I have php server)

How do I Do This!!

#5 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 15 July 2005 - 06:56 AM

HI,

I’ve tested this all is ok; I have altered the top bit of the email.php specifically for you. I noticed you had added a spare www to the referring domains.


// recipient configuration
$tomail[0]=" grafix_dzyner@yahoo.cohm ";
$cc_tomail[0]="";
$bcc_tomail[0]="";
$tomail[1]="";
$cc_tomail[1]="";
$bcc_tomail[1]="";
$tomail[2]="";
$cc_tomail[2]="";
$bcc_tomail[2]="";
// General Variables
$check_referrer=1;
$referring_domains="http://123bingo.com/,http://www. 123bingo.com /";
// Default Error and Success Page Variables
$error_page_title="Error - Missed Fields";
$error_page_text="Please use your browser's back button to return to the form and complete the required fields.";
$thanks_page_title="Message Sent";
$thanks_page_text="Thank you for your inquiry";


If you still have probs try using an email address with no underscore in it.
Maybe the mail function is not available to you to use.
TreV

#6 usability_guy

usability_guy

    Gravity Master Member

  • Members
  • 245 posts

Posted 15 July 2005 - 07:24 AM

Quote:-(Maybe the mail function is not available to you to use. )

Ya that is the problem it seems at the moment.
We need to setup the mail server.
So again this task is in the "to do" list
TYVM

Rams..........................

#7 Minna

Minna

    Gravity Master Member

  • Members
  • 225 posts

Posted 29 July 2005 - 05:08 PM

This seems to work and there isn't too many unnecessary features to weed out. Thanks.

#8 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 30 July 2005 - 03:20 PM

No!!

This is just about the worst kind of script that you could use :eek: First of all, there is absolutely no validation against the users inputs. For all you know, they could easily inject any kind of script for your server to process via this form.

Deadly. Secondly you are mixing PHP with HTML, which is a serious lack of software design methodologies. You could be forgiven for this, since the script and form are simple and the responsibility is self contained, but the first mistake?

Nope, in todays world you really need to prepare yourself (and others who are going to use your script) from hackers and teeny bopping script kiddies. Security is the number one concern and issue for web development, no matter what the scale is, and the task of securing your web site is never finished.

It's a never ending process of preventitive measures :lol:

#9 Minna

Minna

    Gravity Master Member

  • Members
  • 225 posts

Posted 30 July 2005 - 04:50 PM

Nope, in todays world you really need to prepare yourself (and others who are going to use your script) from hackers and teeny bopping script kiddies.

Sigh .... So one should do what?

#10 TheManBehindTheCurtain

TheManBehindTheCurtain

    Time Traveler Member

  • 1000 Post Club
  • 1035 posts

Posted 30 July 2005 - 06:00 PM

Here's a detailed and fascinating article on preventing SQL injection attacks. Although the server-side language is ASP, the general principles are very much the same:

http://www.sitepoint...on-attacks-safe

Although SQL injection attacks are the most commonly talked about, hackers also try submitting Javascript and actual server-side code into your form fields as well. Some are malicious, some are just idle miscreants, and some of course are thieves.

Some good prophylaxis is to pre-process form input to strip special characters that can't possibly be meaningful inside a form field but could be used within script languages: * = + - ( ) etc. The article above also mentions escaping characters such as a single quote, which could be a meaningful part of a submission but which is also a frequently used character in injection attacks. Restrict the length of fields to a minimum to provide less opportunity for injection of lengthy scripts. Surely some of the forum folks know of some good sites with best practices for hardening forms?

Although I think Dr. Livingston was a bit harsh, he's got a point, especially when you consider that the hidden fields in the HTML source provide an excellent roadmap into the properties that are being manipulated by the serverside script. Back mumblty-mumble years ago our gang used to get white papers from competitors without filling out registrations forms because we viewed the source, found the url to the download page, and just went there straight. (In an ironic turn of events, we later merged with one of those companies. I eventually wound up managing a combined site that had that source code, and it took us a couple of years to weed it all out. What goes around comes around.) Anyway, as a general principle, all business logic and details ought to be inside the firewall. The source reveals way, way too much about the application behind it.

I think in all fairness you have to say that form applications are one of the hardest to cleanly divide between content and functionality, especially when a single application must filter fields based on context, campaign, or whatever, and when you start doing a really good job of server-side validations. If you don't need to write a mammoth form application, one modest first step is simply to pull out the HTML chunks and load them into variables that are then referenced inside the script itself. Put all these variables into a single section and it makes it much easier to spot the repetitive bits that can be re-used.

And also in fairness I think we should note that gadzillions of sites still use script like this, and it's great of manager to help colleagues. With a little extra work, this is the start of useful learning experience. The amount of exposure and risk varies greatly depending on your server environment. In general, thieves and hackers are after big fish, and most of us are not big fish. Probably the most common exploit is hijack a mail server to use for spam. Point being, many of us can probably get away with something like this and never suffer any harm. Just like you can live without health insurance. It's the kind of thing, though, that it's too late to go out and get after you've gotten infected.

#11 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 31 July 2005 - 08:03 AM

Hi, to Dr Livingston, Frank and Minna

Thanks for your useful comments :)

It was my intention to share a script; that was much better than “the worse” examples around. This would mainly be used on remotely hosted sites. Where the Webmaster has no access to the server’s smtp, and the server’s php ini file. Several factors in the “remotely hosted environment” can have a bearing on the security of scripts.

The main features of this simple script are as follows:

This script checks to see if the request comes for your domain, this is supposed to prevent people from copying your “form code”, uploading it to their domain and pointing to your mail script.

Hides your email address from “bots” which harvest emails.

Sends the visitors ip address to you

In addition this script attempts to check the validity of the email address, and whether required fields are left empty. It’s also easy to add customised error or success pages.


To Frank: Thanks for your kind words. This script has no connection to a database, yet you say it’s vulnerable to sql injection attacks. How do we address this issue?

Could I just use regex with say preg replace to eliminate / replace words like INSERT DROP, DELETE, SHOW, FROM, and WHERE.

Many of the hidden fields values are unnecessary. If I stripped it to its “bare essentials”, will it still provide a road map for naughty people?


To Dr Livingstone,
Can you please “paste us in” your secure alternative script/ or method? Then my objective will be achieved (sharing a nice form)

Deadly. Secondly you are mixing PHP with HTML, which is a serious lack of software design methodologies.


Is this just in the context of php forms, or generally? Looking forward to hearing more on this...........

TreV

#12 TheManBehindTheCurtain

TheManBehindTheCurtain

    Time Traveler Member

  • 1000 Post Club
  • 1035 posts

Posted 31 July 2005 - 11:54 AM

Hi manager ...

Sorry if it sounded like I was saying the script was vulnerable to SQL injection attacks specifically. I was just giving that as example. That particular essay is a favorite of mine - it shows you some of the techniques that hackers employ to use entry fields to get deeper inside your system, in ways that are quite remarkable and, one must admit, clever. It's worth a read just for the level of insight. Later I mentioned that other methods of attack include injecting JavaScript (in case the server executes server-side JS) and also native script as well. Go googling for "php injection attack" and you'll find eye-opening stuff.

It would be interesting to hear to what extent other folks on the forums harden their forms against hacking. I bet many of us know the best practice and yet don't always follow it when time is short and the scope of the form we are doing is limited. I plead guilty (with "extenuating circumstances"!) myself.

What would be great is to see this form evolve with a few hardening routines. It would be very instructive to see it taken to the next level. I'd love to hear what other programmers on the forum do in this regard.

#13 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 31 July 2005 - 03:21 PM

Well, I can't share any script due to contractual obligations, but what I can do is help spread some experience and I'll get back to you on that once I have some time.

Is this just in the context of php forms, or generally?


I'd say in general terms, you need to separate your PHP from your HTML. For example, if you have PHP in a HTML template, and your web designer makes changes, they could in all probability, mess up your PHP and thus introduce all sorts of problems?

That is one example. What I do is to have placeholders in the HTML template, which are replaced at runtime by other HTML fragments via the Composite View design pattern. Each Composite represents a part of the page, and is responsible in generating the content of it's HTML fragment.

For a better understanding of this, and what I am talking about, you may want to check out www.sitepointforums.com, under the PHP Application Design sub-forum? Search for the term 'MVC', find out more about this, read up on it and you'll have a far better methodology to developing server-side.

MVC stands for Model, View and Controller, and it works like this:

Model

This is where the business logic goes, for example you want to check if someone is who they say they are when they attempt to log in? You need to verify their username/email and their password against your database records, so this is where this happens.

It's said to be business logic.

View

This is how you represent your data to the user, typically it's a web page in our case via a browser. The View takes the Model data, and places it into the HTML template. How it does this is up to you the developer, there are countless methods of doing this.

You also have what is called Presentational Logic, such as for example this would be when you have a negative number, and you need to show it as red, and not black as in an on-line bank statement? Another example of Presentational Logic, is having alternating coloured rows...

Controller

This is what decided what action to take based on what the user requested to do. So the user clicks a link or button? The Controller is the first place everything starts from. The Controller decides which Model(s) to use, and how they should be used, and passes these Model(s) to the View.

You have a FORM and it's submitted? The Controller handles the processing of the FORM, from validating the user inputs, to passing the validated inputs to the Model layer, ready to be inserted into your database for example.

The Controller handles sending an email if that is required as well for example?

Hope this gives you a few clues, but when I'm talking about MVC (or anyother design pattern), I'm talking in terms of object oriented programming, and not (as shown in the examples you've posted) procedural programming, which may be a hinderance to you?

That is not to say that you can't use MVC with procedural programming, it just means that the implementation is going to be different, that's all :)

#14 DaveChild

DaveChild

    Honored One Who Served Moderator Alumni

  • Hall Of Fame
  • 3446 posts

Posted 01 August 2005 - 04:46 AM

Deadly. Secondly you are mixing PHP with HTML, which is a serious lack of software design methodologies. You could be forgiven for this, since the script and form are simple and the responsibility is self contained, but the first mistake?


That's not quite as bad as many people think. PHP is intended to be used in exactly this fashion. It is a feature of the language, and while it goes against traditional software design methodologies (e.g. MVC), it is still a perfectly valid way to do things in PHP. It's not the best way to do things, by any means, but for many it is the only way.

One major problem with the above (aside from it being a perfect spam relay) is the referrer check. First, anyone wanting to manipulate the form could easily spoof the referrer. Second, plenty of people have their referrer field intentionally hidden. This script may prevent normal users from emailing you (which is completely unacceptable in any serious site).

#15 aboyd

aboyd

    Whirl Wind Member

  • Members
  • 84 posts

Posted 01 August 2005 - 06:23 AM

Sigh .... So one should do what?

There is a thread here on Cre8asite that discusses ways to stop bad data from killing your server:

http://www.cre8asite...der=asc&start=0

What's interesting is, almost everyone posting that thread is also posting here now. So I think you guys have seen a lot of example code for how to clean up data. Now it's just time to put it into practice! :)

-Tony

#16 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 01 August 2005 - 02:03 PM

PHP is intended to be used in exactly this fashion.


True. Sometimes I forget that I am scripting large and at times complex applications for office networks...

In that event you do need to be using large scale methodologies and best practices, to not only offer better software to your clients, but also, so that other developers can see how the software it's self, expresses it's self.

If on the other hand you have a typical web site with small to medium growth you could in an average, get away with 'spagetti' code, as it's known. That solves the prolem short to medium term, but long term with sustained growth, content or otherwise, you are going to be faced with a seriously major overhaul of the entire website.

I've been there, and it's frightening :eek:

#17 aboyd

aboyd

    Whirl Wind Member

  • Members
  • 84 posts

Posted 01 August 2005 - 05:11 PM

By the way, if y'all want to see an ingenious hacking attempt and how it was done, check out the third comment down (by thomas at nospam dot deliduka dot com) on this page:

http://www.php.net/mail

I haven't yet tried to duplicate his problem, to see if my addslashes/htmlspecialchars methodology will prevent the badness he found.

I hate black hats, but I admire their smartness.

-Tony

#18 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 02 August 2005 - 05:08 AM

Folks:
I have now significantly modified the original script, taking on board all constructive comments made here, and recommendations on the “php.net link”, posted by Tony.

I feel that now I have relatively secure script, as I have failed to replicate several exploits.

I my opinion, this post has nothing to do with the scale or complexity of the application. Whether you take an OOP/procedural approach to this problem is completely irrelevant. That is to say, that if you haven’t got the appropriate “validation functions” in your class, you’re just as vulnerable.

To “high fliers” with superior knowledge of php: Telling us what’s wrong with the script is great! but it would be even better, if you could post code samples illustrating possible solutions :) .

TreV

#19 Scratch

Scratch

    Light Speed Member

  • Members
  • 964 posts

Posted 02 August 2005 - 06:16 AM

Great, manager! Please would you post it up?

#20 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 02 August 2005 - 08:25 AM

I’m not ready for another mauling! :)

On a serious note, I wanted to post my new code straight away, but concluded that I could not, for commercial reasons.

TreV

#21 BillSlawski

BillSlawski

    Honored One Who Served Moderator Alumni

  • Hall Of Fame
  • 15644 posts

Posted 02 August 2005 - 08:32 AM

Telling us what’s wrong with the script is great! but it would be even better, if you could post code samples illustrating possible solutions


That would be great if someone would. I'd like to see some. Thanks!

#22 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 02 August 2005 - 09:25 AM

but it would be even better, if you could post code samples illustrating possible solutions


I'm on a break at the moment, and hardly near a PC with PHP on it but I'm in the middle of putting together some examples for you so patience :)

#23 aboyd

aboyd

    Whirl Wind Member

  • Members
  • 84 posts

Posted 02 August 2005 - 02:48 PM

Gosh, I can post some. Although I'd ask that readers go easy on me here, because I'm banging this out from memory.

It's actually really easy. Every bit of data that comes in from a form, or cookie, or however, needs to be validated somehow. So if you are expecting a number, say an id, then when it comes in, you do this:

$id = preg_replace('/[^0-9]/', '', $_GET['id']);

On the right side you have the id as it came in. In the middle area it's getting stripped down to numbers only (the carat ^ means "not" and the 0-9 means zero through nine, so anything that is not 0-9 is getting removed). And on the left, that's the new numbers-only $id.

Of course, 99% of the time, the id will come in as a number anyway, and will be unchanged through the "cleansing" process. That's fine. You're worried about the 1% who send in something really nasty and unexpected.

The other thing you can do with incoming data, especially if you don't know what it should look like, is to just do some general protective stuff on it. Like this:

$comment = htmlspecialchars(trim(strip_tags(addslashes($_POST['comment']))));
Woo, I'm sure there's a typo in there somewhere. Anyway, this one works right to left, too. The idea: first, add slashes to the incoming data, which prevents SQL injection. Then, strip tags, so that JavaScript tags and other potential problems are removed. Then, trim to get rid of surrounding whitespace that can arise from strip_tags. Then, htmlspecialchars will transform certain control characters into harmless escape sequences.

Ohh! I just realized what I've left off. htmlspecialchars has an option, called ENT_QUOTES or something, that should be turned on. I'm not sure of the syntax. I think it's like this, htmlspecialchars(string_goes_here, ENT_QUOTES);

Anyway, general rule about incoming data is "don't trust it." Either run a regex to force it into the format you're expecting, or transform it with things like addslashes and strip_tags.

Also, note that on a lot of systems, addslashes happens automatically. There are ways to check for that. You can look up addslashes on php.net.

-Tony

#24 pinbrook

pinbrook

    Gravity Master Member

  • Members
  • 213 posts

Posted 03 August 2005 - 12:34 AM

I always use the script at http://nms-cgi.sourc...t/scripts.shtml

it hides the email address in the cgi script

#25 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 03 August 2005 - 09:41 AM

Using GLOBALs is a bad idea when you start to develop your software in layers, as it should be done. By GLOBALs I mean $_GET, $_POST, et al

So just how do you access this data then? You use what is called a Request object, it's partner is called a Response object. The two go hand in hand, but lets focus on the first shall we?

The Request object basically encapsulates your Request, ie What the user has sent to you, from the client (browser in other words). The Request encapsulates $_REQUEST, $_GET, $_POST, and $_COOKIE parameters. It may also for convienence, tackle $_SESSION as well, but a lot of developers I come across avoid this, as $_SESSION has nothing to do with a Request.

Why? Well, an object has very specific responsibilities, there is no point mixing those responsibilities. So, going by the snippet posted above, I'd have something like this instead:


if( $id = $validator -> isAlpha( $handler -> getRequestParameter( 'id' ) ) ) {

// ... all went well

}

// ... something wrong has happened

What I do is to encapsulate both the Request and the Response objects behind another object, called (wait for it...) a RequestHandler. The Request object has as I said earlier specific responsibilities yes?

What if you want to other logic for example? You could I suppose, leave it to the client script that uses the Request, but you may be repeating pieces of script all over your application, so the additional responsibility goes into the RequestHandler object, which means that you can re-use the Request object at a later date.

How can you re-use it? Well, the Request object therefore does not have application specific logic (responsibility) in it has it?... It's in the RequestHandler object instead, which you can throw away, and just script another one for another application, so you re-using the Request in that sense.

Application logic for example, may be that from application to application, you need to verify that an ID is of the correct format, ie

* The length of the parameters value
* The parameters value is an integer, or is between a range of numbers
* etc

Does this make sense? Hope it helps anyways :(

#26 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 03 August 2005 - 09:55 AM

The idea: first, add slashes to the incoming data, which prevents SQL injection.


This is dangerous... You are making the assumption that in the PHP INI file, Magic Quotes are on. First, you need to check for this, and then act accordingly. For the record, and to help you out, here is my Request class below for public domain:

class HttpRequest {

  private $cookies = array();

  private $sessions = array();

  private $parameters = array();

  

  public function __construct() {

  	foreach( $this -> sanitise( $_COOKIE ) as $parameter => $value ) {

    $this -> cookies[strtolower( $parameter )] = $value;

  	}

  	foreach( $this -> sanitise( $_SESSION ) as $parameter => $value ) {

    $this -> sessions[strtolower( $parameter )] = $value;

  	}

  	foreach( $this -> sanitise( array_merge( $_GET, $_POST ) ) as $parameter => $value ) {

    $this -> parameters[strtolower( $parameter )] = $value;

  	}

  }

  

  public function setSession( $session, $value ) {

  	$this -> sessions[strtolower( $session )] = $this -> sanitise( $value );

  }

  

  public function getCookie( $cookie ) {

  	if( $this -> hasCookie( $cookie ) ) {

    return $this -> cookies[$cookie];

  	}

  	return false;

  }

  

  public function getSession( $session ) {

  	if( $this -> hasSession( $session ) ) {

    return $this -> sessions[$session];

  	}

  	return false;

  }

  

  public function getParameter( $parameter ) {

  	if( $this -> hasParameter( $parameter ) ) {

    return $this -> parameters[$parameter];

  	}

  	return false;

  }

  

public function getInteger( $parameter ) {

  	if( $this -> hasParameter( $parameter ) ) {

    if( is_int( $this -> hasParameter( $parameter ) ) ) {

return $this -> parameters[$parameter];

  	}

}

  	return false;

  }



  private function sanitise( $parameters ) {

  	if( is_array( $parameters ) ) {

    $tmp = array();

    foreach( $parameters as $parameter => $value ) {

    	if( get_magic_quotes_gpc() ) {

      $value = stripslashes( $value );

    	}

    	$tmp[$parameter] = $value;

    }

    return $tmp;

  	}

  }

  

  private function hasCookie( $cookie ) {

  	return array_key_exists( $cookie, $this -> cookies );

  }

  

  private function hasSession( $session ) {

  	return array_key_exists( $session, $this -> sessions );

  }

  

  private function hasParameter( $parameter ) {

  	return array_key_exists( $parameter, $this -> parameters );

  }

	}

This takes care of the problem automatically for use via the private sanitise( $parameters ) class method :) How to use it? Here is an example...


$request = new HttpRequest();

if( $id = $request -> getParameter( 'page' ) ) {

// ... parameter exists, and has a value

) 

// ... something gone wrong, ie the parameter does not exist

Or you expect an integer, and just to confirm that the parameter you want actually is an integer, you'd use this


$num = $request -> getInteger( 'num' );


By the way,

$comment = htmlspecialchars(trim(strip_tags(addslashes($_POST['comment']))));

Using object oriented programming methodologies, to tackle the above you'd apply what is known as Filters prior to any validation. Something else for you to think about :)

#27 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 03 August 2005 - 01:20 PM

Three cheers for the good Doctor!

I was going to post leaner, improved version of the first helping of spaghetti, but I held back, as I knew your code would be more useful. I’m sure this is a post of interest to many. I know it's asking a lot, my knowledge of OOP with php is limited.

How do we "go about" adding the form to be processed?
I assume we will need to “require” or “include” your class in the “form page”

I see you constructing a new object here:
$request = new HttpRequest(); 

if( $id = $request -> getParameter( 'page' ) ) { 

// ... parameter exists, and has a value 

) 

// ... something gone wrong, ie the parameter does not exist

Q1 Are we to construct a new object in the where the form is displayed
Q2 does your code serve to sanitise the inputs before passing to the form code.
Q3 Could you please throw "us penguins" another fish:lol:
Q4 With the utmost respect, can you /*comment*/ your class to make it easier for us to analyse.

This is dangerous... You are making the assumption that in the PHP INI file, Magic Quotes are on .

In my experience in most remotely hosted situations, MQs are off

Sincere thanks for your fantastic contributions, Doc

TreV

#28 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 03 August 2005 - 01:43 PM

Do we use the class to construct “an input filter” then just point the html form to the page with the “input filter”.
On line 2 of the code below: does ‘page’ represent one of our form inputs?

$request = new HttpRequest(); 

if( $id = $request -> getParameter( 'page' ) ) { 

// ... parameter exists, and has a value 

) 

// ... something gone wrong, ie the parameter does not exist

TreV

#29 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 04 August 2005 - 10:10 AM

The class I posted only does one thing, and that is to encapsulate your Request. It does nothing else... Remember the golden rule of OOP: A class has only one responsibility, and nothing more than what it should actually be doing, so...

For filtering a Request, you'd require another class(es) for that. Typically you have a concreate class called a Validator, and whereby you pass through this Validator, a number of Rules (one rule == one class), along with the Request, ie


// ...

$email = new RequiredRule( new EmailRule( '64', $request -> getParameter( 'email' ) ) );

$validator -> attach( $email );

$telephone = new RequiredRule( new TelephoneNoRule( 11, $request -> getParameter( 'telephone' ) ) );

$validator -> attach( $telephone );

// ... other rules

if( $validator -> isValid() ) {

// ... all user inputs are valid

}

// ...


This is just a basic example as it's more complicated of course ;) Note I gave an example of the Decorator design pattern for you? Here...


$email = new RequiredRule( 

// the first object is the decorator, and the decorated object is 

// the second, (or third or whatever) object

new EmailRule( ... ) );

The interface that the *Rules implements, has to be implemented also, by the class that does the decoration, which is important, ie if the decorator does not implement the same interface, then something like this would cause an error,


// ...

public function class_method_name( IRule $rule ) {

// ...

}

So, class EmailRule() implements the IRule interface, if you decorate this with the RequiredRule(), and it's not implementing IRule, you'll get an error, if that makes sense?

#30 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 04 August 2005 - 10:25 AM

Q1 Are we to construct a new object in the where the form is displayed
Q2 does your code serve to sanitise the inputs before passing to the form code.
Q3 Could you please throw "us penguins" another fish:lol:
Q4 With the utmost respect, can you /*comment*/ your class to make it easier for us to analyse.


A1. You'd create an instance of the class prior to checking the form submissions, ie


<html> ... rest of page ...

<?php 

$request = new HttpRequest();

if( $request -> getParameter( 'submit' ) ) {

// ... form has been submitted, so

// validate your user inputs at this point

} else {

?><form name="Test" action="test.php" method="post">

<input type="text" ...>

... rest of form goes here...

<input type="submit" name="submit" value="send" />

<?php } // close off php script ?></body></html>

....

...


But since I layer my scripts based on the MVC model, I have the form submission check and user input validation within the Controller instead. Based on this (validation), the Controller chooses which template to show the user, but I hope the above example makes more sense?

A2. By sanitise, I mean that all it does is to cleanup the input from single quoted characters, such as ', ", etc. For more clarity, there is a part in the online manual which will explain more that what I could.

I'll see if I can find the link for you. But there is no filtering, as that isn't what a Request is about.

A3. I'll see what I can do, I'm trying to drip feed you with examples and methodologies, best practices, etc more that actual applicaiton script which I can't post.

A4. Comments I tend to put in PHPDocumentor format, which is more for API documentation, other than that I tend to leave them out as Unit Testing is primarly used for documentation, other than in-line documenation.

But I'll try adding some as I go ;)

#31 matthewmag

matthewmag

    Whirl Wind Member

  • Members
  • 86 posts

Posted 04 August 2005 - 05:42 PM

I'm generally far too intimidated to post in "website programming" (not much of a programmer) but we have had professional security audits carried out in the past and hired someone to work on protecting our forms as a result...... So while I'm not the person to ask about the code itself, it may be useful to mention a few general principles which we learnt as a result........

The most important of these is that it's no good relying on just one method to ensure that the input in a form is "clean". One of my uneducated questions during a security audit was "why do we need to do anything else since we're using magic quotes - doesn't that render everything harmless?" And it does - until an exploit is found. Likewise anything that offers just a single layer of protection........

So assuming that we're already using something like magic quotes or addslashes (forgive my lack of formalism - like I said, I'm no programmer) what else can be done?

Firstly I notice that people here are talking about validation and sanitisation. For people like myself who might be reading here - I'll try to define them.

Validation is the process of verifying that the input is the type of input you expect in that particular field. e.g. that anything in the field for "email" looks like an email.........

Sanitisation is the process of rendering inert any potentially harmful characters or code (e.g. sql injection, javascript (or other script), html) that might be entered into a particular field.

Good security requires both of these.

One of the things we found is very simple. Many fields require only a limited number of characters - telephone, email, name etc........ by not allowing and stripping away any excess characters, you're denying the opportunity of overflow attacks and the entering of any complex scripts. Always having a maximum number of characters is clearly a good idea - even if it's a high number.

You also have to be careful exactly what you do with text that contains "potentially" dangerous characters. It depends what kind of information you're looking to gather in your form but the inverted commas around "potentially" or the apostrophe in O'Grady are potentially harmful but in this case quite legitimate. In addition to the use of standard php tools, we use a sanitisation script which converts all unusual characters to their html counterparts, thus rendering them harmless. We log any potential sql injection so that we can learn what people are attempting............

I hope that's useful to someone - sorry I haven't included any code - but I think that the philosophy of not relying on one method of security is a good one.........

Matt.

#32 ambassador

ambassador

    Gravity Master Member

  • Members
  • 127 posts

Posted 04 August 2005 - 10:04 PM

-------
Aug 4, 2005


Given the intricate and apparently necessary steps that must be implemented to produce a reasonably secure form, it appears that I may never be able to make one.

Can a truly proper form script be purchased Dr_Livingston/Matt/anyone?

Ambassador
-------

#33 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 05 August 2005 - 07:29 AM

Maybe not bought in the sense of purchising something but you should be able to contract a developer to script a solution for you cheaply enough.

It's not a complex nor a time consuming task to do, going by the complexity of the form of course :( But the real problem for you will be trying to find a reputable developer in the first place, who knows the security issues of today.

Taking care of the basics is one thing, but taking care of avoiding loopholes is another... It just takes one person to find an exploit, and bang, it's all over the internet, which is even more potentially harmful if the site in question is well known, has an ecommerce presense, etc.

#34 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 24 August 2005 - 06:54 AM

Given the intricate and apparently necessary steps that must be implemented to produce a reasonably secure form, it appears that I may never be able to make one.


Don’t give up ambassador, this is defeatist talk! :)


But the real problem for you will be trying to find a reputable developer in the first place, who knows the security issues of today.

Good point ! in a perfect world it would be better to find a developer who knows the possible security issues of TOMMORROW not just today !

I will probably get slated for this, but I feel it is important to make the level of security appropriate to the risk. For example you would not fit a £20,000 security system on a £300 car !

The key thing is to provide reasonably secure forms, and make your clients aware of the risks. If the client decides they wish to pay for increased security, then you can focus more resources in that area, and charge accordingly.


TreV

#35 MorgZ

MorgZ

    Gravity Master Member

  • Members
  • 132 posts

Posted 24 August 2005 - 08:42 AM

What's interesting is, almost everyone posting that thread is also posting here now. So I think you guys have seen a lot of example code for how to clean up data. Now it's just time to put it into practice!


Just thought i should post here just to proove aboyds theory!

[Edit: and prove that i still cant spell! grrr :mad: ]

#36 manager

manager

    Time Traveler Member

  • 1000 Post Club
  • 1331 posts

Posted 24 August 2005 - 03:46 PM

Morgz,

Your right mate, all the usual suspects chatting 'bout forms, it's because we love, forms ;)

I have since stripped it to it’s minimum and added more security, and moved on.... I haven't posted my updated code because of the reception my last code received.
But seriously, I think it's only fair to allow someone else to "show us how it should be done", and of share their complete working script.


TreV

#37 Jonny

Jonny

    Ready To Fly Member

  • Members
  • 32 posts

Posted 25 August 2005 - 07:49 AM

I have a related PHP form question. I have a form on my site that allows alumni from my high school to csubmit contact info. Recently I was going through the submitted data and noticed that there were about 20 or 25 submissions that were in the form of jkjkj@mydomain.com or bldw@mydomain.com . It was almost as if a bot was just entering a ton of email addresses (even though the fields were not meant for email addresses) that were from my domian. I deleted the entries but I have no clue what is going on and why this happened.

Any ideas anyone? Was someone trying to obtain info from my DB?

#38 DaveChild

DaveChild

    Honored One Who Served Moderator Alumni

  • Hall Of Fame
  • 3446 posts

Posted 25 August 2005 - 08:08 AM

Unlikely, Jonny. More likely is that this was a spambot of sorts, automatically filling out forms and using garbage data (usually in the hopes of generating links to a site). If your form had "email" as the name of this field, that might help explain it.

#39 Jonny

Jonny

    Ready To Fly Member

  • Members
  • 32 posts

Posted 25 August 2005 - 08:24 AM

WHEW! That makes me feel better! Thanks for your response!

#40 Dr_Livingston

Dr_Livingston

    Gravity Master Member

  • Members
  • 172 posts

Posted 26 August 2005 - 04:49 PM

If you want to dump all over those bots then one simple solution, though it does have usability issues (be warded), is to use one of those CAPTCHA approaches, whereby the user also has to enter the word as depicted by an image, into a form element.

Since bots (at the moment at least) cannot read images, you just repost the form until the required word is submitted as well. There is an article on www.sitepoint.com which covers the basics, if your interested?

There is I suppose, various other helpful resources if you Goggle for them :D



RSS Feed

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users