Php 如何只测试一个输入
以下是我检查上传文件的php代码:Php 如何只测试一个输入,php,mysql,file-upload,Php,Mysql,File Upload,以下是我检查上传文件的php代码: <?php include("includes/db.php"); include("includes/header.php"); //========================= //Check file upload if (!empty($_FILES["file"])) { $allowedExts = array("jpg", "jpeg", "gif", "png"); $extension = end(explode
<?php
include("includes/db.php");
include("includes/header.php");
//=========================
//Check file upload
if (!empty($_FILES["file"])) {
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && in_array($extension, $allowedExts)) {
if ($_FILES["file"]["size"] > 524288000) {
$mtype="error";
$alertc="Image is too large<br/>\n";
$labelc="labeler";
$inputc="er";
}
else {
$imgname = $arrusrselect[id].md5($arrusrselect[id]).$arrusrselect[id].".jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "images/user/profile/" . $imgname);
setcookie("success", "Profile picture updated<br/>");
$labelc="label";
$inputc="input";
$upusers=$mysqli->query("UPDATE `users` SET `img`='$imgname' WHERE `id`='$arrusrselect[id]'");
$upimg=$mysqli->query("UPDATE `profile_img` SET `visibility`='$_POST[img_pub]' WHERE `id`='$arrusrselect[id]'");
header('Location: '.$_SERVER['REQUEST_URI']);
}
}
else {
$mtype="error";
$alertc="Invalid file. Only image files are allowed<br/>\n";
$labelc="labeler";
$inputc="er";
}
}
else {
$inputc="input";
$labelc="label";
if (isset($_POST['img_pub'])) {
setcookie("success", "Profile picture visibility updated<br/>");
$upimg=$mysqli->query("UPDATE `profile_img` SET `img`='$imgname', `visibility`='$_POST[img_pub]' WHERE `id`='$arrusrselect[id]'");
header('Location: '.$_SERVER['REQUEST_URI']);
}
}
//check image visibility
//image check complete
//checking complete
$prof_img=$mysqli->query("SELECT `visibility` FROM `profile_img` WHERE `id`='$arrusrselect[id]'");
$prof_img_slct = mysqli_fetch_array($prof_img);
if (($prof_img_slct[visibility]) == "Public") {
$imgchecka = "checked='checked'";
}
elseif (($prof_img_slct[visibility]) == "UsersOnly") {
$imgcheckb = "checked='checked'";
}
else {
$imgcheckc = "checked='checked'";
}
if (isset($_COOKIE['success'])) {
echo "<div id=\"msg\" class=\"success hide\">$_COOKIE[success]</div>\n";
setcookie("success", "", time()-3600);
}
elseif (isset($mtype)) {
echo "<div id=\"msg\" class=\"".$mtype."\">".$alerta.$alertb.$alertc.$alertd.$alerte."</div>\n";
}
echo "<form action='test.php' method='post' enctype='multipart/form-data'>\n";
echo "<table class='login'>\n";
echo "<tr><td class='$labelc'>New Profile Picture:</td><td class='input'><input type='file' name='file' class='$inputc' id='file' /></td><td class='input'> <input type='radio' name='img_pub' value='Public' $imgchecka /> </td><td class='input'> <input type='radio' name='img_pub' value='UsersOnly' $imgcheckb /> </td><td class='input'> <input type='radio' name='img_pub' value='Hide' $imgcheckc/> </td></tr>\n";
echo "<tr><td class='label'></td><td class='input'><p class='flag'> Max. size is 500kB. Allowed file types .jpg, .png & .gif </p></td></tr>\n";
echo "<tr><td></td><td><input type='submit' value='Update' /></td></tr>\n";
echo "</table></form>\n";
include("includes/footer.php");
?>
我想做的是更改用户图像的可见性,即使用户没有选择要上载的文件。未选择任何文件时,警报将正确显示。但当我给出一个错误的文件时,例如一个.txt文件的实例页面仍然显示更新的个人资料图片可见性,而不是预期结果无效的文件。只允许使用图像文件
我做错了什么?您可以尝试以下代码:
$error = 1; // this flag will decide any error happens or not
if (!empty($_FILES["file"])) {
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && in_array($extension, $allowedExts)) {
if ($_FILES["file"]["size"] > 524288000) {
$error = 0; // this error so make it 0
$alertc="Image is too large<br/>\n";
}
else {
$imgname = $arrusrselect[id].md5($arrusrselect[id]).$arrusrselect[id].".jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "../images/user/profile/" . $imgname);
$upusers=$mysqli->query("UPDATE `users` SET `img`='$imgname' WHERE `id`='$arrusrselect[id]'");
}
}
else {
$alertc="Invalid file. Only image files are allowed";
$error = 0; // this error so make it 0
}
}
else {
}
//check image visibility
//If all well then, $error will be 1 otherwise 0 so in case of error like invalid file or file too large, following code doesn't execute.
if (isset($_POST[img_pub]) && $error) {
$alertc="Profile picture visibility updated";
$upimgvis=$mysqli->query("UPDATE `profile_img` SET `visibility`='$_POST[img_pub]' WHERE `id`='$arrusrselect[id]'");
}
在进行可见性更新之前,可以检查$alertc是否未设置。您还以一种不推荐的方式访问数组值$\u POST[key]应该是$\u POST['key'],在定义字符串时使用双引号时,可以将变量括在{$\u POST['key']}中
<?php
if (!empty($_FILES['file'])) {
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && in_array($extension, $allowedExts)) {
if ($_FILES["file"]["size"] > 524288000) {
$alertc="Image is too large<br/>\n";
}
else {
$imgname = $arrusrselect['id'].md5($arrusrselect['id']).$arrusrselect['id'].".jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "../images/user/profile/" . $imgname);
$upusers = $mysqli->query("UPDATE `users` SET `img`='$imgname' WHERE `id`='{$arrusrselect['id']}'");
}
}
else {
$alertc="Invalid file. Only image files are allowed";
}
}
//check image visibility
if (isset($_POST['img_pub']) && !isset($alertc)) {
$alertc="Profile picture visibility updated";
$upimgvis=$mysqli->query("UPDATE `profile_img` SET `visibility`='{$_POST['img_pub']}' WHERE `id`='{$arrusrselect['id']}'");
}
//image check complete
?>
我刚刚测试了你的代码,它很混乱,我不相信它真的能工作,但是你没有收到错误消息,因为以下原因: 更新文件时,使用setcookie。。我不认为这是实现打印成功消息的正确方法,然后为用户重新加载页面,以便它直接加载到if$\u文件和if$\u后期检查 然后检查此cookie是否存在打印其值,然后尝试取消设置此cookie,此时代码失败,因为如果页面中打印了任何内容,则无法发送header setcookie、header、session 现在,如果您修复了它也无法工作的问题,因为您正在同一请求中提交图像文件、图像隐私$\u文件和$\u POST,因此如果$\u文件失败,则$\u POST请求将成功,它将重新加载页面,错误变量将丢失 我不知道你为什么要使用标题位置:。。。函数在上传成功时,如果用户重新加载页面,您不希望他重新提交数据吗?这不是一个问题,甚至不是一个安全问题。若要用success消息设置cookies并显示它们,有更好的方法 我很快调整了你的代码,测试它是否适合你,并注意到这不是最好的正确方法,我只提供给你这个,这样你就可以学习在PHP中处理表单的基本结构,这样你就可以在函数和类中使用它们
<?php
/* ADD THE PRIVACY TYPES INTO AN ARRAY,
THE USER CAN CHANGE THE VALUE INTO
SOMETHIING IS NOT IN YOUR CODE
AND SEND IT TO DATABASE
*/
$pubTypes = array(
"Public" => 1,
"UsersOnly" => 1,
"Hide" => 1
);
#check if the submit button is clicked;
if($_POST['Update']){
#This (if) will check and update both file and privacy radio on each submit
#the file validation and upload.
#check if the file is not empty;
if(!empty($_FILES["file"])) {
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && in_array($extension, $allowedExts)) {
#file type is allowed, continue and check size;
if ($_FILES["file"]["size"] > 524288000) {
/*
$mtype="error";
$alertc="Image is too large<br/>\n";
$labelc="labeler";
$inputc="er";
*/
#set upload error/success to an array
$fileup = array(
"error" => 1,
"msg" => "Image is too large"
);
}
else {
#file size allowed upload the image and insert the values in the db
$imgname = md5(time() - rand(0,999))."-".$arrusrselect["id"].".".$extension;
#upload image and detect any error
if(move_uploaded_file($_FILES["file"]["tmp_name"], "images/user/profile/" . $imgname)){
#image uploaded successfuly
#update the data base
if($upusers=$mysqli->query("UPDATE `users` SET `img`='{$imgname}' WHERE `id`='{$arrusrselect['id']}'")){
$fileup = array(
"success" => 1,
"msg" => "Profile picture updated."
);
}else{
$fileup = array(
"error" => 1,
"msg" => "Error updating the new picture value in the database."
);
#AT THIS POINT, you better delete the new image from server.
#@unlink("images/user/profile/" . $imgname);
}
}else{
#image upload ERROR
$fileup = array(
"error" => 1,
"msg" => "Error moving the file to the server."
);
}#endelse
}#end if file size allowed
}#end if if file type allowed
else{
#file type is not allowed
$fileup = array(
"error" => 1,
"msg" => "Invalid file. Only image files are allowed"
);
}
}else{ #file IS EMPTY
/*NO need to print erros, because a user may
only update his profile privacy only without
submitting a new image*/
}
/* CHECK PROFILE PRIVACY UPDATE */
if(!empty($pubTypes[$_POST['img_pub']])){
#check if img_pub selected and its in a valid type, update the database.
#you have to check the $imgname, because the upload may have returned errors.
if($imgname){
$sql = "UPDATE `profile_img` SET `img`='{$imgname}', `visibility`='{$_POST['img_pub']}' WHERE `id`='{$arrusrselect[id]}'";
}else{
$sql = "UPDATE `profile_img` SET `visibility`='{$_POST['img_pub']}' WHERE `id`='{$arrusrselect[id]}'";
}
#send the update query
if($upimg=$mysqli->query($sql)){
$pubup = array(
"success" => 1,
"msg" => "Profile picture visibility updated"
);
}else{
$pubup = array(
"error" => 1,
"msg" => "Error updating picture visibility."
);
}
}else{
#invalid type, do nothing or you can reset the option to the default
$pubup = array(
"error" => 1,
"msg" => "Invalid visibility type."
);
}
}#end of $_POST['Update'];
#END OF CHECKING IF THE FORM WAS POST;
//get user's image and visibilty settings.
$prof_img=$mysqli->query("SELECT * FROM `profile_img` WHERE `id`='{$arrusrselect['id']}'");
$prof_img_data = mysqli_fetch_array($prof_img);
$vis = $prof_img_data['visibility'];
if($pubTypes[$vis]) {$pubTypes[$vis] = 'checked';}
#you can use the image in html
$imgname = $prof_img_data['visibility'];
# PRINT UPLOAD AND UPDATE RESULT IF ERROR OR SUCCESS
#check file upload result, class will be class="file-error" OR class="file-success"
if(is_array($fileup)){
echo "<p class='file-{$fileup['result']}'>Image upload: {$fileup['msg']}</p>";
}
#check profile visibility result, class will be class="pub-error" OR class="pub-success"
if(is_array($pubup)){
echo "<p class='pub-{$pubup['result']}'>Visibility update: {$pubup['msg']}</p>";
}
?>
<form action='<?= $_SERVER['PHP_SELF']; ?>' method='post' enctype='multipart/form-data'>
<table class='login'>
<tr>
<td class='<?php $fileup['error'] ? print("errorClass") : '';?>'>New Profile Picture:</td>
<td class='input'><input type='file' name='file' class='<?php $fileup['error'] ? print("er") : print("inputc");?>' id='file' /></td>
<?php foreach($pubTypes as $key=>$value){
echo "<td class='input'><input type='radio' name='img_pub' value='$key' value=".($value != 1 ? 'checked' :'')." /></td>";
}?>
</tr>
<tr>
<td class='label'></td>
<td class='input'><p class='flag'> Max. size is 500kB. Allowed file types .jpg, .png & .gif </p></td>
</tr>
<tr><td></td><td><input type='submit' name='Update' value='Update' /></td></tr>
</table></form>
你试过投吗!空的$\u文件[文件]带双引号!空$_文件[file]@MohdMoe是的。但是没有运气哦,你确定你在重复这个错误吗?尝试添加退出$alertc;$alertc之后=无效文件。只允许使用图像文件;奇怪的文件中还有其他代码吗?你能发布你的html代码吗?@MohdMoe请检查编辑的代码。完整的php就在那里