我有一个关于PHP表单检查发布文本和图像的问题。我如何处理这两种数据的表单检查?
$latErr = $lngErr = $photoErr = "";
$lat = $lng = $photo = "";
//what if i am not using form action-PHP_SELF, currently i am use anotherfile.php, what do i use below?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["inputfield1"])) {
$latErr = "Latitude is required. Enable your browser geolocation.";
} else {
$lat = test_input($_POST["inputfield1"]);
}
if (empty($_POST["inputfield2"])) {
$lngErr = "Longitude is required. Enable your browser geolocation.";
} else {
$lng = test_input($_POST["inputfield2"]);
}
//can i check for image like this?
if (empty($_POST["photo"])) {
$photoErr = "Please select your image.";
} else {
$photoErr = test_input($_POST["photo"]);
}
}
答案 0 :(得分:2)
您需要使用输入类型file
,然后检查$_FILES
是否包含任何上传的图片:
if (empty($_FILES['photo']['name'])) {
// error - no photo selected
}
if (empty($_POST['inputfield1'])) {
// error - no text input
}
// ...
// ... form ...
<form method="POST" enctype="multipart/form-data">
<input type="file" name="photo" />
<input type="text" name="inputfield1" />
// ...
答案 1 :(得分:0)
如果有人在没有发送图片的情况下使用cURL,您的代码就会崩溃,因为它正在尝试查看是否有通过POST发送的“照片”。你应该尝试做这样的事情:
if( $_FILES['photo']['error'] == 4 )
$photoErr = "No file was uploaded";
答案 2 :(得分:0)
if(isset($_FILES['input_field_name']['name'])){
//File Exists
}
if(isset($_POST['input_fiel_text'])){
//Text field exists
}
答案 3 :(得分:0)
您可以获得有关图像的更多信息以获得良好的控制
$name = $_FILES['filename']['name'];
$dir = pathinfo($name);
$extension = $dir['extension'];
$extensionsAutorisees = array("png","gif","bmb");
$to_dir = dirname(__FILE__)."/img/";
$new_name = $name.".".$extension;
if (!(in_array($extension, $extensionsAutorisees))) {
.... error with extension alow
} else {
..... your action
}
答案 4 :(得分:0)
我喜欢Mark M的回答,他是对的,但我想将上传图片的验证添加到:
public static function isValidUpload() {
if ($_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
return false;
}
$info = getimagesize($_FILES['photo']['tmp_name']);
return !(($info === FALSE) || (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)));
}
不要检查扩展名,因为我可以编写PHP文件并将其另存为evil.png。在这种情况下,尽管扩展名是png,但这将是一个潜在危险的php。