Get file contents without file_get_contents - php

I'm not allowed to use file_get_contents. Originally I got the file contents by simply doing this:
$filepath = $_FILES['resume-attachment']['tmp_name'];
$filecontent = file_get_contents($filepath);
$encodedFile = base64_encode($filecontent);
Unfortunately, it's not allowed.
$filepath = $_FILES['resume-attachment']['tmp_name'];
$filename = $_FILES['resume-attachment']['name'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $filepath);
$filecontent = curl_exec($ch);
curl_close($ch);
$encodedFile = base64_encode($filecontent);
The code above is my attempt at using cURL. I get the filename uploaded, so I get some reaction, but the uploaded file is 0.0 bytes of size... which is not correct. I would think that perhaps the issue could be that I shouldn't treat $filepath as a URL, but what would the alternative be? I should also mention that I'm not trying to post it from this code. I simply want to get the file contents, and then encode it. It's part of an XML string later on.

Related

Download remote PDF

I'm trying to load and save a remote PDF to my server for a project, but the link has no file extension. It's a kind of secured link.
https://www.enablelogistics.com.au/BECPRD/SSOAuth.aspx?SESSION_KEY=F86A56B3-D12C-4E70-AE71-A8A422B3EA4E&LINK_PAGE=ITINERARYENC&TRANS_ID=A25D191B-B098-4F45-9217-FB6D2B70F803
When I open the link in the browser I can download the PDF file, but saving it with my script has no success.
Is there a way to save the PDF on my server with a script?
I tried following code without success:
$url ="https://www.enablelogistics.com.au/BECPRD/SSOAuth.aspx?SESSION_KEY=F86A56B3-D12C-4E70-AE71-A8A422B3EA4E&LINK_PAGE=ITINERARYENC&TRANS_ID=A25D191B-B098-4F45-9217-FB6D2B70F803";
getFileContents($url);
function getFileContents($url)
{
// Workaround: Save temp file
$img = tempnam(sys_get_temp_dir(), 'pdf-');
$img .= '.' . pathinfo($url, PATHINFO_EXTENSION);
$fp = fopen($img, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);
return $result ? $img : false;
}
I found the script here : Downloading a large file using curl
To download a file (binary or not) you can use file_get_contents().
file_get_contents return the file content into a string.
//Download PDF content
$pdfContent = file_get_contents("https://www.enablelogistics.com.au/BECPRD/SSOAuth.aspx?SESSION_KEY=XXXXXXX-DDDD-4444-AAAA-XXXXXXX&LINK_PAGE=ITINERARYENC&TRANS_ID=AAAAAAAA-3333-5555-6666-222222222");
$fileName = "myPDF.pdf";
$fp = fopen($fileName, 'w+');
//Write content into the file
fwrite($fp, $pdfContent);
fclose($fp);
You can if necessary use options in file_get_contents to specify GET or POST method, Basic Authentication and more.
Thanks for your reply, but your code doesn't saves the PDF im looking for.
It safes a PDF with HTML content :
WWW.ENABLELOGISTICS Enable Logistics v95.4248
Welcome to Enable
Logistics Please enter your username and password to sign in.
Forgot Password?©2016 Bright People Technologies Pty Ltd
I have no clue how to dowload the pdf to my server.
Clicking the link only let's me download local.

readfile vulnerability how to avoid

I heard that the function readfile is vulnerable as a php function, so I disabled it, and I have a script to download files, which uses this function:
$url = strip_tags($_GET['path']);
$fileName = strip_tags($_GET['file']);
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$fileName.";");
header ("Content-Length: ".filesize($url.$fileName));
readfile($url.$fileName);
exit;
If it is vulnerable, is there a way to avoid it or replace it with another function, I tried cURL, but the download failed, I got from this link
Using cURL:
<?php
set_time_limit(0);
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');//This is the file where we save the information
$ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch); // get curl response
curl_close($ch);
fclose($fp);
?>
Thanks in advance
readfile isn't vulnerable per se. A possible attack vector is only given, when you pass un-sanitized data as parameter to it.
I mean $url. Your example doesn't show where URL comes from.
Let's use the worst case and assume $url comes from $_POST, e.g.
$url = $_POST['url']; and combine it with a nice Path Traversal attack (https://www.owasp.org/index.php/Path_Traversal).
You could limit the file access to the current dir (__DIR__).
Or use realpath() and exclude/restrict what readfile can do.
Referencing: How to avoid path traversal attacks
Ok, i've tested you cURL example. It works!
<?php
$url = 'http://www.thetimes.co.uk/tto/news/rss';
set_time_limit(0);
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');//This is the file where we save the information
$ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch); // get curl response
curl_close($ch);
fclose($fp);
This downloads the content of the news/rss feed URL and saves it to localfile.tmp.

