I have script-1 on server A, where user ask for a file.
I have script-2 on server B (the file repository) where I check that user can access it and return the correct file (I'm using Smart File Download http://www.zubrag.com/scripts/download.php).
I've tried cURL and file_get_contents, I've changed Content Header in various ways, but I wasn't still able to download the file.
This is my request:
$request = "http://mysite.com/download.php?f=test.pdf";
and it works fine.
What should I call in script-1 to force the file be downloaded?
Some of my tries
This works, but I don't know how to handle unauthorized or broken downloads
header('Content-type: application/pdf');
$handle = fopen($request, "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
This prints the pdf code (not the text) straight in the browser (I think it's a header problem):
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $request);
$contents = curl_exec($c);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
This generate a white page
file_get_contents($request);
To force download, add
header('Content-disposition: attachment');
But Note, that it's not in HTTP 1.1 spec anymore, see Uses of content-disposition in an HTTP response header first answer
Without your code I don't know what you've tried, but you need to get the contents of the file via cURL and then save it to your server. Something like...
$url = 'http://website.com/file.pdf';
$path = '/tmp/file.pdf';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
curl_close($ch);
file_put_contents($path, $contents);
If you want to downloads file from the FTP server you can use php File Transfer Protocol (FTP) extension. Please find below code:
<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);
// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);
$server_file="test.pdf" //FTP server file path
$local_file = "new.pdf"; //Local server file path
##----- DOWNLOAD $SERVER_FILE AND SAVE IT TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
ftp_close($conn_id);
?>
Download the file with curl, then check this: http://php.net/function.readfile
It shows how to force download.
SOLVED
I ended by simply redirect the request with:
header("Location: $request");
Related
I am looking for a function that gets the metadata of a .mp3 file from a URL (NOT local .mp3 file on my server).
Also, I don't want to install http://php.net/manual/en/id3.installation.php or anything similar to my server.
I am looking for a standalone function.
Right now i am using this function:
<?php
function getfileinfo($remoteFile)
{
$url=$remoteFile;
$uuid=uniqid("designaeon_", true);
$file="../temp/".$uuid.".mp3";
$size=0;
$ch = curl_init($remoteFile);
//==============================Get Size==========================//
$contentLength = 'unknown';
$ch1 = curl_init($remoteFile);
curl_setopt($ch1, CURLOPT_NOBODY, true);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, true);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch1);
curl_close($ch1);
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
$size=$contentLength;
}
//==============================Get Size==========================//
if (!$fp = fopen($file, "wb")) {
echo 'Error opening temp file for binary writing';
return false;
} else if (!$urlp = fopen($url, "r")) {
echo 'Error opening URL for reading';
return false;
}
try {
$to_get = 65536; // 64 KB
$chunk_size = 4096; // Haven't bothered to tune this, maybe other values would work better??
$got = 0; $data = null;
// Grab the first 64 KB of the file
while(!feof($urlp) && $got < $to_get) { $data = $data . fgets($urlp, $chunk_size); $got += $chunk_size; } fwrite($fp, $data); // Grab the last 64 KB of the file, if we know how big it is. if ($size > 0) {
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RESUME_FROM, $size - $to_get);
curl_exec($ch);
// Now $fp should be the first and last 64KB of the file!!
#fclose($fp);
#fclose($urlp);
} catch (Exception $e) {
#fclose($fp);
#fclose($urlp);
echo 'Error transfering file using fopen and cURL !!';
return false;
}
$getID3 = new getID3;
$filename=$file;
$ThisFileInfo = $getID3->analyze($filename);
getid3_lib::CopyTagsToComments($ThisFileInfo);
unlink($file);
return $ThisFileInfo;
}
?>
This function downloads 64KB from a URL of an .mp3 file, then returns the array with the metadata by using getID3 function (which works on local .mp3 files only) and then deletes the 64KB's previously downloaded.
Problem with this function is that it is way too slow from its nature (downloads 64KB's per .mp3, imagine 1000 mp3 files.)
To make my question clear : I need a fast standalone function that reads metadata of a remote URL .mp3 file.
This function downloads 64KB from a URL of an .mp3 file, then returns the array with the metadata by using getID3 function (which works on local .mp3 files only) and then deletes the 64KB's previously downloaded. Problem with this function is that it is way too slow from its nature (downloads 64KB's per .mp3, imagine 1000 mp3 files.)
Yeah, well what do you propose? How do you expect to get data if you don't get data? There is no way to have a generic remote HTTP server send you that ID3 data. Really, there is no magic. Think about it.
What you're doing now is already pretty solid, except that it doesn't handle all versions of ID3 and won't work for files with more than 64KB of ID3 tags. What I would do to improve it to is to use multi-cURL.
There are several PHP classes available that make this easier:
https://github.com/jmathai/php-multi-curl
$mc = EpiCurl::getInstance();
$results[] = $mc->addUrl(/* Your stream URL here /*); // Run this in a loop, 10 at a time or so
foreach ($results as $result) {
// Do something with the data.
}
1 - I have configure google picker and it is working fine and I select the file from picker and get the file id.
2 - After refresh token etc all process I get the file metadata and get the file export link
$downloadExpLink = $file->getExportLinks();
$downloadUrl = $downloadExpLink['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
3 - After that I use this
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200)
{
$content = $httpRequest->getResponseBody();
print_r($content);
} else {
// An error occurred.
return null;
}
and get this response
[responseBody:protected] => PK��DdocProps/app.xml���
�0D���k�I[ѫ��m
��!����A={���}�
2G�Z�g�V��Bľ֧�n�Ҋ�ap!����fb�d����k}Ikc�_`t<+�(�NJ̽�����#��EU-
�0#���P����........
4 - I use some cURL functions to get file from google drive and save it to server. IN server directory a file created but cropped. I use this code
$downloadExpLink = $file->getExportLinks();
$downloadUrl = $downloadExpLink['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
//$downloadUrl value is
/*https://docs.google.com/feeds/download/documents/export/Export?id=1CEt1ya5kKLtgK************IJjDEY5BdfaGI&exportFormat=docx*/
When I put this url into browser it will download file successfully but when I use this url to fetch file with cURL or any php code and try to save it on server it saves corrupted file.
$ch = curl_init();
$source = $downloadUrl;
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "test/afile5.docx";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
It result a corrupted file stored on server but whe I use this code to get any file other then google drive I download it successfully on server.
Can any one please help that how to download file from $downloadUrl to my server using php ?
I'm trying to run PHP script (from a Linux server) that will download a file through direct download link and save it on my server.
here is the script I'm using:
<?php
$url = 'http://download.maxmind.com/app/geoip_download?edition_id=108&date=20131015&suffix=zip&license_key=XXXXXXXXXXX';
$path = '/apps/test/';
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
for some reason it doesn't work for me, any suggestions ?
You need to verify that the ports are open on your firewall and use the below command:
(this will also download the file in the original format)
shell_exec("wget -P /apps/birst/php_test_scripts/ --content-disposition "."'"."https://download.maxmind.com/app/geoip_download?edition_id=108&suffix=zip&license_key=XXXXXXXX"."'");
Why dont you just use :
shell_exec("wget -P /target/directory/ http://download.link.com/download.zip");
Try this
$url = 'http://download.maxmind.com/app/geoip_download?edition_id=108&date=20131015&suffix=zip&license_key=XXXXXXXXXXX';
$path = '/apps/test/';
$filepath = $path .'file.zip';
$data = file_get_contents($url);
file_put_contents($filepath, $data);
I am using following codes to upload remote files to my server. It works great where direct download link is given but recently I have noticed that few websites are giving mysql links as download link and when we click on that link the files start downloading to my pc. But even in html source of that page it does not show the direct link.
Here is my code:
<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);
}
?>
It works great for all links where the download link is direct for example if I will give
http://priceinindia.org/muzicpc/48.php?id=415508 link it will upload the music file but the file name will be 48.php?id=415508 but the actual mp3 file is stored at
http://lq.mzc.in/data48-2/37202/Appy_Budday_(Videshi)-Santokh_Singh(www.Mzc.in).mp3
So if I can get the actual destination url the name will be Appy_Budday_(Videshi)-Santokh_Singh(www.Mzc.in).mp3
So I want to get the actual download url.
You should use Curl library for this. http://php.net/manual/en/book.curl.php
An example of how to use curl is provided in tha manual (on that link) befo before you close the connections, call curl_getinfo (http://php.net/manual/en/function.curl-getinfo.php) and specifically get CURLINFO_EFFECTIVE_URL which is what you want.
<?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);
?>
(You can also use curl to write directly to a file - use the CURLOPT_FILE options. Also in the manual)
The problem is the original URL is redirecting. You want to catch the URL it is being redirected to, try using the headers and then get the basename($redirect_url) as your file name.
+1 for Robbie using CURL.
If you run (from command line)
[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
You can see the location header here is the new url.
in php try something like
$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
You want to find the location part of the header. not sure the setting im sure though.
EDIT 3..or 4?
Yeah right, I see whats happening. You actually want to follow the location url then echo the effective url without downloading file. try.
$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
When I run this my output is
[username#localhost ~]$ php test.php
http://lq.mzc.in/data48-2/37202/Appy_Budday_(Videshi)-Santokh_Singh(www.Mzc.in).mp3
I need a PHP Web Proxy that read html, show to the user and rewrite all the links for when the user click in the next link the proxy will handle the request again, just like this code, but with additionaly sould make the rewrite of all the links.
<?php
// Set your return content type
header('Content-type: text/html');
// Website url to open
$daurl = 'http://www.yahoo.com';
// Get that website's content
$handle = fopen($daurl, "r");
// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
I hope I have explained well. This question is for not reinventing the wheel.
Another additional question. This kind of proxies will deal with contents like Flash?
For an open source solution, check out PHProxy. I've used it in the past and it seemed to work quite well from what I can remember.
It will sort of work, you need to rewrite any relative path to apsolute, and I think cookies won't work in this case. Use cURL for this operations...
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
return curl_exec($ch);
curl_close ($ch);
}
$url = "http://www.yahoo.com";
echo curl($url);