【问题标题】:Check if user has selected a file to upload检查用户是否选择了要上传的文件
【发布时间】:2016-02-15 07:13:39
【问题描述】:

我正在尝试编写一个脚本,系统会在其中检查用户是否在上传任何内容之前选择了要上传的文件。我遇到的问题是,即使我没有选择文件,系统也会回显文件已成功上传。见以下代码:

<?php
include("dbconfig.php");

if(isset($_POST['btn-upload'])) {

    $loggedinuser = $_GET['bid'];   
    $file = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];

    $sql = mysqli_query($conn, "INSERT INTO upload (personalid, file, type, size) values ((select personalid from person where username='$loggedinuser'), '$file', '$file_type', '$file_size')") or die (mysqli_error($conn));

    if($sql){
        header("location:upload.php?msg0=Document upload successful.");     
    } elseif( !file_exists($_FILES['file']['name']) || !is_uploaded_file($_FILES['file']['name']) ) {
        header("location:upload.php?msg1=Document upload failed.");
    }
}
?>
<!-- need to comment -->

更新版本 - 16:34 (13/11/2015)

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include("dbconfig.php");
if(isset($_POST['btn-upload'])){

if (empty($_FILES['file']['name'])){

    echo 'error!';

} else {

$loggedinuser = $_GET['bid'];

$file = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$sql = mysqli_query($conn, "INSERT INTO upload (personalid, file, type, size) values ((select personalid from person where username='$loggedinuser'), '$file', '$file_type', '$file_size')") or die (mysqli_error($conn));

if($sql){
    header("location:upload.php?msg0=Document upload successful.");     
}
else {
    header("location:upload.php?msg1=Document upload failed.");
}
}
}


 ?>
<!-- need to commentt -->

我在网上做了一些研究,我遇到了一些讨论,提到您可以使用我们 file_existsis_uploaded_file - 我不确定我是否正确使用它们。请告诉我如何在上传之前检查用户是否选择了文件。

谢谢,

苏海尔。

【问题讨论】:

  • 检查$_FILES['file']['name']是否为空
  • 在这方面你唯一能做的检查就是使用javascript,因为file_existsis_uploaded_file等只会在提交后被调用..
  • if (isset($_FILES['file']['name'])) 是我检查上传文件的方式
  • 你应该检查你的语法。您似乎也有语法错误。 error_reporting( E_ALL );

标签: php


【解决方案1】:

目前,您的声明仅在按钮作为 POST 请求被按下时才是基于的,它将始终如此。

我不是 100% 同意这个问题,但我准备尝试回答这个问题。

$loggedinuser = $_GET['bid'];
if (isset($_FILES['file']['name']) && !empty($_FILES['file']['name'])) {
    $file = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];
}

if (isset($file) && isset($file_size) && isset(file_type)) {    
  SQL stuff;
}

if(isset($sql) && $sql){
    header("location:upload.php?msg0=Document upload successful.");     
} else {
    header("location:upload.php?msg1=Document upload failed.");
}

顺便说一句,你能不能只确保 HTML 中的字段是必需的?

【讨论】:

  • 感谢您的努力,但我已经纠正了这个问题。
  • @MuhammadSohailArif:有什么问题?
  • 过去我通常只是将 required 放在输入的 html 部分 我很想知道什么是结果,我没有自己测试上面的代码,它是我自己的。
猜你喜欢
  • 2021-11-02
  • 1970-01-01
  • 2016-06-06
  • 2011-02-26
  • 2014-11-17
  • 1970-01-01
  • 2018-04-01
  • 2011-05-09
  • 1970-01-01
相关资源
最近更新 更多