php fopen fread images - php

I am trying to tcp an image from my linux php ec2 instance to another server.
when i echo out the contents of fopen and fread i can see the image is processed but only halfway
Does anyonew know what is causing this please, thank you.
$imageURL = 'http://ec2-**-***-**-**.compute-1.amazonaws.com/New_Era_For_NASA_2.jpg';
$ch = curl_init($imageURL);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
//echo $data;
curl_close($ch);
if ($data === false) {
die('cURL failed');
}
if ( preg_match('/Content-length: (\d+)/', $data, $matches) || preg_match('/Content-Length: (\d+)/', $data, $matches) ) {
$size = (int)$matches[1];
}
$fileHandle = fopen($imageURL, 'rb'); //r or rb
$fileData = fread( $fileHandle, $size );
//echo $fileData;
fclose( $fileHandle );
$data = $fileData;
header('Content-type: image/jpeg');
echo $data;

Why fetch it twice? Curl could do the job in one step. i.e.
$imageURL = 'http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Tibia_insulaechorab_transparent.png/320px-Tibia_insulaechorab_transparent.png';
$ch = curl_init($imageURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
die('cURL failed');
}
header('Content-Type: image/png');
header('Content-Length: ' . curl_getinfo( $ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD ) );
echo $data;

$imageURL = 'http://ec2-**-***-**-**.compute-1.amazonaws.com/New_Era_For_NASA_2.jpg';
$ch = curl_init($imageURL);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
echo $data;
curl_close($ch);
Would be enough
file_get_content( $imageURL );
Would work to0 but be aware of memory_limit, fread might be a better option.

Related

fopen and CURLOPT_FAILONERROR

I'm new to this. How to NOT write to the file if CURLOPT_FAILONERROR is triggered?
$token = "123";
$url = "foo.com";
$fp = fopen("file.txt", "wb");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
curl_close($ch);
fclose($fp);
I'm not sure that is possible in that way.
I download the origin file first in /tmp and if there isn't error then I move it to whatever you want.
$tmpFp = null;
$token = '123';
$url = 'foo.com';
$source = '';
$dest = 'file.txt';
$meta = null;
try {
// creating tmp file
$tmpFp = tmpfile();
$meta = stream_get_meta_data($tmpFp);
// getting its name
$source = $meta['uri'];
if($tmpFp === false){
throw new Exception('Could not open Temporal File');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FILE, $tmpFp);
curl_exec($ch);
// download file
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($tmpFp);
if($statusCode != 200) {
// if the file don't exist or some other web error
throw new Exception('Status Code: '. $statusCode);
}
// copy to dest
if (!copy($source, $des)) {
throw new Exception('failed to copy file');
}
echo('Download success!');
} catch(Exception $e) {
echo($e->getMessage());
}
last note, make sure that you have permissions
regards

Get file by curl_setopt() and write it as a .PNG

I need to create a .PNG file from a file that I am dowloading by curl_setopt().
The .PNG will be created, only it can't be read anymore.
So my thougts are, the $rawdata does not have the right content.
// Function to download a file (needed in one of the programming missions)
function htsGetFile($url, $filename) {
$cookiefile = "cookie.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0');
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); // Cookiejar on creation, cookiefile on use
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // We need tot get the data back.
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //Will not check the ssl sertification.
$rawdata = curl_exec($ch);
if(file_exists($filename)){
unlink($filename);
}
$fp = fopen($filename, 'wb');
fwrite($fp, $rawdata);
fclose($fp);
if(curl_errno($ch)) {
return false;
} else {
return $rawdata;
}
curl_close ($ch);
}
$username = "*******";
$password = "*******";
$url = "https://www.domain/path/";
$file = "download.png";
if (htsLogin($username, $password))
if (htsGetHTML($url) !== false)
if (htsGetFile($url, $file) !== false)
$img = htsGetFile($url, $file);
else
echo 'Getting file went wrong.';
else
echo 'Getting page went wrong.';
else
echo 'Can\'t login.';
Try file_put_contents($file_name, $rawdata) instead of
$fp = fopen($filename, 'wb');
fwrite($fp, $rawdata);
fclose($fp);
or base64_encode($rawdata) in both variants

How to download an mp3 file from remote url?

