0

そこで、フォームを含むWebページを作成し、フォームの内容を取得してエラーや不完全なセクションをチェックし、エラーを返すか送信するための比較的簡単なコードを見つけました。残念ながら、フォームページ自体ではなく、新しいページでエラーが返されます。これが私が望んでいることです。

HTMLフォーム:

    <form name="contactform" method="post" action="send_form.php">
        <table width="450px">
            <tr>
                <td valign="top">
                    <label for="first_name">First Name &#42</label>
                </td>
                <td valign="top">
                    <input type="text" name="first_name" maxlength="50" size="30">
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <label for="last_name">Last Name &#42</label>
                </td>
                <td valign="top">
                    <input type="text" name="last_name" maxlength="50" size="30">
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <label for="email">Email Address &#42</label>
                </td>
                <td valign="top">
                    <input type="text" name="email" maxlength="80" size="30">
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <label for="telephone">Telephone Number</label>
                </td>
                <td valign="top">
                    <input type="text" name="telephone" maxlength="30" size="30">
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <label for="comments">Comments &#42</label>
                </td>
                <td valign="top">
                    <textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:center">
                    <h6>An astrisk (&#42) denotes a required field.</h6>
                    <input type="submit" value="Submit" />
                </td>
            </tr>
        </table>
    </form>

PHPコード:

if(isset($_POST['email'])) {

$email_to = "my@email.com";
$email_subject = "Comments";


function died($error) {
    //This is where I think the code that prints to the same webpage should be rather than putting on a new page, which is what I does now
    echo "There were error(s) found with the form you submitted. Please review these errors and resubmit.";
    echo "These errors appear below.<br /><br />";
    echo $error."<br /><br />";
    echo "Please go back and fix these errors.<br /><br />";
    die();
}

// validation expected data exists
if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['telephone']) ||
    !isset($_POST['comments'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');       
}

$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";


// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  

<!-- email success html -->
<h4>Thank you for contacting us. We will be in touch with you very soon.</h4>
<h4><a class="submitSuccess" href="index.php">Return to Index</a></h4>

}

基本的に、フォームが正しく入力されなかったことを示すテキスト行をテキストボックスの上に印刷する必要があります。現在、エラーのある新しいWebページが作成されます。

補足:いくつかのphpブラケットがあるはずですが、コードが正しく表示されていなかったので、それらを削除しました。ただし、コードのアイデアは得られます。

4

3 に答える 3

2

コードを見ると、PHPページの基本的な動作は、検証エラーがあるかどうかを確認することです。はいの場合はエラーメッセージを表示し、そうでない場合はメールを送信します。

実行したいのは、検証エラーのある元のページを表示することです。

通常、少なくとも私が知っているほとんどすべてのフレームワークでは、これはリダイレクトを使用して行われます。基本的に、エラーがない場合は、ユーザーを成功ページにリダイレクトします。

エラーがある場合は、エラー情報とユーザーデータをセッション変数に入れて、元のフォームにリダイレクトします。

基本的なコード構造は次のようになります。

検証スクリプト:

if ( validate_form($_POST))
{
     /*
         Form validation succeeded, 
         Do whatever processing you want (Like sending an email)
     */    
     header('location: success.php'); // redirect to the success page
}
else
{
     /*
         Form validation failed        
     */
     session_start(); 
     $error = ...;
     $form_data = array('error' => $error, 'username' => $_POST['username'], ...);
     $SESSION['form_data'] = $form_data;
     header('location: form.php');

}

フォームスクリプト:

<?php
     session_start(); 
     if( isset($SESSION['form_data']))
     { 
         $username = $SESSION['form_data']['username'];
         $errors = $SESSION['form_data']['error'];
     }
     else
     {
         $username = '';
         $errors = '';          
     }

?>

<form name="contactform" method="post" action="send_form.php">
      <input type="text" name="username" value=<?php $username ?> >       
      <label for="errors"><?php $errors ?></label>   
</form>

PS:このコードは単純なデモンストレーションであり、明らかに100%正しくありません。より多くの例外処理、より多くのセキュリティチェックを追加する必要があります...しかし、あなたはその考えを理解します。

軽量のMVCフレームワークを使用して、これを正しい方法で実行する方法を理解することをお勧めします。これらのフレームワークのソースコードを見ることもできます。

于 2012-10-02T13:25:07.887 に答える
0

フォームデータが検証サーバー側を通過しない場合は、最後にdie()を指定して関数died()を呼び出します。PHPヘルプをチェックして、die()が必要なことを実行することを確認してください。PHPに、PHPの解析を停止し、ページを現状のままクライアントに送信するように指示します。したがって、フォームは表示されません。

個人的に:私はデバッグ目的でのみdie関数を使用します

于 2012-10-02T13:09:36.583 に答える
0

言うことによって:

<form name="contactform" method="post" action="send_form.php">

Webブラウザでsend_form.phpに移動するようにHTMLフォームに指示しています。次に、send_form.phpで、フォームの内容が正しいかどうかを確認するロジックが実行されるため、その新しいページにエコーが表示されます。

フォームが正しく入力されているかどうかを確認するには、元のHTMLページでスクリプト(javascript / php)を使用する必要があります。

次のようなものを参照してください:http ://www.thesitewizard.com/archive/validation.shtml

于 2012-10-02T13:16:49.267 に答える