这很有效。事实是,如果用户没有选择文件,则会出错。如果没有选择文件,我怎么能不检查任何文件,如果选择了文件则只检查错误。
此功能位于<form>
内,并在提交表单时运行。
if (empty($errors) === true){
if (isset($_FILES['cover']) === true){
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['cover']['name'];
$file_size = getimagesize($_FILES['cover']['name']);
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['cover']['tmp_name'];
if(in_array($file_extn, $allowed) === true){
$file_path = 'images/cover/' . substr(md5(time()), 0, 10) . '.' . $file_extn;
move_uploaded_file($file_temp, $file_path);
}else{
$errors[] = 'Incorrect file type. Only allowed: ' . implode(', ', $allowed) . '';
}
}
答案 0 :(得分:0)
也许这样的事情对你有用......
if (!empty($_FILES['cover'])){
if (empty($errors) === true){
if (isset($_FILES['cover'])){
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['cover']['name'];
$file_size = getimagesize($_FILES['cover']['name']);
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['cover']['tmp_name'];
if(in_array($file_extn, $allowed) === true){
$file_path = 'images/cover/' . substr(md5(time()), 0, 10) . '.' . $file_extn;
move_uploaded_file($file_temp, $file_path);
}else{
$errors[] = 'Incorrect file type. Only allowed: ' . implode(', ', $allowed) . '';
}
}
}
答案 1 :(得分:0)
测试它或其余数据是否设置为空?如何?
if (!empty($_FILES['cover'])) {
if ($_FILES['cover']['name'] != "") {
// execute your code here
} else if ($_FILES['cover']['name'] == "") {
// do nothing
// or header them to the appropriate page
header("location: http://yourpage.com");
exit();
}
}
我添加了这个以查看我们是否在同一页面上。
if (!empty($_FILES['cover'])){
if ( $_FILES['cover']['name'] != "") {
$file_name = $_FILES['cover']['name'];
// etc
// then the rest of your code
} else {
// do nothing
}
} else {
// do nothing or header to appropriate location and exit
header("location: http://yourpage.com");
exit();
}
好的,试试这个:
if(!empty($_FILES['cover'])) {
if($_FILES['cover']['tmp_name'] != "") {
$fileName = $_FILES["cover"]["name"];
$fileTmpLoc = $_FILES["cover"]["tmp_name"];
$fileType = $_FILES["cover"]["type"];
$fileSize = $_FILES["cover"]["size"];
$fileErrorMsg = $_FILES["cover"]["error"];
$boomBoom = explode(".", $fileName);
$fileExt = end($boomBoom);
// this next if is okay because if a new file is not selected
// the script wouldn't make it this far anyway
// so this will not require a new selection
// just a check that should pass every time
if (!$fileTmpLoc){
echo "ERROR: Please browse for a file before uploading";
exit();
}
else if($fileSize > 20480000){
echo "ERROR: Your file was larger than 20 Megabytes";
unlink($fileTmpLoc);
exit();
}
else if (!preg_match("/.(gif|jpg|png|jpeg)$/i", $fileName)){
echo "ERROR: Your image was not .gif, .jpg, .jpeg, or .png.";
unlink($fileTmpLoc);
exit();
}
else if ($fileErrorMsg == 1){
echo "ERROR: An error occurred.";
exit();
}
move_uploaded_file($_FILES['cover']['tmp_name'], "pathTo/$fileName");
header("location: http://www.yoursite.com");
exit();
}
}