2014-03-12 3 views
-1

이 코드를 사용하여 mysql에 내 연락처 양식을 연결했는데 문제는 이름 채우기가 유효하거나 이메일이 유효해야하므로 각 항목의 유효성을 검사하는 방법을 모르는 것이므로 나중에 걸릴 때마다 문제가되지 않습니다. 그것의 모든 신경, 여기에 내 코드입니다 : 당신이 나를 도울 수 : 폼의 적절한 검증을위한문의 양식을 확인하는 방법은 무엇입니까?

<?php 
$con=mysqli_connect("example.com","peter","abc123","my_db"); 
// Check connection 
if (mysqli_connect_errno()) 
     { 
echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

$sql="INSERT INTO Persons (FirstName, LastName, Age) 
VALUES 
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; 

if (!mysqli_query($con,$sql)) 
{ 
die('Error: ' . mysqli_error($con)); 
} 
echo "1 record added"; 

mysqli_close($con); 
?> 
+0

각각의 장소에서 $ MSG1, $ MSG2를 찾아주세요 jquery-plugins/jquery-plugin-validation/** – Johnny000

+0

html 형식으로 표시됩니다. –

+1

폼 유효성 검사에 대한 튜토리얼이 많이 있습니다. 당신은 구글에 대한 약간의 연구를 할 수 있습니다. – Kuzgun

답변

0

당신은 클라이언트 측 유효성 검사 (예를 들어, 사용 JQuery와)

을해야하고 PHP에서이 같은 시도 할 수 있습니다 : 당신이 할 수있는

if(!empty($_POST['lastname']) && !empty($_POST['age']) && !empty($_POST['firstname']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { 
    $con=mysqli_connect("example.com","peter","abc123","my_db"); 
    // Check connection 
    if (mysqli_connect_errno()) 
      { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

    $sql="INSERT INTO Persons (FirstName, LastName, Age) 
    VALUES 
    ('mysqli_real_escape_string($con,$_POST[firstname])','mysqli_real_escape_string($con,$_POST[lastname])','mysqli_real_escape_string($con,$_POST[age])')"; 

    if (!mysqli_query($con,$sql)) 
    { 
    die('Error: ' . mysqli_error($con)); 
    } 
    echo "1 record added"; 

    mysqli_close($con); 
    } 

을 다음과 같이 PHP에서 이메일을 확인하십시오 :

filter_var($emailAddress, FILTER_VALIDATE_EMAIL) 
//bassistance.de/ :

php filter

+0

그래서 "mysql_real_escape_string"을 추가해야합니다. 간단합니다. 곧 시도해 보겠습니다. – hdjkshdak

+0

아니요. 모든 데이터를 사용할 수 있는지 확인하는 첫 번째 조건이 필요하지 않습니다. –

+0

내 코드에 "filter_var ($ emailAddress, FILTER_VALIDATE_EMAIL)"을 넣었습니까? @awlad – hdjkshdak

0

는 몇 가지 측면은 쓰레기 입력의 과잉을 필터링 할 수 있도록 고려되어야한다. 내 접근 방식은 다음과 같습니다.

먼저 텍스트의 최소 길이를 확인하십시오. 이렇게하면 무의미한 입력을받을 위험이 줄어 듭니다. 둘째, 텍스트의 최대 길이를 확인하십시오. 당신은 누군가를 당신의 데이터베이스에 대량의 텍스트로 가득 채우고 싶지는 않을 것입니다. 셋째, 정규 표현식을 사용하여 다른 필드 (우편 번호, 전화 번호, 전자 메일)의 올바른 형식을 확인하고 위험을 피하거나 최소화하기 위해 해당 필드에 필요한 문자 만 허용해야합니다. 입력을 통해 비참한 교차 사이트 주사를 보내는 누군가의 여기

orientative 예 :

function validate_form() { 
$errors = array(); 
// El nombre del usuario es necesario 
if (! strlen(trim($_POST['user_name']))) { 
$errors[] = 'The username is required.'; 
} 
// El nombre del usuario no debe contener caracteres problemáticos 
if (preg_match('@[^a-zA-Z0-9_\- ]@', trim($_POST['user_name']))) { 
$errors[] = 'The username cannot contain invalid characters.'; 
} 
// El nombre del usuario no debe tener menos de 3 caracteres 
if (strlen(trim($_POST['user_name'])) < 3) { 
$errors[] = 'The username cannot have less than 3 characters long.'; 
} 
// El nombre del usuario no debe tener más de 24 caracteres 
if (strlen(trim($_POST['user_name'])) > 24) { 
$errors[] = 'The username cannot have more than 24 characters long.'; 
} 
// La contraseña es necesaria 
if (! strlen(trim($_POST['password']))) { 
$errors[] = 'The password is required.'; 
} 
// La contraseña no debe contener caracteres problemáticos 
if (preg_match('@[^a-zA-Z0-9_\-]@', trim($_POST['password']))) { 
$errors[] = 'The password cannot contain invalid characters.'; 
} 
// La contraseña no debe tener menos de 6 caracteres 
if (strlen(trim($_POST['password'])) < 6) { 
$errors[] = 'The password cannot have less than 6 characters long.'; 
} 
// La contraseña no debe tener más de 12 caracteres 
if (strlen(trim($_POST['password'])) > 12) { 
$errors[] = 'The password cannot have more than 12 characters long.'; 
} 
// La contraseña debe contener letras y números 
if (! preg_match('/([a-zA-Z][0-9]|[0-9][a-zA-Z])+/', trim($_POST['password']))) { 
$errors[] = 'The password must contain letters and numbers.'; 
} 
// Password y Password Check deben ser iguales 
if ($_POST['password'] != $_POST['password_check']) { 
$errors[] = 'Password and Password Check do not match.'; 
} 
// El correo electrónico es necesario 
if (! strlen(trim($_POST['e_mail']))) { 
$errors[] = 'The e-mail is required.'; 
} 
// El correo electrónico no debe contener caracteres problemáticos 
if (preg_match('/[^a-zA-Z0-9_\[email protected]\.]/', trim($_POST['e_mail']))) { 
$errors[] = 'The e-mail cannot contain invalid characters.'; 
} 
// El correo electrónico no debe tener más de 64 caracteres 
if (strlen(trim($_POST['e_mail'])) > 64) { 
$errors[] = 'The e-mail cannot have more than 64 characters long.'; 
} 
// El correo electrónico debe tener un formato correcto 
if (! preg_match('/[^@\s]{3,}@([-a-z0-9]{3,}\.)+[a-z]{2,}/', trim($_POST['e_mail']))) { 
$errors[] = 'The e-mail must have a valid format.'; 
} 
// El país seleccionado debe ser válido 
if (! array_key_exists($_POST['country'], $GLOBALS['countries'])) { 
$errors[] = 'Please select a valid country.'; 
} 
// La ciudad es necesaria 
if (! strlen(trim($_POST['city']))) { 
$errors[] = 'The city is required.'; 
} 
// La ciudad no debe contener caracteres problemáticos 
if (preg_match('@[^a-zA-Z\- ]@', trim($_POST['city']))) { 
$errors[] = 'The city cannot contain invalid characters.'; 
} 
// La ciudad no debe tener menos de 3 caracteres 
if (strlen(trim($_POST['city'])) < 3) { 
$errors[] = 'The city cannot have less than 3 characters long.'; 
} 
// La ciudad no debe tener más de 64 caracteres 
if (strlen(trim($_POST['city'])) > 64) { 
$errors[] = 'The city cannot have more than 64 characters long.'; 
} 
// El mes seleccionado debe ser válido 
if (! array_key_exists($_POST['month'], $GLOBALS['months'])) { 
$errors[] = 'Please select a valid month.'; 
} 
// El día seleccionado debe ser válido 
if (! array_key_exists($_POST['day'], $GLOBALS['days'])) { 
$errors[] = 'Please select a valid day.'; 
} 
// El año seleccionado debe ser válido 
if (! array_key_exists($_POST['year'], $GLOBALS['years'])) { 
$errors[] = 'Please select a valid year.'; 
} 
// El nombre real del usuario es necesario 
if (! strlen(trim($_POST['real_name']))) { 
$errors[] = 'Your real name is required.'; 
} 
// El nombre real del usuario no debe contener caracteres problemáticos 
if (preg_match('@[^a-zA-Z\- ]@', trim($_POST['real_name']))) { 
$errors[] = 'Your real name cannot contain invalid characters.'; 
} 
// El nombre real del usuario debe tener menos de 3 caracteres 
if (strlen(trim($_POST['real_name'])) < 3) { 
$errors[] = 'Your real name cannot have less than 3 characters long.'; 
} 
// El nombre real del usuario no debe tener más de 64 caracteres 
if (strlen(trim($_POST['real_name'])) > 64) { 
$errors[] = 'Your real name cannot have more than 64 characters long.'; 
} 
// El número CAPTCHA introducido debe ser correcto 
$captcha_num_1 = substr($_POST['captcha'], 0, 1); 
$captcha_num_2 = substr($_POST['captcha'], 1, 1); 
$captcha_num_3 = substr($_POST['captcha'], 2, 1); 
$captcha_num_4 = substr($_POST['captcha'], 3, 1); 
$captcha_num_5 = substr($_POST['captcha'], 4, 1); 
if (($_SESSION['num1'] != crypt($captcha_num_1, $_SESSION['num1'])) || 
($_SESSION['num2'] != crypt($captcha_num_2, $_SESSION['num2'])) || 
($_SESSION['num3'] != crypt($captcha_num_3, $_SESSION['num3'])) || 
($_SESSION['num4'] != crypt($captcha_num_4, $_SESSION['num4'])) ||                   ($_SESSION['num5'] != crypt($captcha_num_5, $_SESSION['num5']))) { 
$errors[] = 'The CAPTCHA number entered is not correct.'; 
} 
// El nombre de usuario y la dirección de e-mail deben ser únicos en la base de datos 
global $db; 
$sql = 'SELECT user_name, e_mail FROM users'; 
$q = mysqli_query($db, $sql); 
if (mysqli_num_rows($q) > 0) { 
while ($users = mysqli_fetch_object($q)) { 
if ($users->user_name == $_POST['user_name']) { 
$errors[] = 'This username already exists in the database. Please use a different one.'; 
} 
if ($users->e_mail == $_POST['e_mail']) { 
$errors[] = 'This e-mail address already exists in the database. Please use a different one.'; 
} 
} 
} 
// Si hay errores, resetear el CAPTCHA 
if (is_array($errors)) {                    reset_captcha(); 
} 
return $errors; 
} 
0

16,하면 다음과 같은 대답을

<?php 
$con=mysqli_connect("example.com","peter","abc123","my_db"); 
//Check connection 
if (mysqli_connect_errno()) 
{ 
echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 
$c=0; 
if($_POST['firstname']=="") 
{ 
$msg='Please enter firstname'; 
$c++; 
} 
if($_POST['lastname']=="") 
{ 
$msg1='Please enter lastname'; 
$c++; 
} 
if($_POST['age']=="") 
{ 
$msg2='Please enter age'; 
$c++; 
} 
if($c==0) 
{ 
$sql="INSERT INTO Persons (FirstName, LastName, Age) 
VALUES 
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; 

if (!mysqli_query($con,$sql)) 
{ 
die('Error: ' . mysqli_error($con)); 
} 
echo "1 record added"; 
} 
mysqli_close($con); 
?> 

인쇄 $의 MSG, 당신은 ** HTTP로 살펴 수

관련 문제