Saving PDF Curl response on server directory - php

I'm getting and downloading a .pdf from an URL. It's downloading directly on my PC through the Curl request.
How to save this in a directory at the server where the page is running?
I'm able to use PHP and JS, i've tried many things even combine the two languages but it seems only works the curl request, and it doesnt save that in the directory
<body>
<button id="boton">CLICK ME</button>
<?php
$name = 'file';
$file_downloaded = curl_init();
curl_setopt($file_downloaded, CURLOPT_URL, 'The url');
//curl_setopt($file_downloaded, CURLOPT_HEADER, true);
curl_setopt($file_downloaded, CURLOPT_RETURNTRANSFER, true);
curl_setopt($file_downloaded, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($file_downloaded, CURLOPT_AUTOREFERER, true);
$file_downloaded = curl_exec($file_downloaded);
if(!curl_errno($file_downloaded))
{
header('Content-type:application/pdf');
header('Content-Disposition: attachment; filename ="'.$nuevo_nombre.'.pdf"');
echo($file_downloaded);
exit();
}else
{
echo(curl_error($file_downloaded));
}
?>
<script>
$("#boton").click(function () {
var archivo = '<?php echo($file_downlaoded) ?>';
var data = new FormData();
data.append("data" , archivo);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/my/directory', true );
xhr.send(data);
});
</script>
</body>
It's downloading on my local PC, and it's expected to download on the path /my/directory of the server.
EDIT
<?php
$nuevo_nombre = 'remito'; //asignamos nuevo nombre
$archivo_descarga = curl_init(); //inicializamos el curl
curl_setopt($archivo_descarga, CURLOPT_URL, 'URL');
//curl_setopt($archivo_descarga, CURLOPT_HEADER, true);
curl_setopt($archivo_descarga, CURLOPT_RETURNTRANSFER, true);
curl_setopt($archivo_descarga, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($archivo_descarga, CURLOPT_AUTOREFERER, true);
$resultado_descarga = curl_exec($archivo_descarga);
file_put_contents('/path/to/file.pdf', $resultado_descarga);
?>

That was solved with the file_put_contents() function, and there was also an issue with permissions on the directory folder.
function Download($endpoint) {
$URL = 'URL';
$fileName= 'name1';
$path = 'testDirectory/'.$filename.'.pdf';
$file_download= curl_init();
curl_setopt($file__download, CURLOPT_URL, $URL.$endpoint);
curl_setopt($file__download, CURLOPT_RETURNTRANSFER, true);
curl_setopt($file__download, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($file__download, CURLOPT_AUTOREFERER, true);
$result= curl_exec($file__download);
file_put_contents($path, $result);
}

Related

Can't upload file from php to nodejs

I have two parts of my project. The first one is PHP part, that takes file and send it to the second part. Here is my code:
$file = fopen('file.wav', 'r');
$size = filesize('file.wav');
$ex_id = getExternalId();
$apiurl = 'http://url.to.the.second.part/?id='.$ex_id.'&oneway=true';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_INFILE, $file);
curl_setopt($ch, CURLOPT_INFILESIZE, $size);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
fclose($file);
//apply logic to $result
exit(0);
The second part is API part on nodejs. I can handle requests, and get id parameter from query, but req.body is undefined:
const express = require('express');
const app = express();
app.put('api.url', (req, res) => {
const externalId = req.query.id;
//do some stuff here...
//and here i'm expecting uploaded file
//but i got nothing here
const file = req.body;
//other logic here...
res.status(200).send(result);
}
What am i doing wrong?
You are opening the file using fopen fun which returns file pointer resource. You need to get the contents of the file and for that you can use file_get_contents function and then pass the file contents in the request parameter.
$file = file_get_contents('file.wav');

Node js Faye Client not working properly with HTTPS

I tried to integrate node js with my application, I have just test the http server It works well, but when I use https server as following with my index.php to subscribe the message, This does not work.
Start a server
var https = require('https'),
faye = require('faye');
var fs = require('fs');
var options = {
key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};
var server = https.createServer(options),
bayeux = new faye.NodeAdapter({mount: '/'});
bayeux.attach(server);
server.listen(1337);
Create a client
<script src="faye-browser-min.js"></script>
<script>
var client = new Faye.Client('https://localhost:1337/');
client.subscribe('/messages/*', function(message) {
alert('Got a message:');
});
</script>
Send messages
I used Faye client to push message in test.php .
$adapter = new \Nc\FayeClient\Adapter\CurlAdapter();
$client = new \Nc\FayeClient\Client($adapter, 'https://localhost:1337/');
$client->send("/messages/test", array("name" => "foo"), array("token" => "456454sdqd"));
Thank you,
Please tell me how to check is there any error on server side.
I fixed issue my self, The issue was not in server side. It was in php Faye Client side. That Php Client works fine for HTTP server, but I need to use it for HTTPS server. I have done following changes then It works fine.
/vendor/nc/faye-client/src/Nc/FayeClient/Adapter/CurlAdapter.php
public function postJSON($url, $body)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($body),
));
curl_exec($curl);
curl_close($curl);
}

I am getting "Requested URL not found..." error with cURL. Any ideas?

