【问题标题】:file_get_contents doesn't work with tmp filefile_get_contents 不适用于 tmp 文件
【发布时间】:2014-09-11 16:21:20
【问题描述】:

我的问题:我想用 BLOB 将图像插入到 MySQL 表中。在同一个项目中,我上传了一个文件,但只是 VARCHAR 列中的链接,它可以工作。现在我尝试使用file_get_contentsfread,它们都返回空字符串。我的代码有什么问题?还是php.ini的配置有问题?代码是:

    $imgdata = NULL;
    $imgext = NULL;
    $file = $_FILES['foto'];
    if (!in_array($file['type'], $con->ext)) {
        exit('Archivo no permitido');
    } else {
        if ($file['error'] === FALSE) {
            exit('Error ' . $file['error']);
        } else {
            $attachtmp = $file['tmp_name'];
            $imgext = $file['type'];
            if (file_exists($attachtmp)) {
                if (is_uploaded_file($attachtmp)) {
                    $fp = fopen($attachtmp, 'r+b');
                    $imgdata = fread($fp, filesize($attachtmp));
                    fclose($fp);
                    //if (empty(file_get_contents($attachtmp))) {
                    //$imgdata = $con->real_escape_string(file_get_contents($attachtmp));
                    //}
                } else {
                    exit('<h3>Error interno del servidor<h3>');
                }
            } else {
                exit('<h3>Error error interno del servidor<h3>');
            }
        }
    }

【问题讨论】:

  • $file = $_FILES['foto']['name'];$file = $_FILES['foto']['tmp_name'];
  • 您从来不用检查上传是否成功。你只是假设它做到了。如果上传失败,则['tmp_name'] 将指向一个不存在或已损坏的文件。
  • 如何验证文件是否损坏?
  • echo "Error: " . $_FILES["foto"]["error"] . "&lt;br&gt;";

标签: php mysql file-get-contents fread


【解决方案1】:

首先检查你的结果:

// Check $_FILES['foto']['error'] value.
switch ($_FILES['foto']['error']) {
    case UPLOAD_ERR_OK:
        break;
    case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('No file sent.');
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        throw new RuntimeException('Exceeded filesize limit.');
    default:
        throw new RuntimeException('Unknown errors.');
}

取自php manual

【讨论】:

  • 好像?不管是不是。您需要将文件移动到具有安全名称的安全位置,然后打开它,请参阅我帖子中的链接示例
  • 抱歉,似乎。是的,它已正确上传,因为该文件存在于临时 php 文件中。我以同样的方式上传了文件,只是将file_get_contents 更改为move_uploaded_file 并且可以工作。
猜你喜欢
  • 2011-03-28
  • 2017-03-02
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多