登録フォームを作成する方法を学ぶために、PHP スクリプトをつなぎ合わせています。フォームは情報を取得し、空のフィールドをチェックしてからデータベースに挿入し、成功した場合はメールを送信してから成功ページにリダイレクトすることになっています。
以下のコードでは、ページの読み込み時に何かがデータベースに入力され、ページの読み込み時にすぐに成功ページにリダイレクトされると考えているようです。どこが間違っていますか?
<?php
session_start();
$_SESSION['user'] = $user;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(empty($_POST["first_name"]))
{
$first_name_err = "<p>What is your first name?</p>";
}
if(empty($_POST["last_name"]))
{
$last_name_err = "<p>What is your last name?</p>";
}
//checks email
if(empty($_POST["email"]))
{
$email_err = "<p>What is your email address?</p>";
}
if(empty($_POST["phone"]))
{
$phone_err = "<p>What is your phone number?</p>";
}
if(empty($_POST["password"]))
{
$pass_err = "<p>Please enter your password</p>";
}
}
require_once('includes/db_connect.php');
// Get values from form
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$password = mysql_real_escape_string($_POST['password']);
// Insert data into mysql
$sql="INSERT INTO dontblame (first_name, last_name, email, phone, password, reg_date)
VALUES ('$first_name', '$last_name', '$email', '$phone', SHA1('$password'), NOW())";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
//Send to Success Page
header('Location: ../thankyou.php?first_name=' . htmlentities($first_name));
}
else {
echo "ERROR there was a problem with the registration form. Please try again.";
}
// close mysql
mysql_close();
if(IsInjected($email))
{
echo "Please don't SPAM.";
exit;
}
$email_from = 'hello@dontblame.co';//<== update the email address
$email_subject = "Welcome to Jon's First Registration Form";
$email_body = "Hi, $first_name,\n".
"\n Welcome to Jon's First Registration Form! Below is your login information: \n\n Username: $email \n Password: $password \r\n".
$to = "$email";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email_from \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
// Function to validate against any email injection attempts
function IsInjected($str){
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>