通过URL在php中保存文件

时间:2013-04-03 20:23:47

标签: php file-upload curl

我有一个函数应该将文件保存到我的服务器,该函数需要两个参数文件url和文件名,它将在数据库中保存它

function saveFile($url, $filename){

    $location = "http://138.90.30.311/docs/";
    $ext = pathinfo($url, PATHINFO_EXTENSION);
    $file_path = $location.''.$filename.'.'.$ext;
    $ch = curl_init($url);
    $fp = fopen($file_path, 'wb');  //Error here (line 16)
    curl_setopt($ch, CURLOPT_FILE, $fp);  //Error here (line 17)
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);        
}

传入的参数示例为

filename = 14426
url = http://u.goal.com/269000/269085_hp_thumb.jpg

我有一次工作,但它似乎不再保存文件而且我得到3个错误

Warning: fopen(http://138.90.30.311/docs/14426.jpg) [function.fopen]: failed to open stream: HTTP wrapper does not support writeable connections in C:\wamp\www\functions.php on line 16

Warning: curl_setopt(): supplied argument is not a valid File-Handle resource in C:\wamp\www\functions.php on line 17

在第二次错误之后,我收到很多垃圾回传给浏览器

Warning: fclose() expects parameter 1 to be resource, boolean given in C:\wamp\www\functions.php on line 21

1 个答案:

答案 0 :(得分:0)

您无法将文件写入网站(使用HTTP),如错误消息所示。如果您考虑一下,这是一件好事,否则我可能会在未经您许可的情况下将文件写入您的网站!

您为fopen(特别是$location)提供的文件路径必须是运行PHP的服务器上的某个普通文件路径。