#php
#php
Вопрос:
Это должно быть просто, но я играл с ним два дня и заставил его работать. Когда я добрался до страницы благодарности, в электронном письме не было данных. Теперь я не могу пройти мимо страницы с ошибкой.
HTML-форма:
<form action="send_group_photo_order.php" method="post" name="GroupPhoto" id="GroupPhoto" title="GroupPhoto">
<p>
<label for="name">Name:</label>
<input name="name" type="text" id="name" value="" form="GroupPhoto" title="name" size="50" />
</p>
<p>Student ID #:
<input name="id" type="text" id="id" form="GroupPhoto" title="id" />
</p>
<p>
<label for="email">Email:</label>
<input name="email" type="email" id="email" form="GroupPhoto" title="email" size="50" />
</p>
<p>Phone
<label for="phone">:</label>
<input name="phone" type="text" id="phone" form="GroupPhoto" title="phone" />
<br />
<br />
</p>
<p>
<input name="orders[]" type="checkbox" id="checkbox1" form="GroupPhoto" title="GroupCD" value="cd" />
<label for="type1">I want Digital Photos on a CD for $5.00 </label>
</p>
<p>
<input name="orders[]" type="checkbox" id="checkbox2" form="GroupPhoto" title="Group-Print-Package" value="prints" />
<label for="type2">I want the Full Color Print Package for $25.00<br />
<br />
</label>
</p>
<input name="orders[]" type="checkbox" id="checkbox3" form="GroupPhoto" title="Acknowledge" value="acknowledge"/>
<label for="type3">I understand that I must pay for this service in full before the photos will be printed. I will
receive a preview copy via email prior to printing. This will be a locked file.<br />
<br />
</label>
<input name='submit' type="submit" form="GroupPhoto" value="submit" id="submit" />
</form>
PHP-код:
<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "yearbook@gphs-go4news.com";
/*
This bit sets the URLs of the supporting pages.
If you change the names of any of the pages, you will need to change the values here.
*/
$feedback_page = "order_photos.html";
$error_page = "error_message.html";
$thankyou_page = "thank-you.html";
/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$id = $_REQUEST['id'] ;
$selectedOrders = 'None';
if(isset($_POST['orders']) amp;amp; is_array($_POST['orders']) amp;amp; count($_POST['orders']) > 0){
$selectedProjects = implode(', ', $_POST['orders']);
}
$body .= 'Selected orders: ' . $selectedOrders;
/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
$injections = array('(n )',
'(r )',
'(t )',
'(
)',
'(
)',
'( )',
'( )'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
return true;
}
else {
return false;
}
}
// If the user tries to access this script directly, redirect them to the feedback form,
if (!isset($_REQUEST['email'])) {
header( "Location: $feedback_page" );
}
// If the form fields are empty, redirect to the error page.
elseif (empty($email_address) || empty($comments)) {
header( "Location: $error_page" );
}
// If email injection is detected, redirect to the error page.
elseif ( isInjected($email_address) ) {
header( "Location: $error_page" );
}
// If we passed all previous tests, send the email then redirect to the thank you page.
else {
mail( "$webmaster_email", "Feedback Form Results",
$comments, "From: $email" );
header( "Location: $thankyou_page" );
}
?>
Комментарии:
1. Что говорит «страница ошибок»?
2. Здесь в порядке базовая отладка. Если ваш скрипт всегда перенаправляет на
$error_page
, вы должны закомментироватьheader()
вызовы по одному, чтобы определить, какой из них неисправен (их может быть несколько), и вместо выполнения перенаправления проверьте затронутые переменные, напримерvar_dump($email_address);
, иvar_dump($comments);
, чтобы выяснить, какая проверка завершается с ошибкой.3. Кроме того, всегда вызывайте
exit();
сразу после aheader("Location...")
. Если у вас есть дополнительный код, который может быть достигнут (например, не в другомif/else
состоянии) PHP все равно может выполнить его, даже если вы собираетесь завершить скрипт перенаправлением. Это частый источник действительно труднодоступных ошибок (хотя здесь это не ваша проблема)4. Последний момент: всегда при разработке кода убедитесь, что вы
display_errors
включили. В верхней части вашего скрипта,error_reporting(E_ALL); ini_set('display_errors', 1);
поэтому любые предупреждения и уведомления PHP выводятся на экран. Любые пустые значения в$_REQUEST
будут выдаватьсяNotice undefined index...
так, как вы их закодировали прямо сейчас, поскольку у вас нетisset()
вызовов на$email = $_REQUEST['email'];
и другие.5. Когда я добавил ваш отличный код, вернулось сообщение: Notice: Неопределенная переменная: body в /hermes/bosoraweb149/b1648/glo.gphsgo4newscom/yearbook/send_group_photo_order.php Предупреждение в строке 30: mail() ожидает не более 5 параметров, 8 из которых указаны в /hermes/bosoraweb149/b1648/glo.gphsgo4newscom/yearbook/send_group_photo_order.php в строке 73 Предупреждение: невозможно изменить информацию заголовка — заголовки, уже отправленные (вывод начался с / hermes/bosoraweb149/b1648/glo.gphsgo4newscom/yearbook/send_group_photo_order.php:30) в /hermes/bosoraweb149/b1648/glo.gphsgo4newscom/yearbook/send_group_photo_order.php в строке 74