Php 如何验证通过post发送的数据?
我有一个ajax代码,它将Php 如何验证通过post发送的数据?,php,ajax,post,Php,Ajax,Post,我有一个ajax代码,它将postid和comment发送到另一个页面 ajax.php $.ajax({ type: "POST", url: "addcomment.php", data: {comment : comment,postid : postid}, 我在另一页收到的数据如下: if ($_SERVER['REQUEST_METHOD'] === 'POST') { $postid=$_POST[
postid
和comment
发送到另一个页面
ajax.php
$.ajax({
type: "POST",
url: "addcomment.php",
data: {comment : comment,postid : postid},
我在另一页收到的数据如下:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$postid=$_POST['postid'];
$comment=$_POST['comment'];
下面是我可以做哪些改进来验证第二个代码。我的意思是,只有在发布了
posted
和comment
之后,代码才应该继续 只需检查它们是否已定义
if (isset($_POST['postid']) && isset($_POST['comment'])) {
//continue
} else {
// do not continue
}
或者,您可以在进行AJAX调用之前执行此操作。在获取postid和comment元素的值时,只需检查它们是否有值。如果没有从函数返回。只需检查它们是否已定义
if (isset($_POST['postid']) && isset($_POST['comment'])) {
//continue
} else {
// do not continue
}
或者,您可以在进行AJAX调用之前执行此操作。在获取postid和comment元素的值时,只需检查它们是否有值。如果不从函数返回。那么有几件事可以做,首先要确保这两个变量都存在,这可以通过
isset()
对于这样的代码,我倾向于使用早期返回而不是嵌套ifs,因此您可以执行以下操作:
if (!isset($_POST['postid']) || !isset($_POST['comment'])) {
$error = 'Values for postid and comment were not set.';
return $error;
}
检查两个变量是否都已设置后,就可以开始验证变量的类型和大小是否正确
您可能会将isset()
替换为empty()
,因此:
if (empty($_POST['postid'] || empty($_POST['comment']) {
$error = 'Values are not set.';
return $error;
}
例如,我假定postid
是一个数字,所以
if (!is_numeric($_POST['postid'])) {
$error = 'Value for postid must be numeric.';
return $error;
}
您还可以检查它是否高于0:if(!$\u POST['postid']>0){}
然后,您可以检查长度是否大于0以获取注释
if (!strlen($_POST['comment']) > 0) {
$error = 'Comment was left blank, ensure it is filled in.';
return $error;
}
以上只是一些例子,希望能对您有所帮助。:) 您可以做几件事,首先要确保这两个变量都存在,您可以使用
isset()
对于这样的代码,我倾向于使用早期返回而不是嵌套ifs,因此您可以执行以下操作:
if (!isset($_POST['postid']) || !isset($_POST['comment'])) {
$error = 'Values for postid and comment were not set.';
return $error;
}
检查两个变量是否都已设置后,就可以开始验证变量的类型和大小是否正确
您可能会将isset()
替换为empty()
,因此:
if (empty($_POST['postid'] || empty($_POST['comment']) {
$error = 'Values are not set.';
return $error;
}
例如,我假定postid
是一个数字,所以
if (!is_numeric($_POST['postid'])) {
$error = 'Value for postid must be numeric.';
return $error;
}
您还可以检查它是否高于0:if(!$\u POST['postid']>0){}
然后,您可以检查长度是否大于0以获取注释
if (!strlen($_POST['comment']) > 0) {
$error = 'Comment was left blank, ensure it is filled in.';
return $error;
}
以上只是一些例子,希望能对您有所帮助。:) 我建议您创建一个通用验证程序类,该类将根据要验证的表单进行不同的配置(使用配置数组或文件可以轻松完成)。
这样,您只需做一次工作,就可以在整个项目中重复使用它,还可以使代码更干净、易于维护 我建议您创建一个通用验证程序类,该类将根据要验证的表单进行不同的配置(使用配置数组或文件可以轻松完成)。 这样,您只需做一次工作,就可以在整个项目中重复使用它,还可以使代码更干净、易于维护