curl_exec succeeds but the output file is empty - php

I wrote the PHP function below to download files and it works as expected.
However, when I try to download this file:
$url = 'http://javadl.sun.com/webapps/download/GetFile/1.7.0_02-b13/windows-i586/jre-7u2-windows-i586-iftw.exe';
download($url);
... no content is written to the file. And I can't figure out why. The file is created, the call to curl_exec returns true, but the output file remains empty. The file can be downloaded in the browser just fine and the function successfully downloads other files. It's just this file (host?) that I'm having problem with.
Any help is appreciated.
function download($url)
{
$outdir = 'C:/web/www/download/';
// open file for writing in binary mode
if (!file_exists($outdir)) {
if (!mkdir($outdir)) {
echo "Could not create download directory: $outdir.\n";
return false;
}
}
$outfile = $outdir . basename($url);
$fp = fopen($outfile, 'wb');
if ($fp == false) {
echo "Could not open file: $outfile.\n";
return false;
}
// create a new cURL resource
$ch = curl_init();
// The URL to fetch
curl_setopt($ch, CURLOPT_URL, $url);
// The file that the transfer should be written to
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, false);
$header = array(
'Connection: keep-alive',
'User-Agent: Mozilla/5.0',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// downloading...
$downloaded = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
fclose($fp);
if (!$downloaded) {
echo "Download failed: $error\n";
return false;
} else {
echo "File successfully downloaded\n";
return $outfile;
}
}

That url redirects to another. You need to set CURLOPT_FOLLOWLOCATION to 1 for that to work.

Try Adding;
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
//then after curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
Check some sample: http://www.php.net/manual/en/function.curl-exec.php#84774

Related

Sending a chunked file with curl and receiving

I have created two file php. The first one for send a file through curl utilizing the chunking method. And a second one for receiving the file.
What I need is to send a chunked file with curl and receive it. However, I am not really sure that the code in this two pages does what I need.
This is the code in the first page (send.php).
<?php
function curlPutThrottle($ch, $fh, $length = false)
{
if (!$length)
{
$length = 4096;
}
return fread($fh, $length);
}
$target_url = "http://localhost/save.php?filename=test2.zip";
$cFile = fopen ('./test.zip', "r");
$size = filesize('./test.zip');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_PUT, true);
// Let curl know that we are sending an entity body
curl_setopt($ch, CURLOPT_UPLOAD, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
// Let curl know that we are using a chunked transfer encoding
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Transfer-Encoding: chunked'));
curl_setopt($ch, CURLOPT_READFUNCTION, 'curlPutThrottle');
curl_setopt($ch, CURLOPT_INFILE, $cFile);
curl_setopt($ch, CURLOPT_INFILESIZE, $size);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
?>
And this is the code in save.php.
<?php
function file_get_contents_chunked($filename, $chunk_size, $callback) {
$handle = fopen($filename, 'r');
if (feof($handle)) {
return 0;
} else {
while (!feof($handle)) {
call_user_func_array($callback, array(fread($handle, $chunk_size)));
}
fclose($handle);
return 1;
}
}
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$count = 0;
$file = fopen('./'.$_GET['filename'], 'wb+');
$res = file_get_contents_chunked('php://input', 8192, function ($chunk) use (&$file) {
global $count;
fwrite($file, $chunk);
$count++;
});
if (!$res)
echo "file not received";
else
echo "file received ".$count;
} else {
echo 'Not a PUT request!!!';
}
?>
Is this code in these two pages correct for sending a chunked file through curl? Or is it incomplete in some way?
And, if is it incomplete what I need to send a chunked file correctly using curl?
Thanks at all for your help in this.

how to parse a csv from an auto download url using php

I have a product feed which automatically downloads as a csv when I put the url in a browser.
I want to write a php script to get the data from the url,parse it,get what data I require and create a new csv.
The problem i am facing is when I use curl or file_get_contents() I get an empty array.
Update:
the new CSV file is empty
$feed = 'https:/www.url/feeds/feed.csv';
$path = "./newfile.csv";
function download_page($path,$feed){
$fp = fopen ($path, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$feed);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
$retValue = curl_exec($ch);
curl_close($ch);
fclose($fp);
return $retValue;
}
CURLOPT_FILE changes the output from STDOUT to a file, but then CURLOPT_RETURNTRANSFER tells it not to output anything. Use one or the other:
function download_page($path,$feed){
$ch = curl_init($feed);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
$retValue = curl_exec($ch);
curl_close($ch);
if($retValue === false) {
return false;
} else {
file_put_contents($path, $retValue);
return true;
}
}
$feed = 'https:/www.url/feeds/feed.csv';
$path = "./newfile.csv";
download_page($path,$feed);
Incidentally, this could be done with much less code, though you may have less flexibility to catch 404 errors and whatnot:
function download_page($path,$feed)
{
$result = file_get_contents($feed);
return $result ? file_put_contents($path, $result) : false;
}

PHP Download Facebook User Image Profile Error

