通过URL在php中保存文件


Saving File in php through URL

我有一个函数应该保存一个文件到我的服务器,该函数需要两个参数文件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

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

您给fopen(特别是$location)的文件路径需要是PHP运行的服务器上的某个地方的普通文件路径。