2013-04-29 3 views
0

나는 입력을 검증하고 유효성 검사를 통과하면 웹 서비스에 정보를 보내고 백업으로 mySQL에 저장하는 웹 양식을 가지고있다. 웹 서비스로 보내거나 sql로 오류가 발생하면 알려주는 경고 메일을 보내고 싶습니다. 오류가 없으면 모든 것이 정상적으로 실행됩니다. 오류가있는 경우 어떤 일이 발생하는지 테스트하려면 잘못된 MySQL 자격 증명을 입력해야합니다. 이 경우 전체 스크립트를 처리하는 데 약 30 초가 걸립니다. 스크립트를 완료하기 전에 유효성 검사를 실행하고 응답을 반환하는 방법이 있는지 궁금합니다. 웹 서비스를 호출하고 서버에 대한 응답을 보낸 후에 백그라운드에서 mysql에 저장하려고합니다. 이것이 가능한가? 기어맨 같은 것을 구현해야합니까?PHP의 느린 폼 처리 - 대기열이 필요하십니까?

또한 상당히 높은 볼륨 형태입니다. 두 사람이 동시에 제출하려고하면 mysql 문제가 발생합니까? 보안을 향상시킬 수있는 방법이 있습니까? 나는 초보자이므로 어떤 추가 조언도 훌륭합니다.

감사합니다.

<?php 
if(isset($_POST)){ 
//form validation vars 
$formok = true; 
$errors = array(); 

//sumbission data 
$ipaddress = $_SERVER['REMOTE_ADDR']; 

// 
//form data 
// 

//Services 
if(isset($_POST['services'])) {  
    $services = $_POST['services']; 
} else { 
    $services = array(
     'Neck' => NULL, 
     'Back' => NULL, 
     'Other' => NULL, 
    ); 
} 

$firstname = $_POST['firstname']; 
$lastname = $_POST['lastname']; 
$email = $_POST['email']; 

$telephone = $_POST['telephone']; 
$TelephoneSanitized = preg_replace("/[^0-9]/", "", $telephone); //format phone as number only 

//if phone number does not start with 1, and the length is less than 11 characters, add the 1 to the beginning 
if ((substr($TelephoneSanitized, 0, 1) != '1') && (strlen($TelephoneSanitized) < 11)) { 
    $TelephoneSanitized = "1".$TelephoneSanitized;  
    } 

//$state = strip_tags($_POST['state']); 
$location = $_POST['location']; 
$message = $_POST['message']; 

$leadsource = $_POST['leadsource']; 
$refId = $_POST['refId']; 
$isconsult = $_POST['isconsult']; 

//Third Party Emails 
if(isset($_POST['receiveThirdPtyEmails'])) {   
    $receiveThirdPtyEmails = strip_tags($_POST['receiveThirdPtyEmails']); 
} else { 
    $receiveThirdPtyEmails = NULL;  
} 

// 
//validation 
// 

//validate location has been set 
if($location == 0){ 
    $formok = false; 
    $errors[] = "Please select your nearest location"; 
} 

//validate name is not empty 
if(empty($firstname)){ 
    $formok = false; 
    $errors[] = "Please enter your first name"; 
} 
if(empty($lastname)){ 
    $formok = false; 
    $errors[] = "Please enter your last name"; 
} 

//validate email address is not empty 
if(empty($email)){ 
    $formok = false; 
    $errors[] = "Please enter your email address"; 
//validate email address is valid 
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){ 
    $formok = false; 
    $errors[] = "You have not entered a valid email address"; 
} 

//validate phone is not empty 
if(empty($telephone)){ 
    $formok = false; 
    $errors[] = "Please enter your phone number"; 
} 
//validate phone is at least 10 characters 
elseif(strlen($TelephoneSanitized) < 10){ 
    $formok = false; 
    $errors[] = "Your phone number must be at least 10 characters"; 
} 

//what we need to return back to our form 
$returndata = array(
    'posted_form_data' => array(
     'services' => $services, 
     'firstname' => $firstname, 
     'lastname' => $lastname, 
     'email' => $email, 
     'telephone' => $telephone, 
     //'state' => $state, 
     'location' => $location, 
     'message' => $message 
    ), 
    'form_ok' => $formok, 
    'errors' => $errors, 
); 

//if this is not an ajax request 
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){ 

    //set session variables 
    session_start(); 
    $_SESSION['cf_returndata'] = $returndata; 

    //redirect back to form 
    header('location: ' . $_SERVER['HTTP_REFERER']); 

} 
// 
//send to web service if all is ok 
// 
if($formok){ 

    //build query string 
    $fields = array('services' => $services, 
      'location' => $location, 
      'firstname' => $firstname, 
      'lastname' => $lastname, 
      'email' => $email, 
      'emailconfirm' => $email, 
      'phone' => $TelephoneSanitized, 
      'comments' => $message, 
      'refid' => $refId, 
      'leadsource' => $leadsource, 
      'isconsult' => $isconsult, 
      'receiveThirdPtyEmails' => $receiveThirdPtyEmails); 

    $url = "http://fake.aspx?" . http_build_query($fields, '', "&"); 

    $url = preg_replace('/%5B[a-zA-Z]+%5D/', '', $url); 

    $curl_handle = curl_init($url); 
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true); 
    $results = curl_exec($curl_handle); 
    curl_close($curl_handle); 

} 

