如何通过is_uploaded_file签入php?

How to pass is_uploaded_file check in php?

我正在使用 php 代码(不是来自用户 post 请求)将文件从外部文件上传到 tmp 文件夹,然后用该文件的信息填充 $_FILES 并将其传递给使用的代码$_FILES 变量。 但在该代码中,它使用 move_uploaded_file,具有 is_uploaded_file 检查。通过代码(而不是用户表单 posted)手动上传的文件未通过此检查,因为它不是使用 POST 上传的。我能让它通过检查吗?

失败的代码:

//$url contains url of image from another site
function upload_from_url($url)
{
    global $modx;
    // we load temporary file to /tmp and then add it to $_FILES
    $img = '/tmp/'.uniqid("", true); // no extension here since we can't trust it
    $res = file_put_contents($img, file_get_contents($url)); // UPLOAD is made here, it works
    $mimeType = mime_content_type($img);
    $allowedMimeTypes = ["image/jpeg","image/gif","image/png"];
    if (!in_array($mimeType, $allowedMimeTypes))
    {
        logError("!!!ATTENTION!!! got file $img with forbidden mime type $mimeType");
        throw new RuntimeException("Forbidden file mime type!"); 
        die; // just to be sure; shouldn't get here
    }
    $_FILES['file']['name'] = uniqid("img", true)."."
        .(explode("/", $mimeType)[1]); // get jpg part of image/jpg
    $_FILES['file']['type'] = $mimeType;
    $_FILES['file']['tmp_name'] = $img;
    $_FILES['file']['error'] = 0; // = UPLOAD_ERR_OK
    $_FILES['file']['size'] = filesize($img);
    $response = $modx-> runProcessor('browser/file/upload', ['path' => 'assets/images']); // <= here it fails
}

$modx-> runProcessor('browser/file/upload'... 代码中,有部分失败:

    if (!move_uploaded_file($file['tmp_name'],$newPath)) {
        $this->addError('path',$this->xpdo->lexicon('file_err_upload'));
        continue;
    }

它从 $_FILES 变量的 $files 获取 $file,我不想修改框架代码来解决它。

move_uploaded_file 的文档指出:

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

所以看起来如果文件没有实际发布,这是不可能的。您仍然可以通过 rename.

移动之前上传的文件

我认为您无法让 php 核心相信它确实是上传的文件,但您可以尝试使用 MODX 媒体源而不是上传处理器。

获取媒体源的实例,对其进行初始化,然后使用createObject创建文件:

$source = $modx->getObject('sources.modMediaSource', $idOfSource);
if ($source && $source->initialize()) { 
    $source->createObject($objectPath, $name, $content)
}