Моя форма php не работает, и я не могу понять, где я ошибся

Я новичок во всем этом, но я создал форму, и вот что я написал, чтобы отправить ее. Я использовал здесь «[email protected]» вместо реального адреса.

<?php

/* Set e-mail recipient */
$myemail  = "[email protected]";

/* Check all form inputs using check_input function */
$names = check_input($_POST['names'], "Please return to our Application Form and enter your and your future spouse's names.");
$weddingtype = check_input($_POST['weddingtype'], "Please return to our Application Form and fill in what kind of wedding you will be having.");
$religioussect = check_input($_POST['religioussect'], "Please return to our Application Form and tell us about your religion and wedding traditions.");
$dateone = check_input($_POST['dateone'], "Please return to our Application Form and give us the date for at least one event.");
$eventone = check_input($_POST['eventone'], "Please return to our Application Form and list at least one event.");
$locationone = check_input($_POST['locationone'], "Please return to our Application Form and give us the location for at least one event.");
$durationone = check_input($_POST['durationone'], "Please return to our Application Form and give us the duration of at least one event.");
$typeone = check_input($_POST['typeone'], "Please return to our Application Form and tell us whether you would like video, photo or both for at least one event.");
$datetwo = $_POST['datetwo'];
$eventtwo = $_POST['eventtwo'];
$locationtwo = $_POST['locationtwo'];
$durationtwo = $_POST['durationtwo'];
$typetwo = $_POST['typetwo'];
$datethree = $_POST['datethree'];
$eventthree = $_POST['eventthree'];
$locationthree = $_POST['locationthree'];
$durationthree = $_POST['durationthree'];
$typethree = $_POST['typethree'];
$datefour = $_POST['datefour'];
$eventfour = $_POST['eventfour'];
$locationfour = $_POST['locationfour'];
$durationfour = $_POST['durationfour'];
$typefour = $_POST['typefour'];
$guests1 = check_input($_POST['guests1'], "Please return to our Application Form and tell us how many guests will attend at least one event.");
$guests2 = $_POST['guests2'];
$guests3 = $_POST['guests3'];
$guests4 = $_POST['guests4'];
$concerns = $_POST['concerns'];


if(!isset($_POST['submit'])){

$subject = "Quote Application";


/*Message for the e-mail */
$message = "Hello!

Another happy couple has filled out a Quote Application Form :D Hooray!

Their names are $names.

What sort of wedding are they having?
'$weddingtype'.

What religious sect and wedding traditions are they following?
'$religioussect'.

Now for their wedding events... Ooh boy!

1.  $dateone    
$eventone
$durationone
$typeone
Estimated guests: $guests1

$locationone

2.  $datetwo    
$eventtwo
$durationtwo
$typetwo
Estimated guests: $guests2

$locationtwo

3.  $datethree  
$eventthree
$durationthree
$typethree
Estimated guests: $guests3

$locationthree

4.  $datefour 
$eventfour
$durationfour
$typefour
Estimated guests: $guests4

$locationfour


Any concerns the couple have follow here:
'$concerns'

You better be ready to get to work now!
And also, have a really good day :)
";

/* Functions used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
    show_error($problem);
}
return $data;
}


function show_error($myError)
{
?>


<b>We apologize for the inconvenience, an error occurred.</b><br />
<?php echo $myError; ?>


<?php
exit();
}

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();

?>

Пожалуйста, помогите мне найти, что я делаю неправильно, я едва новичок здесь. Заранее спасибо!


person user1081524    schedule 28.06.2012    source источник
comment
Что значит не работает? Вы получаете какие-либо ошибки?   -  person j08691    schedule 29.06.2012
comment
небольшие примеры способствуют желанию посмотреть код. Я сомневаюсь, что нам нужно вручную проверять каждую POST переменную, которую вы устанавливаете... И минимизация кода, который создает проблемы, часто дает ответ автоматически;)   -  person Wrikken    schedule 29.06.2012
comment
Пожалуйста, сообщите об ошибках, которые вы получаете при отправке этой формы, это очень поможет нам.   -  person Amaerth    schedule 29.06.2012
comment
Пожалуйста, пожалуйста, пожалуйста, не используйте родную почту... Я понимаю, что вы только начинаете, но ваши сообщения будут отправлены в спам/доставляемость, так как этот подход не отправляет никаких заголовков. Загляните в PHPmailer для простой быстрой библиотеки, которая поможет вашим сообщениям и SMTP-серверу оставаться в здравом уме.   -  person DeaconDesperado    schedule 29.06.2012
comment
Подождите горячую секунду. stackoverflow .com/questions/8601790/   -  person ionFish    schedule 29.06.2012


Ответы (2)


PHP Parse error:syntax error, unexpected $end in /var/www/test.php on line 133

Исправьте, поставив отсутствующий '}' перед последним закрывающим тегом PHP ?>

Это показывает: PHP Fatal Error: Call to undefined function check_input() in /var/www/test.php on line 7

Переместите это наверх:

function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
    show_error($problem);
}
return $data;
}

Показывает, что мы должны переместить другую прямо под другую функцию.

function show_error($myError)
{
?>
<b>We apologize for the inconvenience, an error occurred.</b><br />
<?php echo $myError; ?>
<?php
exit();
}

И это исправлено. Полный исправленный код (довольно неаккуратный, я его не подчищал): [ссылка]

person ionFish    schedule 28.06.2012

Я пытался помочь очистить ваш код и исправить логические ошибки. Я не тестировал этот код, поэтому обязательно проверьте его. Я бы также порекомендовал вам уделить минуту изучению используемых языковых конструкций, таких как foreach, потому что запись такого длинного списка переменных может быть очень сложной для отладки.

<?php

if(! isset($_POST['submit'])) exit;

// Error messages
$error_messages = array(
    'names'         => 'Please return to our Application Form and enter your and your future spouse\'s names.',
    'weddingtype'   => 'Please return to our Application Form and fill in what kind of wedding you will be having.',
);

$errors = array();

foreach ($_POST as $key => &$value) {
    // If value is empty and error message exists, add error to the list
    if (empty($value) AND in_array($key, $error_messages)) {
        $errors[] = $error_messages[$key];
        continue;
    }

    // Variable variables, worth learning. $_POST['key'] becomes $key in your script.
    ${$key} = htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
}

// Errors existed, let's show them all
if (! empty($errors)) {
    echo '<b>We apologize for the inconvenience but there were errors:</b><br />';

    foreach ($errors as &$error) {
        echo $error . '<br />';
    }

    exit;
}

// All good, let's send
$email  = "[email protected]";
$subject = "Quote Application";

$message = "
    Hello!

    Another happy couple has filled out a Quote Application Form :D Hooray!

    Their names are $names.

    What sort of wedding are they having?
    '$weddingtype'.

    What religious sect and wedding traditions are they following?
    '$religioussect'.

    Now for their wedding events... Ooh boy!

    1.  $dateone    
    $eventone
    $durationone
    $typeone
    Estimated guests: $guests1

    $locationone

    2.  $datetwo    
    $eventtwo
    $durationtwo
    $typetwo
    Estimated guests: $guests2

    $locationtwo

    3.  $datethree  
    $eventthree
    $durationthree
    $typethree
    Estimated guests: $guests3

    $locationthree

    4.  $datefour 
    $eventfour
    $durationfour
    $typefour
    Estimated guests: $guests4

    $locationfour


    Any concerns the couple have follow here:
    '$concerns'

    You better be ready to get to work now!
    And also, have a really good day :)
";

mail($email, $subject, $message);

header('Location: thanks.html');
exit;

?>
person Seralize    schedule 28.06.2012