I am redirecting my website to a url where only an mp3 file is streaming and I want that file to be downloaded to local computer.
how can i do that?
I have already searched google and stacksoverflow but the solutions didn't worked for me
I couldn't find solution for my specific problem.
Use CURL to download, then you can use file_get_contents to save file on server, or you can use some headers to force download the file.
$ch = curl_init('http://url-to-file.com/audio.mp3');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
$output = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status == 200) {
file_put_contents(dirname(__FILE__) . '/audio.mp3', $output);
}
Download to browser:
$ch = curl_init('http://url-to-file.com/audio.mp3');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
$output = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status == 200) {
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=audio.mp3");
echo $output;
die();
}
curl only works for small files.
For larger files you can download mp3, mp4, zip by doing the following:
file_put_contents(dirname(__FILE__) . '/recordings/audio.mp3', fopen('http://url-to-file.com/audio.mp3', 'r'))
There are two ways to do it.
First way is use function readfile - it will be faster, then all other methods.
function curl_get_file_size( $url ) {
$result = -1;
$curl = curl_init( $url );
curl_setopt( $curl, CURLOPT_NOBODY, true );curl_setopt( $curl, CURLOPT_HEADER, true );curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
$data = curl_exec( $curl );
curl_close( $curl );
if( $data ) {
$content_length = "unknown";
$status = "unknown";
if( preg_match( "/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches ) ) $status = (int)$matches[1];
if( preg_match( "/Content-Length: (\d+)/", $data, $matches ) ) $content_length = (int)$matches[1];
if( $status == 200 || ($status > 300 && $status <= 308) )
$result = $content_length;
}
return $result;
}
function run() {
global $url,$title;
header("Content-type: audio/mpeg");
header("Content-Disposition: attachment; filename=$title.mp3");
header("Content-length: " . curl_get_file_size($url));
header("accept-ranges: bytes");
readfile($url);
}
run();
Second way is when you download full file and then return it
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
$output = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status == 200) {
header("Content-type: audio/mpeg");
header("Content-Disposition: attachment; filename=$title.mp3");
header("Content-length: " . strlen($output));
header("accept-ranges: bytes");
echo $output;
die();
}

Curl progress function in PHP

I am wondering why this download() function is not working.
function download($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$html = curl_exec($ch);
curl_close($ch);
function progress($resource, $download_size, $downloaded, $upload_size, $uploaded)
{
if ($download_size > 0)
$progress = round($downloaded / $download_size * 100);
$progress = array('progress' => $progress);
$path = "temp/";
$destination = $path."11.json";
$file = fopen($destination, "w+");
fwrite($file, json_encode($progress, JSON_UNESCAPED_UNICODE));
fclose($file);
}
}
download("http://stackoverflow.com");
But when I am using without function like
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com");
or when I am using the function twice like
download("http://stackoverflow.com");
download("http://stackoverflow.com");
it works. Otherwise it doesn't create any json file.
Declare your function progress outside of download:
function download($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$html = curl_exec($ch);
curl_close($ch);
}
function progress($resource, $download_size, $downloaded, $upload_size, $uploaded)
{
if ($download_size > 0)
$progress = round($downloaded / $download_size * 100);
$progress = array('progress' => $progress);
$path = "temp/";
$destination = $path."11.json";
$file = fopen($destination, "w+");
fwrite($file, json_encode($progress, JSON_UNESCAPED_UNICODE));
fclose($file);
}

how to save remote image to a file using php curl?

i am trying to save a remote image to a file using php curl but the file never get saved! could any one help me how to troublshoot this problem ? the image file never get created and but echo $returned_content has the data!
<?
$returned_content = get_data('http://somesite.com/43534545345dfsdfdsfdsfds.jpg');
echo $returned_content;
$fp = fopen('43534545345dfsdfdsfdsfds.jpg', 'w');
fwrite($fp, $returned_content);
fclose($fp);
/* gets the data from a URL */
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
<?php
$ch = curl_init('http://www.example/2012/09/flower.jpg');
$fp = fopen('/localProject/imagesFolder/newname.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
Try this
<?php
function getImagen($url, $rename, $ch)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$fp = fopen("$rename.jpg",'w');
fwrite($fp, $rawdata);
fclose($fp);
}
$ch = curl_init();
$image ="http://sampleurl.com/imagen.jpg";
getImagen ($image, "imagen", $ch);
?>
Works 100% :)

Categories