duanchongzi9997 2012-12-17 11:28 采纳率: 0%
浏览 33
已采纳

如何保存以curl形式提交的文件网址?

I am trying to create an upload plugin that allows for a user to upload any file from their computer or from a url they type into the provided text field.

This is the script I have to upload files from a local disk:

session_start();
//Loop through each file
for($i=0; $i<count($_FILES['file']); $i++) {
  //Get the temp file path
  if (isset($_FILES['file']['tmp_name'][$i]))
  {
  $tmpFilePath = $_FILES['file']['tmp_name'][$i];
  }

  //Make sure we have a filepath
  if ($tmpFilePath != ""){
    //Setup our new file path
    if (isset($_FILES['file']['name'][$i]))
    $newFilePath = "./uploaded_files/" . $_FILES['file']['name'][$i];
    }

    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

    echo "Uploaded Successfully!<br />";

}

All I need now is for the curl part to take the file from the url submitted in the text field and save it to the same location.

Here is the cURL I have so far:

function GetImageFromUrl($link) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_setopt($ch,CURLOPT_URL,$link);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result=curl_exec($ch);
    curl_close($ch);
    return $result;
}

$sourcecode=GetImageFromUrl("http://domain.com/path/image.jpg");
$savefile = fopen('/home/path/image.jpg', 'w');
fwrite($savefile, $sourcecode);
fclose($savefile);
  • 写回答

1条回答 默认 最新

  • dongxie7683 2012-12-17 11:43
    关注

    Is there a specific reason you want to use curl? Here's how you can simply do that without it:

    $url = $_POST['url'];
    $file_content = file_get_contents($url);
    $file_name = array_pop(explode('/', parse_url($url, PHP_URL_PATH)));
    file_put_contents('/home/path/' . $file_name, $file_content);
    

    You should also consider looking into $url and checking if it's valid before working with it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?