help me to fix this problem
I want to download Facebook user image profile using PHP 5.3.27
I use this code, the image is downloaded but size 0 bytes and cannot be open.
first code:
function DownloadImage($url, $dest){
$curl = curl_init($url);
$fp = fopen($dest, 'wb');
curl_setopt($curl, CURLOPT_FILE, $fp);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($fp);
}
try{
$social_id='1234';
DownloadImage('http://graph.facebook.com/'.$social_id.'/picture', '../user_image/normal/'.$social_id.'.jpg');
DownloadImage('http://graph.facebook.com/'.$social_id.'/picture?width=141&height=141', '../user_image/bigger/'.$social_id.'.jpg');
}
catch(Exception $errr){
echo $errr;
}
and this is the second code..
with the same result (0 bytes of size and cannot be open)
$url = 'http://graph.facebook.com/1234/picture';
$img = '../user_image/bigger/1234.jpg';
file_put_contents($img, file_get_contents($url));
As I see
http://graph.facebook.com/1234/picture
do redirect to:
https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash2/t1.0-1/c47.7.85.85/s50x50/417599_10100236041078581_1583446385_a.jpg
Try to add:
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
So your code may looks like:
function DownloadImage($url, $dest){
$curl = curl_init($url);
$fp = fopen($dest, 'wb');
curl_setopt($curl, CURLOPT_FILE, $fp);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_exec($curl);
curl_close($curl);
fclose($fp);
}
try{
$social_id='1234';
DownloadImage('http://graph.facebook.com/'.$social_id.'/picture', '../user_image/normal/'.$social_id.'.jpg');
DownloadImage('http://graph.facebook.com/'.$social_id.'/picture?width=141&height=141', '../user_image/bigger/'.$social_id.'.jpg');
}
catch(Exception $errr){
echo $errr;
}

PHP cURL error The URL was not properly formatted

I am trying to do a simple cURL file upload from one server to another. The problem is I get Error #3 from the cUrl error codes: The URL was not properly formatted.
I have copied the url into my browser and logged onto the ftp site without a problem. I have also verified the proper formatting and searched the web and this site for an answer without any success.
Here's the code:
$ch = curl_init();
$localfile = '/home/httpd/vhosts/homeserver.com/httpdocs/admin.php';
echo $localfile; //This reads back to proper path to the file
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://username:password#199.38.215.1xx/');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0) {
$error = 'File uploaded succesfully.';
} else {
$error = 'Upload error:'.$error_no ;//Error codes explained here http://curl.haxx.se/libcurl/c/libcurl-errors.html';
}
echo $error;
I have also tried this:
curl_setopt($ch, CURLOPT_URL, 'ftp://199.38.215.1xx/');
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
I still get error #3.
Any ideas?
your remote URL needs to contain the path and name of the destination file, as shown in this example
<?php
// FTP upload to a remote site Written by Daniel Stenberg
// original found at http://curl.haxx.se/libcurl/php/examples/ftpupload.html
//
// A simple PHP/CURL FTP upload to a remote site
//
$localfile = "me-and-my-dog.jpg";
$ftpserver = "ftp.mysite.com";
$ftppath = "/path/to";
$ftpuser = "myname";
$ftppass = "mypass";
$remoteurl = "ftp://${ftpuser}:${ftppasswd}#${ftpserver}${ftppath}/${localfile}";
$ch = curl_init();
$fp = fopen($localfile, "rb");
// we upload a JPEG image
curl_setopt($ch, CURLOPT_URL, $remoteurl);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
// set size of the image, which isn't _mandatory_ but helps libcurl to do
// extra error checking on the upload.
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
$error = curl_exec($ch);
// check $error here to see if it did fine or not!
curl_close($ch);
?>

File posting using cURL into a secured folder(https://)

The problem is to upload a txt file into a secured folder(https://www.mydomain.com/myfolder/) using cURL.
I have a relevant ftp details to connect that folder. here is my code, but it does not getting connected properly...
can any one please advise what mistake i did on this code. which returns error_no:7 while uploading file
<?
if (isset($_POST['Submit'])) {
if ($_FILES['upload']['name']!="")
{
$localfile = $_FILES['upload']['tmp_name'];
$newfile = $_FILES['upload']['name'];
$ch = curl_init();
$url = 'ftp://ftp_login:password#ftp.mydomain.com/myfolder/'.$newfile;
$fp = fopen ($localfile, "r");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_FTPASCII, 1);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $newfile);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
echo curl_error($ch);
echo $error_no = curl_errno($ch);
curl_close($ch);
//echo $result;
if ($error_no == 0)
{
$error = 'File uploaded succesfully.';
}
else
{
$error = 'File upload error.';
}
}
else
{
$error = 'Please select a file.';
}
}
?>
According to this list, error code 7 is
CURLE_COULDNT_CONNECT (7)
Failed to connect() to host or proxy.
Are you sure the server is reachable? Can you try manually?
Also, I'm not really getting what you are doing here. You are establishing a ftp connection but adding POST fields. Also, nothing of this has to do with https. What exactly are you trying to do?
I don't know why you have to use cURL but PHP has its own FTP functions that will make life a bit easier.

Categories