// 
//save data to mysql if all is ok PDO 
// 
if($formok){ 

    // Connecting to the MySQL server 
    $host="fakehost-on the same server as form"; 
    $user_name="fakeuser"; 
    $pwd="fakepass"; 
    $database_name="fakedb";   

    $services = implode(',',array_filter($services)); // change array to string 

    date_default_timezone_set('America/New_York'); 
    $date = date('m/d/Y h:i:s a', time()); 
    $date = date("Y-m-d H:i:s",strtotime($date)); 

    // mysql 
    try { 
     //connect to db 
     $conn = new PDO("mysql:host=$host;dbname=$database_name", $user_name, $pwd); 
     //set error handling 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     //prepare statement 
     $q = $conn->prepare("INSERT INTO leads 
     (ip_address, lead_time, location, first_name, last_name, email_address, telephone, comments, services, receiveThirdPtyEmails, leadsource, refid) 
     VALUES 
     (:ip_address, :lead_time, :location, :first_name, :last_name, :email_address, :telephone, :comments, :services, :receiveThirdPtyEmails, :leadsource, :refid)"); 

     //execute statement     
     $q->execute(array(
      ':ip_address'=>$ipaddress, 
      ':lead_time'=>$date, 
      ':location'=>$location, 
      ':first_name'=>$firstname, 
      ':last_name'=>$lastname, 
      ':email_address'=>$email, 
      ':telephone'=>$TelephoneSanitized, 
      ':comments'=>$message, 
      ':services'=>$services, 
      ':receiveThirdPtyEmails'=>$receiveThirdPtyEmails, 
      ':leadsource'=>$leadsource, 
      ':refid'=>$refId)); 

    } 
    catch(PDOException $e) { 
     $error_code = $e->getMessage();  // Specify the error code 
     $error_type = "SQL Insert Failed"; 
     require_once("resources/error-mailer.php"); // Include the error mailer script 
    } 
    # close the connection 
    $conn = null;  
} 
} 

답변

0

JSON과 AJAX를 사용하는 Javascript/jQuery가 최선의 방법입니다. 여기 좋은 예가있다 :

Send JSON data via POST (ajax) and receive json response from Controller (MVC) 또한

보안 현명한, 당신은 mysqli_real_escape_string()를 사용하는 것이 좋습니다 : 문자열에

http://php.net/manual/en/mysqli.real-escape-string.php

당신이 POST를 통해 승인하거나 전에 GET 값을 그 값을 귀하의 질의에 넣으십시오. 그것은 SQL 주입을 피합니다. 정수의 경우 abs (intval ($ _ POST [ 'posted_integer'])) 또는 ctype_digit을 사용하거나, 필요에 따라 preg_replace()/preg_match() 정규식을 사용하십시오.

POST 또는 GET 값을 데이터베이스에 그대로 두지 마십시오!

+0

Jquery/Ajax와 함께 제출할 예정이지만 JS가 꺼져있는 상태에서 양식에 액세스 할 수 있어야합니다. mySQLi가 아닌 PDO를 사용하고 있기 때문에 PDO가 자동으로 이스케이프를 수행하지 않습니까? – Evan

+0

다른 사람이 하위 쿼리로 SELECT/UPDATE/INSERT/DELETE를 전달하는 것을 막지 말고 테이블 이름에 틱을 추가하는 것처럼 이스케이프 처리를 수행합니다. – Frank