这是我检查上传文件的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(".", $_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文件的实例页面仍显示"Profile picture visibility updated"
而不是预期的结果"Invalid file. Only image files are allowed"
我做错了什么?
答案 0 :(得分:2)
我刚刚测试了你的代码,它的凌乱,我不相信它会真的有用,但是由于以下原因你没有得到错误信息:
当文件更新时,你使用setcookie(..)
我不相信是实现打印出“成功消息”的正确方法,然后你为用户重新加载页面,以便它直接加载到{{1}之后1}}检查。
然后你检查这个cookie是否存在你打印它的值然后你试图取消设置这个cookie,此时你的代码失败了,因为你不能发送头文件(setcookie,header(),session())如果有的话打印在页面中。
现在,如果您修复了它也无法正常工作,因为您在同一请求中同时提交了图像文件和图片隐私if $_FILES and if $_POST
,因此$_FILES and $_POST
如果$_FILES
失败了$_POST
请求将成功,它将重新加载页面,错误变量将丢失。
我不知道为什么你会在上传成功时使用header("location:...")
函数,你不希望用户重新加载页面时重新提交数据?它不是一个问题,如果它是用成功的msg设置cookie并显示它们,甚至不是安全问题,还有更好的方法。
我快速调整你的代码,测试它是否适合你,注意这不是以正确的方式做到这一点的最佳方式,我只提供你这样你就可以学习基本结构用于处理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>
答案 1 :(得分:1)
您可以尝试以下代码:
$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]'");
}
答案 2 :(得分:1)
在进行可见性更新之前,您可以检查是否未设置$alertc
。您还以不推荐的方式访问数组值$_POST[key]
$_POST['key']
在定义字符串时使用{$_POST['key']}
双引号时,"
可以包围var。
<?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
?>