gpt4 book ai didi

php - PHP 表单验证/避免注入(inject)

转载 作者:行者123 更新时间:2023-11-29 06:14:45 25 4
gpt4 key购买 nike

我在 HTML 中创建了一个表单(查询表单),该表单发布到以下代码:

<?php           
if(isset($_POST['submit']))

{
$name = mysql_real_escape_string((string)$_POST['name']);
$surname = mysql_real_escape_string((string)$_POST['surname']);
$email = mysql_real_escape_string((string)$_POST['email']);
$phone = mysql_real_escape_string((string)$_POST['phone']);
$country = mysql_real_escape_string((string)$_POST['country']);
$message = mysql_real_escape_string((string)$_POST['message']);

$sql = "INSERT INTO contact
(name, surname, email, phone, country, message)
VALUES('$name', '$surname', '$email', '$phone', '$country', '$message')";

mysql_select_db($db);
$retval = mysql_query( $sql, $conn )or die(mysql_error());

echo 'Thank you '.$name.' '.$surname.'. Your enquiry has been forwarded to our team. <br><br>Please check you email inbox for further information.<br><br>Return to homepage:<br><br><button class="search" onclick="/">Return to homepage</button>';

mysql_close($conn);
}

?>

我想知道,当输入无效或零数据时,如何显示错误并停止表单发布?

在学习如何在网络上创建表单时,我还听说过 SQL 注入(inject)。我受到保护吗?

非常感谢您的帮助。

最佳答案

I am wondering how I can display errors and stop the form posting when invalid or zero data is entered.

您必须在 if(isset($_POST['submit'])) 之后进行验证。例如,您可以检查名称是否非空:

if (empty($_POST['name'])) {
$errors[] = 'name must not be empty';
}

对于更复杂的验证,例如验证电子邮件是否有效,您应该查看 filter extension :

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email) // invalid email

经过所有验证后:

if (!count($errors)) {
// do the insert here
}

一旦检测到错误,您可以使用 while block 来中断:

while (isset($_POST['submit'])) {

if (empty($_POST['name'])) {
$errors = 'name must not be empty';
break;
}

// do the insert here

break;
}

Whilst learning how to create forms on the web, I also heard about sql injections, am I protected?

是的,只要您转义 SQL 查询中嵌入的任何内容(就像您正在做的那样),您就受到保护。

您应该尝试使用 prepared statements ,这样更安全,更容易使用。

关于php - PHP 表单验证/避免注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7220444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com