Newbie using someone elses code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pzh20
Forum Newbie
Posts: 2
Joined: Sat Jul 01, 2006 5:23 am

Newbie using someone elses code

Post by pzh20 »

I am completely new to PHP (plenty of other languages) and have been asked to use a form to send an email for a clients web site. However, I get the following errors

Notice: Undefined index: subject in C:\xx\xx\hhhconsulting.co.uk\contact\contact_form\aformmail.php on line 294

Notice: Use of undefined constant email_from - assumed 'email_from' in C:\xx\xx\hhhconsulting.co.uk\contact\contact_form\aformmail.php on line 241

Warning: mail() [function.mail]: SMTP server response: 501 5.5.4 Invalid Address in C:\xx\xx\hhhconsulting.co.uk\contact\contact_form\aformmail.php on line 245

Warning: Cannot modify header information - headers already sent by (output started at C:\xx\xx\hhhconsulting.co.uk\contact\contact_form\aformmail.php:294) in C:\xx\xx\hhhconsulting.co.uk\contact\contact_form\aformmail.php on line 91

from the folowing code (I've highlighted the lines with <-------Line xx etc but not sure they line up exactly). I really need an answer to this if anyone can help. Maybe it's to do with the PHP installation options on my server as my client says this code works as is elsewhere. To see the options, go to http://www.hhhconsulting.co.uk/test.php

Many thanks

<?
/**
* aFormMail script - sending mail via form
*
* Author: Alex Scott
* Email: alex@cgi-central.net
* Web: http://www.cgi-central.net
* Details: The installation file
* FileName $RCSfile: aformmail.php,v $
* Release: 1.1 ($Revision: 1.6 $)
*
* Please direct bug reports,suggestions or feedback to the cgi-central forums.
* http://www.cgi-central.net/forum/
*
* aMember is free for both commercial and non-commercial use.
* Re-distribution of this script without prior consent is strictly prohibited.
*
*/

/*****************************************************************************
* *
* C O N F I G U R A T I O N *
* *
*****************************************************************************/

// email for send submitted forms //////////////////////////////////////////
// if empty, use value from form ('send_to' field)
$send_to = "Pete <pete@hhhconsulting.co.uk>";

// set $send_cc address if you need copy of mail to other addresses
// for example: $send_cc = array('friend1@ccc.cc', 'friend2@ccc.cc');
//
$send_cc = array();

// Subject. if empty, use value from form ('subject' field)
$subject = "From Cityboxer site via Area17";

// Allowed Referres. Should be empty or list of domains
$referrers = array();

// Attachments
$attachment_enabled = 0;

////// Database - write CSV file with data of submitted forms //////////////
$database_enabled = 1;
$database_file = 'cityboxer_db1.csv';

// Fields to collect
// $database_fields = '*' - mean all fields, as in form
// $database_fields = array('from', 'subject') - only 'from', 'subject' fields
$database_fields = '*';

////// Redirect user after submitting form
$redirect_url = 'thankyou.html';

////// Auto-Responder
////// You can substitute any of form fields in response by using
////// %field_name% in response text.
//////
$autoresponder_enabled = 0;
$autoresponder_from = $send_to;
$autoresponder_subject = "%subject% (autoresponse)";
$autoresponder_message = <<<MSG
Hi %name_from%,

Thank you for your submission.

MSG;

/***************************************************************************/

function do_formmail(){
global $autoresponder_enabled, $database_enabled;
$form = get_form_data();
$errors = check_form($form);
if ($errors) {
display_errors($errors);
return;
}
send_mail($form);
if ($autoresponder_enabled)
auto_respond($form);
if ($database_enabled)
save_form($form);
redirect();
}

function redirect(){
global $redirect_url;
header("Location: $redirect_url");
exit(); <---------- Line 91
}


function save_form($vars){
global $database_file, $database_fields;
$f = fopen($database_file, 'a');
if (!$f){
die("Cannot open db file for save");
}
foreach ($vars as $k=>$v) {
$vars[$k] = str_replace(array("|", "\r","\n"), array('_',' ',' '), $v);
}
if (is_array($database_fields)) {
$vars_orig = $vars;
$vars = array();
foreach ($database_fields as $k)
$vars[$k] = $vars_orig[$k];
}
$str = join('|', $vars);
fwrite($f, $str."\n");
fclose($f);
}

function auto_respond($vars){
global $autoresponder_from, $autoresponder_message, $autoresponder_subject;
/// replace all vars in message
$msg = $autoresponder_message;
preg_match_all('/%(.+?)%/', $msg, $out);
$s_vars = $out[1]; //field list to substitute
foreach ($s_vars as $k)
$msg = str_replace("%$k%", $vars[$k], $msg);
/// replace all vars in subject
$subj = $autoresponder_subject;
preg_match_all('/%(.+?)%/', $subj, $out);
$s_vars = $out[1]; //field list to substitute
foreach ($s_vars as $k)
$subj = str_replace("%$k%", $vars[$k], $subj);
//
$_send_to = "$vars[name_from] <".$vars[email_from].">";
$_send_from = $autoresponder_from;
mail($_send_to, $subj, $msg, "From: $_send_from");
}

function _build_fields($vars){
$skip_fields = array(
'email_to',
'name_to',
'subject');
// order by numeric begin, if it exists
$is_ordered = 0;
foreach ($vars as $k=>$v)
if (in_array($k, $skip_fields)) unset($vars[$k]);

$new_vars = array();
foreach ($vars as $k=>$v){
// remove _num, _reqnum, _req from end of field names
$k = preg_replace('/_(req|num|reqnum)$/', '', $k);
// check if the fields is ordered
if (preg_match('/^\d+[ \:_-]/', $k)) $is_ordered++;
//remove number from begin of fields
$k = preg_replace('/^\d+[ \:_-]/', '', $k);
//remove 'from' in labels
$k = preg_replace('/from/', '', $k);
$new_vars[$k] = $v;
}
$vars = $new_vars;

$max_length = 10; // max length of key field
foreach ($vars as $k=>$v) {
$klen = strlen($k);
if (($klen > $max_length) && ($klen < 40))
$max_length = $klen;
}

if ($is_ordered)
ksort($vars);

// make output text
$out = "";
foreach ($vars as $k=>$v){
$k = str_replace('_', ' ', $k);
$k = ucfirst($k);
$len_diff = $max_length - strlen($k);
if ($len_diff > 0)
$fill = str_repeat('.', $len_diff);
else
$fill = '';
$out .= $k."$fill...: $v\n";
}
return $out;
}


function send_mail($vars){
global $send_to, $send_cc;
global $subject;
global $attachment_enabled;
global $REMOTE_ADDR;

global $HTTP_POST_FILES;
$files = array(); //files (field names) to attach in mail
if (count($HTTP_POST_FILES) && $attachment_enabled){
$files = array_keys($HTTP_POST_FILES);
}

// build mail
$date_time = date('Y-m-d H:i:s');
$mime_delimiter = md5(time());
$fields = _build_fields($vars);
$mail = <<<EOF
This is a MIME-encapsulated message

--$mime_delimiter
Content-type: text/plain
Content-Transfer-Encoding: 8bit

$fields
EOF;

if (count($files)){
foreach ($files as $file){
$file_name = $HTTP_POST_FILES[$file]['name'];
$file_type = $HTTP_POST_FILES[$file]['type'];
$file_tmp_name = $HTTP_POST_FILES[$file]['tmp_name'];
$file_cnt = "";
$f=@fopen($file_tmp_name, "rb");
if (!$f)
continue;
while($f && !feof($f))
$file_cnt .= fread($f, 4096);
fclose($f);
if (!strlen($file_type)) $file_type="applicaton/octet-stream";
if ($file_type == 'application/x-msdownload')
$file_type = "applicaton/octet-stream";

$mail .= "\n--$mime_delimiter\n";
$mail .= "Content-type: $file_type\n";
$mail .= "Content-Disposition: attachment; filename=\"$file_name\"\n";
$mail .= "Content-Transfer-Encoding: base64\n\n";
$mail .= chunk_split(base64_encode($file_cnt));
}
}
$mail .= "\n--$mime_delimiter--";


//send to
$_send_to = $send_to ? $send_to : "$vars[name_to] <".$vars[email_to].">";
$_send_from = "$vars[name_from] <".$vars[email_from].">";
$_subject = $subject ? $subject : $vars['subject'];
<--------- Line 241
mail($_send_to, $_subject, $mail,
"Mime-Version: 1.0\r\nFrom: $_send_from\r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline");
<--------- Line 245
foreach ($send_cc as $v){
mail($v, $_subject, $mail,
"Mime-Version: 1.0\r\nFrom: $_send_from\r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline");
}

}

function get_form_data(){
global $REQUEST_METHOD;
global $HTTP_POST_VARS;
global $HTTP_GET_VARS;

$vars = ($REQUEST_METHOD == 'GET') ? $HTTP_GET_VARS : $HTTP_POST_VARS;
//strip spaces from all fields

$parts=array();
foreach ($vars as $k=>$v) {
if ($k=="send" || $k=="submit") {
$parts=$parts+array($k=>$v);
}
}
$vars=(array_diff($vars,$parts));
//exit;

return $vars;
}

function check_form($vars){
global $referrers;
global $send_to;
global $subject;
global $HTTP_REFERER;

$errors = array();

// check from email set
if (!strlen($vars['email_from'])){
$errors[] = "<b>From Email address</b> empty";
} else if (!check_email($vars['email_from'])){
$errors[] = "<b>From Email address</b> incorrect";
}
if (!strlen($send_to) && !strlen($vars['email_to'])){
$errors[] = "<b>To Email</b> address empty (possible configuration error)";
} else if (!strlen($send_to) && !check_email($vars['email_to'])){
//if to email specified in form, check it and display error
$errors[] = "<b>To Email address</b> incorrect";
}
if (!strlen($vars['subject']) && !strlen($subject)){
$errors[] = "<b>Subject</b> empty (possible configuration error)";
} <------------ Line 294
foreach ($vars as $k=>$v){
// check for required fields (end with _req)
if (preg_match('/^(.+?)_req$/i', $k, $m) && !strlen($v)){
$field_name = ucfirst($m[1]);
$errors[] = "Required field <b>$field_name</b> empty";
}
// check for number fields (end with _num)
if (preg_match('/^(.+?)_num$/i', $k, $m) && strlen($v) && !is_numeric($v)){
$field_name = ucfirst($m[1]);
$errors[] = "Field <b>$field_name</b> must contain only digits or be empty";
}
// check for number & required fields (end with _reqnum)
if (preg_match('/^(.+?)_reqnum$/i', $k, $m) && !is_numeric($v)){
$field_name = ucfirst($m[1]);
$errors[] = "Field <b>$field_name</b> must contain digits and only digits";
}
}

//check referrer
if (is_array($referrers) && count($referrers)){
$ref = parse_url($HTTP_REFERER);
$host = $ref['host'];
$host_found = 0;
foreach ($referrers as $r){
if (strstr($host, $r))
$host_found++;
}
if (!$host_found){
$errors[] = "Unknown Referrer: <b>$host</b>";
}
}
return $errors;
}

function display_errors($errors){
$errors = '<li>' . join('<li>', $errors);
print <<<EOF

<html><!-- InstanceBegin template="/Templates/main.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<!-- InstanceBeginEditable name="doctitle" -->
<title>mobile personal training - nutritional advice - massage - Move Your Butt
</title>
<!-- InstanceEndEditable -->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<!-- InstanceBeginEditable name="head" --><!-- InstanceEndEditable -->

<link href="mybcss1.css" rel="stylesheet" type="text/css">
</head>

<body bgcolor="#F1EFE2" leftmargin="0" topmargin="0" onLoad="MM_preloadImages('images/topnav/but_home_f2.gif','images/topnav/but_mobile_f2.gif','images/topnav/but_massage_f2.gif','images/topnav/but_trainers_f2.gif','images/topnav/but_press_f2.gif','images/topnav/but_links_f2.gif','images/topnav/but_contact_f2.gif','images/topnav/but_online_f2.gif','images/topnav/but_testimonials_f2.gif','images/topnav/but_nutrition_f2.gif')">
<table width="920" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#663300" class="body">
<tr>
<td width="15"><img src="images/spacer.gif" width="31" height="170"></td>

<td width="654"><img src="images/myb_logo.gif" width="351" height="145"></td>
<td width="254">&nbsp;</td>
</tr>
<tr bgcolor="#714112">
<td><img src="images/spacer.gif" width="20" height="40"></td>
<td colspan="2"><a href="index.htm" target="_top" onClick="MM_nbGroup('down','group1','home','',1)" onMouseOver="MM_nbGroup('over','home','images/topnav/but_home_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img src="images/topnav/but_home.gif" alt="home" name="home" width="43" height="21" border="0" onload=""></a><a href="mobile.htm" target="_top" onClick="MM_nbGroup('down','group1','mobile','',1)" onMouseOver="MM_nbGroup('over','mobile','images/topnav/but_mobile_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img src="images/topnav/but_mobile.gif" alt="mobile personal trainers" name="mobile" width="179" height="21" border="0" onload=""></a><a href="nutrition.htm" target="_top" onClick="MM_nbGroup('down','group1','nutrition','',1)" onMouseOver="MM_nbGroup('over','nutrition','images/topnav/but_nutrition_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img src="images/topnav/but_nutrition.gif" alt="nutrition" name="nutrition" width="73" height="21" border="0" onload=""></a><a href="massage.htm" target="_top" onClick="MM_nbGroup('down','group1','massage','',1)" onMouseOver="MM_nbGroup('over','massage','images/topnav/but_massage_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img src="images/topnav/but_massage.gif" alt="massage" name="massage" width="65" height="21" border="0" onload=""></a><a href="trainers.htm" target="_top" onClick="MM_nbGroup('down','group1','trainers','',1)" onMouseOver="MM_nbGroup('over','trainers','images/topnav/but_trainers_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img src="images/topnav/but_trainers.gif" alt="trainers" name="trainers" width="69" height="21" border="0" onload=""></a><a href="testimonials.htm" target="_top" onClick="MM_nbGroup('down','group1','testimonials','',1)" onMouseOver="MM_nbGroup('over','testimonials','images/topnav/but_testimonials_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img src="images/topnav/but_testimonials.gif" alt="testimonials" name="testimonials" width="92" height="21" border="0" onload=""></a><a href="press.htm" target="_top" onClick="MM_nbGroup('down','group1','press','',1)" onMouseOver="MM_nbGroup('over','press','images/topnav/but_press_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img src="images/topnav/but_press.gif" alt="press" name="press" width="47" height="21" border="0" onload=""></a><a href="links.htm" target="_top" onClick="MM_nbGroup('down','group1','links','',1)" onMouseOver="MM_nbGroup('over','links','images/topnav/but_links_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img name="links" src="images/topnav/but_links.gif" border="0" alt="links" onLoad=""></a><a href="contact.htm" target="_top" onClick="MM_nbGroup('down','group1','contact','',1)" onMouseOver="MM_nbGroup('over','contact','images/topnav/but_contact_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img name="contact" src="images/topnav/but_contact.gif" border="0" alt="contact us" onLoad=""></a><a href="online.htm" target="_top" onClick="MM_nbGroup('down','group1','online','',1)" onMouseOver="MM_nbGroup('over','online','images/topnav/but_online_f2.gif','',1)" onMouseOut="MM_nbGroup('out')"><img name="online" src="images/topnav/but_online.gif" border="0" alt="online training" onLoad=""></a></td>
</tr>
<tr bgcolor="#F2F2FF">
<td>&nbsp;</td>
<td valign="top"><img src="images/spacer.gif" width="10" height="10"><!-- InstanceBeginEditable name="body" -->
<p><img src="images/title_contact.gif" width="163" height="35"></p>

<p>Please use the contact form below, call us on 0700 340 1378 or email
<span class="bodyheavy">help@mybpersonaltrainers.com</span>. We promise
to get back to you within 24 hours. (Monday to Friday only - excluding
holidays).</p>
<p><span class="bodyheavy">Want to become a Trainer?</span> If you are freelance
fitness professional interested in filling in the gaps in your own training
schedule with Move Your Butt clients, please Contact us. You must be qualified
to level three REPS, hold up-to-date insurance and first-aid and have
excellent inter-personal skills. <br>
</p>
<p>$errors</p>
<p>Please press the back button and try again.</p>
<!-- InstanceEndEditable --></td>

<td valign="top"><div align="right"><!-- InstanceBeginEditable name="photoright" --><img src="images/photos/main_photo_contact.jpg" alt="contact" width="279" height="440"><!-- InstanceEndEditable --></div></td>
</tr>
</table>
</body>
<!-- InstanceEnd --></html>



EOF;
}


/**
* Check email using regexes
* @param string email
* @return bool true if email valid, false if not
*/
function check_email($email) {
#characters allowed on name: 0-9a-Z-._ on host: 0-9a-Z-. on between: @
if (!preg_match('/^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/', $email))
return false;

#must start or end with alpha or num
if ( preg_match('/^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/', $email))
return false;

#name must end with alpha or num
if (!preg_match('/([0-9a-zA-Z_]{1})\@./',$email) )
return false;

#host must start with alpha or num
if (!preg_match('/.\@([0-9a-zA-Z_]{1})/',$email) )
return false;

#pair .- or -. or -- or .. not allowed
if ( preg_match('/.\.\-.|.\-\..|.\.\..|.\-\-./',$email) )
return false;

#pair ._ or -_ or _. or _- or __ not allowed
if ( preg_match('/.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./',$email) )
return false;

#host must end with '.' plus 2-5 alpha for TopLevelDomain
if (!preg_match('/\.([a-zA-Z]{2,5})$/',$email) )
return false;

return true;
}

do_formmail();
?>
bdlang
Forum Contributor
Posts: 395
Joined: Tue May 16, 2006 8:46 pm
Location: Ventura, CA US

Post by bdlang »

The NOTICE errors appear to be warning you that there are reference to an array index email_from that are not properly quoted, i.e. $vars['email_from'] instead of $vars[email_from] as you have it. For the most part, NOTICE errors are harmless but ensure you use good practice in your code. I note there are several references to array indexes such as this.

The WARNING error 'Warning: mail() [function.mail]: SMTP server response: 501 5.5.4 Invalid Address in C:\xx\xx\hhhconsulting.co.uk\contact\contact_form\aformmail.php on line 245' is likely your issue. What line is #245?

The error seems to indicate the SMTP server doesn't like the email address handed to it. Secondly, I notice this is on a IIS server, and PHP 'SMTP' config is set to 'localhost', so make certain there is a mail server on that machine that can handle the mail request.

I would comment out the last line in the script that calls the function do_formmail(), and add this below:

Code: Select all

echo '<pre>'; print_r($vars); echo '</pre>';
echo '<pre>'; print_r($send_cc); echo '</pre>';
These are essentially the important elements in the script, it should give you the necessary troubleshooting info. I would also take a hard look at these lines in the send_mail() function:

Code: Select all

//send to
$_send_to = $send_to ? $send_to : "$vars[name_to] <".$vars[email_to].">";
$_send_from = "$vars[name_from] <".$vars[email_from].">";
The output of those lines determines the to / from addresses in your initial call to mail().

Please note your post is tough to read through, make sure you use the [ PHP ] tags in all future posts, and indent your code!

Further issues, you may want to hire an outside consultant (I am available for small jobs like this anytime).
pzh20
Forum Newbie
Posts: 2
Joined: Sat Jul 01, 2006 5:23 am

Post by pzh20 »

Thanks for this reply. I will look at the Server for the mail server issue.

Line 245 is highlighted, with "<---------- Line 245" if you need to look again.

Does PHP use it's own mail server, i.e. is there another configuration option to point it at something else?

Thanks again
Pete
bdlang
Forum Contributor
Posts: 395
Joined: Tue May 16, 2006 8:46 pm
Location: Ventura, CA US

Post by bdlang »

pzh20 wrote: Line 245 is highlighted, with "<---------- Line 245" if you need to look again.
Ah, missed that. Like I said, it's hard to parse through all that code in black & white. Line 245 is the call to mail() that uses the values I mentioned.
Does PHP use it's own mail server, i.e. is there another configuration option to point it at something else?
No, there is no mail server included with PHP.

The config option 'SMTP' is noted in the PHP Manual as being a 'Windows only option' that points to the address of your SMTP server. There are, in fact, 2 more of these SMTP options for Windows, 'smtp_port' and 'sendmail_from' that you might want to look at. Your phpinfo() output looks like those settings are set to an acceptable default.

As I mentioned previously, the error code indicates to me that the SMTP server is responding to the script, it just doesn't like the input it's getting, i.e. one of the addresses used.
Post Reply