需要使用php将远程文件保存在磁盘上

时间:2013-01-07 09:47:17

标签: php curl save

您好我正在尝试使用php将文件保存在磁盘上,当我在“位置”变量中复制文件的地址时,它可以工作,但是当我使用javascript函数传递值时,它不会。我认为这个问题是由于空白或类似的问题,但不知道如何解决它。

function upload(location){
if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("myOutput").innerHTML="done";
                }
            }
            xmlhttp.open("GET","SaveFiles.php?a="+location,true);
            xmlhttp.send();
    }  

   if(isset($_GET["a"]))
   {
     $Location = $_GET["a"];
     FileFunc($Location);
   }

 function FileFunc($Location){

     // $Location = "http://www.xxx.com/1.jpg"; <<When I uncomment this line it works
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $Location);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $myFile = curl_exec($ch);
     curl_close($ch);
     $file = 'myFile.jpg';
     file_put_contents($file, $myFile);
 }

1 个答案:

答案 0 :(得分:0)

您必须将服务器主机添加到您的卷曲地址

 function FileFunc($Location){

  $Location = $_SERVER['HTTP_HOST']."/".$Location;
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $Location);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $myFile = curl_exec($ch);
 curl_close($ch);
    $file = 'myFile.jpg';
 file_put_contents($file, $myFile);
}