PHP copy() doesn't work for random URLS which redirect to files

trying to copy() .MP3 file from remote url but it always fails.
$link = str_replace(' ','%20','http://mp3hungama.com/music/download.php?song_id=80522');
if (!copy($link,'/home2/muser/tmp/newname.mp3')) {
echo 'copy failed !';
}
$link url redirects to http://mp3hungama.com/music/audio//Indian%20Movies/Indian%20Movies%20Hindi%20Mp3%20Songs/Singh%20Is%20Bling%20(2015)/songs/Cinema%20Dekhe%20Mamma%20#%20Mp3HunGama.Com.mp3
same code works for others random urls like www.example.com/download.php?id=2332. what's the specifically problem here or any other way to do this job ?
I've tested your code and I also couldn't download the file, then, I've used curl an it work as expected:
$local_file = "/home2/muser/tmp/newname.mp3";//This is the file where we save the information
$remote_file = "http://mp3hungama.com/music/download.php?song_id=80522"; //Here is the file we are downloading
$ch = curl_init();
$fp = fopen ($local_file, 'w+');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_exec($ch);
curl_close($ch);
fclose($fp);
NOTE:
Make sure /home2/muser/tmp/ has write permissions.
TIP:
In the future, if you need to encode/decode a url, use urlencode or urldecode instead of str_replace
This link
already redirects to second link. So it's working already.

Collecting file with PHP CURL after validating request downloads an empty file

I am doing a system where one of my sites goes to the other to get documents.
On the first site I am using Curl to make a request to get the file wanted:
I am using the solution from Download file from URL using CURL :
function collect_file($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, "http://example.com");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
return($result);
}
function write_to_file($text,$new_filename){
$fp = fopen($new_filename, 'w');
fwrite($fp, $text);
fclose($fp);
}
$curlUrl = 'http://site2.com/file-depository/14R4NP8JkoIHwIyjnexSUmyJibdpHs5ZpFs3NLFCxcs54kNhHj';
$new_file_name = "testfile-new.png";
$temp_file_contents = collect_file($curlUrl);
write_to_file($temp_file_contents,$new_file_name);
I am testing downloading an image. If i use a direct URL into $curlUrl , for instance http://site2.com/file-depository/image.png it works perfect.
What I am doing is that the URL http://site2.com/file-depository/14R4NP8JkoIHwIyjnexSUmyJibdpHs5ZpFs3NLFCxcs54kNhHj is then parsed and checked against a database to match the document requested, once there is a document matched I need to provide this document to the Curl response.
I have tried many ways to read the file but everytime i am getting a file on the other end but it is only 1kb in size (45 expected) and when trying to open it i get an error unkown file type etc.
On the second site, once the URL is validated here is what I have:
$file = readfile('some-image.png');
echo $file;
I am guessing there is part of the information which belongs to the file missing but can't figure it out, any pointers appreciated!
I have replaced
function write_to_file($text,$new_filename){
$fp = fopen($new_filename, 'w');
fwrite($fp, $text);
fclose($fp);
}
by file_put_contents($new_file_name,trim($temp_file_contents));
Please note the trim(), the issue was that I was apparently collecting some empty space in front of the file content.

How can get an image from a 301 redirect download link in PHP?

I'm trying to download this image with PHP to edit it with GD. I found many solutions for image links, but this one is a download link.
Edit:
$curl = curl_init("http://minecraft.net/skin/Notch.png");
$bin = curl_exec($curl);
curl_close($curl);
$img = #imagecreatefromstring($bin);
This is my current code. It displays "301 Moved Permanently". Are there CURLOPTs I have to set?
$curl = curl_init("http://minecraft.net/skin/Notch.png");
// Moved? Fear not, we'll chase it!
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Because you want the result as a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$bin = curl_exec($curl);
curl_close($curl);
$img = #imagecreatefromstring($bin);
Here is an option to directly save the image to a file (instead of using imagecreatefromstring):
<?php
$fileName = '/some/local/path/image.jpg';
$fileUrl = 'http://remote.server/download/link';
$ch = curl_init($fileUrl); // set the url to open and download
$fp = fopen($fileName, 'wb'); // open the local file pointer to save downloaded image
curl_setopt($ch, CURLOPT_FILE, $fp); // tell curl to save to the file pointer
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // tell curl to follow 30x redirects
curl_exec($ch); // fetch the image and save it with curl
curl_close($ch); // close curl
fclose($fp); // close the local file pointer
fopen - depends on your php settings if url fopen is allowed.
or curl
see the fine php manual.

Categories