So I am posting data to another system and am wanting to retrieve the "redirection url" that the system responds back with and redirect the user after 2 seconds but I get:
The requested URL /somescript.aspx was not found on this server.
Any idea what I am doing wrong? Or is there something else at play?
<?php
$strURL = 'http://someplace.com/somescript.aspx';
$fields_string = implode('&', (array)$_SESSION['apply']);
$resURL = curl_init();
curl_setopt($resURL, CURLOPT_URL, $strURL);
curl_setopt($resURL, CURLOPT_POST, true);
curl_setopt($resURL, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($resURL, CURLOPT_HEADER, TRUE);
curl_setopt($resURL, CURLOPT_FOLLOWLOCATION, FALSE);
$response = curl_exec($resURL);
$RedirectLocation = curl_getinfo($resURL, CURLINFO_EFFECTIVE_URL);
unset($_SESSION['apply']); ?>
<script type="text/javascript">
$(function() {
setTimeout(function() {
window.location.href = "<?php echo $RedirectLocation; ?>";
}, 2000)
});
</script>
So you're looking to retrieve the 301/302 redirect target, but not actually follow it? Set CURLOPT_RETURNTRANSFER to true, and parse the Location: header out of the response.
To see what I mean change your code to this:
curl_setopt($resURL,CURLOPT_RETURNTRANSFER);
$response = curl_exec($resURL);
echo $repsonse
IIRC CURLINFO_EFFECTIVE_URL won't change if you don't set curl to follow redirects.

Facebook profile image and download it to my web directory

Take a Facebook profile image and download it to my directory "www.site.com/images"..
<?php $url = "https://graph.facebook.com/$id/picture?width=350&height=500&redirect=false"; ?>
The variable "$id" is taken from a textfield, I've tried getting around the "redirect" that facebook places on their images, so to get the "real url" I've decided to extract it from a JSON. In browser I receive this:
"url": "https://fbcdn-profile-a.akamaihd.net/hprofil[...]",
"width": 299,
"height": 426,
"is_silhouette": false
All I need is the "real url" to be extracted and saved unto my website's directory.
$.getJSON, seems to be the easiest way to separate the information.
Summary
Extracting/Separator script for JSON in PHP or JAVASCRIPT
Or Save "Image" to "Directory".
My solutions:
PHP with curl
<?php
$ch = curl_init("http://graph.facebook.com/$id/picture?width=350&height=500&redirect=false");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // Mean 5 seconds
$content = curl_exec($ch);
$data = json_decode($content, true);
curl_close($ch);
var_dump($data["data"]["url"]);
PHP with file_get_contents()
<?php
$content = file_get_contents("http://graph.facebook.com/$id/picture?width=350&height=500&redirect=false");
$data = json_decode($content, true);
var_dump($data["data"]["url"]);
javascript with jQuery
var url = "http://graph.facebook.com/ID/picture?width=350&height=500&redirect=false";
$.get(url,function(resp) {
alert(resp.data.url);
});
EDIT
Have you tried to remove "&redirect=false"
"https://graph.facebook.com/$id/picture?width=350&height=500"
redirect to
"https://fbcdn-profile-a.akamaihd.net/hprofil[...]"
So you can do:
<?php
$url = "https://graph.facebook.com/$id/picture?width=350&height=500";
$data = file_get_contents($url);
$fp = fopen("img$id.jpg","wb");
if (!$fp) exit;
fwrite($fp, $data);
fclose($fp);
Learn more about picture graph
I used this code when storing images from fb.
$dir = "your_directory";
$img = md5(time()).'.jpg';
$url = "some_value";
$ch = curl_init($url);
$fp = fopen($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$img, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);

IMGUR file upload via PHP and cURL

I'm trying to upload an image to IMGUR via PHP.
This is the code:
<?
$filename = "image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'mykey' => IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
?>
This is the error message I receive:
Warning: fopen(image.jpg) failed to open stream: No such file or directory
I don't understand the part: $filename = "image.jpg";
Where does the filename come from since it's a base64 generated string?
Thanks,
Bob
That warning is because fopen is trying to read in the file image.jpg from the directory from which your script is running.
A good example on how to transfer a file through curl can be seen here
Send file via cURL from form POST in PHP
Where they have $localFile = $_FILES[$fileKey]['tmp_name']; you would put $localFile = '/path/to/image.jpg'; As well as change the server info and add in any other variables you may need to pass to imgur.
Change line 1 from:
$filename = "image.jpg";
To:
$filename = $_FILES['uploaded_file']['tmp_name'];
Then, to post... I recommend a form similar to this:
<form enctype="multipart/form-data" method="post" action="upload.php" target="my_iframe">
Choose your file here:
<input name="uploaded_file" type="file"/>
<input type="submit" value="Upload It"/>
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<script language="JavaScript">
<!--
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
}
document.getElementById(id).height= (newheight) + "px";
document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>
<IFRAME name="my_iframe" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>
If you put all your php into upload.php and then have that form on a page in the same directory, it's pretty close to being functional... Except you don't yet have an API_KEY in your source.
You can get an API KEY here: https://imgur.com/register/api_anon
In the end your php should look like this:
<?
if( isset($_FILES['uploaded_file']) )
{
$IMGUR_API_KEY = 'u432ewriuq3oirefuie'; //put your api key here
$filename = $_FILES['uploaded_file']['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
//$data is file data
$pvars = array('image' => base64_encode($data), 'key' => $IMGUR_API_KEY);
#$pvars = array('key' => $IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
#curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/gallery.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
$xmlsimple = new SimpleXMLElement($xml);
echo '<img height="180" src="';
echo $xmlsimple->links->original;
echo '">';
curl_close ($curl);
}
?>

Categories