You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在PHP或Laravel中如何从URL获取与HTML表单$_FILES格式一致的图片数据

实现思路

PHP通过表单上传得到的单文件$_FILES结构固定包含5个字段,我们只需手动构造完全匹配该结构的数组即可,对应字段说明:

  • name:文件原始文件名
  • type:文件MIME类型
  • tmp_name:文件在服务器上的临时存储路径
  • error:上传错误码,上传成功固定为UPLOAD_ERR_OK(值为0)
  • size:文件大小,单位为字节

场景1:读取服务器本地已有文件
// 替换为你的本地文件实际路径
$localFilePath = '/www/project/test.jpg';
// 自定义原始文件名,对应表单上传时用户端的文件名
$originFileName = 'test.jpg';

// 构造与表单上传完全一致的文件数据
$fileInfo = [
    'name' => $originFileName,
    'type' => mime_content_type($localFilePath),
    'tmp_name' => $localFilePath,
    'error' => UPLOAD_ERR_OK,
    'size' => filesize($localFilePath)
];

场景2:读取远程URL文件

基础版(需开启allow_url_fopen配置)

$url = 'https://pbs.twimg.com/profile_images/805651234698842112/uPSrYOHT.jpg';
// 从URL提取原始文件名
$originFileName = basename(parse_url($url, PHP_URL_PATH));
// 生成和PHP原生上传一致的临时文件路径
$tmpFilePath = sys_get_temp_dir() . '/' . uniqid() . '.' . pathinfo($originFileName, PATHINFO_EXTENSION);

// 下载远程文件到临时目录
file_put_contents($tmpFilePath, file_get_contents($url));

// 构造与表单上传完全一致的文件数据
$fileInfo = [
    'name' => $originFileName,
    'type' => mime_content_type($tmpFilePath),
    'tmp_name' => $tmpFilePath,
    'error' => UPLOAD_ERR_OK,
    'size' => filesize($tmpFilePath)
];

兼容版(cURL实现,无需开启allow_url_fopen)

$url = 'https://pbs.twimg.com/profile_images/805651234698842112/uPSrYOHT.jpg';
$originFileName = basename(parse_url($url, PHP_URL_PATH));
$tmpFilePath = sys_get_temp_dir() . '/' . uniqid() . '.' . pathinfo($originFileName, PATHINFO_EXTENSION);

$ch = curl_init($url);
$fp = fopen($tmpFilePath, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
curl_close($ch);
fclose($fp);

$fileInfo = [
    'name' => $originFileName,
    'type' => mime_content_type($tmpFilePath),
    'tmp_name' => $tmpFilePath,
    'error' => UPLOAD_ERR_OK,
    'size' => filesize($tmpFilePath)
];

注意事项
  • 手动构造的文件数据无法使用move_uploaded_file()移动,直接用rename()函数操作即可
  • 读取远程文件前建议添加HTTP状态码校验,避免下载到404等无效响应内容

内容的提问来源于stack exchange,提问作者FGtaV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:54:03