将远程URL上传到服务器

时间:2012-09-19 06:24:55

标签: php url

我使用以下代码将远程文件上传到我的服务器。它在直接下载链接的情况下工作得很好,但最近我注意到很少有网站提供mysql链接作为下载链接,当我们点击该链接时,文件开始下载到我的电脑。但即使在该页面的html源代码中,也没有显示直接链接。

这是我的代码:

 <form method="post">
 <input name="url" size="50" />
 <input name="submit" type="submit" />
 </form>
 <?php
 if (!isset($_POST['submit'])) die();
 $destination_folder = 'mydownloads/';
 $url = $_POST['url'];
 $newfname = $destination_folder . basename($url);
 $file = fopen ($url, "rb");
 if ($file) {
 $newf = fopen ($newfname, "wb");

  if ($newf)
 while(!feof($file)) {
 fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
 }
 }

 if ($file) {
  fclose($file);
 }

if ($newf) {
fclose($newf);
}

?>

它适用于下载链接是直接的所有链接,例如,如果我愿意      http://priceinindia.org/muzicpc/48.php?id=415508链接它将上传音乐文件,但文件名将是48.php?id = 415508但实际的mp3文件存储在
     http://lq.mzc.in/data48-2/37202/Appy_Budday_(Videshi)-Santokh_Singh(www.Mzc.in).mp3

因此,如果我可以获得实际的目标网址,名称将为Appy_Budday_(Videshi)-Santokh_Singh(www.Mzc.in).mp3

所以我想获得实际的下载URL。

2 个答案:

答案 0 :(得分:1)

您应该使用Curl库。 http://php.net/manual/en/book.curl.php

关闭连接之前,在手动(在该链接上)befo中提供了如何使用curl的示例,请调用curl_getinfo(http://php.net/manual/en/function.curl-getinfo.php)并特别得到你想要的CURLINFO_EFFECTIVE_URL。

<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');

// Execute
$fileData = curl_exec($ch);

// Check if any error occured
if(!curl_errno($ch)) {
    $effectiveURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
}

// Close handle
curl_close($ch);
?> 

(您也可以使用curl直接写入文件 - 使用CURLOPT_FILE选项。也可以在手册中)

答案 1 :(得分:0)

问题是原始网址是重定向的。您想要捕获重定向到的URL,尝试使用标头,然后获取基本名称($ redirect_url)作为您的文件名。

罗比使用CURL

+1。

如果你跑(从命令行)

[username@localhost ~]$ curl http://priceinindia.org/muzicpc/48.php?id=415508 -I
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.0.10
Date: Wed, 19 Sep 2012 07:31:18 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.3.10
Location: http://lq.mzc.in/data48-2/37202/Appy_Budday_(Videshi)-Santokh_Singh(www.Mzc.in).mp3

您可以在此处看到位置标题是新网址。

在php中尝试

之类的东西
$ch = curl_init('http://priceinindia.org/muzicpc/48.php?id=415508'); 
curl_setopt($ch, CURLOPT_HEADER, 1); // return header
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // dont redirect 
$c = curl_exec($ch); //execute
echo curl_getinfo($ch, CURLINFO_HTTP_CODE); // will echo http code.  302 for temp move
echo curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // url being redirected to

您想要找到标题的位置部分。不确定设置是否确定。

编辑3..or 4? 是的,我知道发生了什么事。您实际上想要按照位置网址然后回显有效网址而不下载文件。尝试。

$ch = curl_init('http://priceinindia.org/muzicpc/48.php?id=415508');
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$c = curl_exec($ch); //execute
echo curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // url being redirected to

当我运行时,我的输出是

[username@localhost ~]$ php test.php
http://lq.mzc.in/data48-2/37202/Appy_Budday_(Videshi)-Santokh_Singh(www.Mzc.in).mp3
相关问题