How can I send and receive put query with same script - php

I need to receive image send by PUT method. So I'm wrinting script for testing it. I want to receive and send it with the same script. How can I implement this? The following variant echoes nothing and string about Congratulations that http method was send ok.
<?php
//if they DID upload a file...
var_dump(file_get_contents("php://input"));
if($_FILES['photo']['tmp_name'])
{
echo $_FILES['photo']['error'];
if($_FILES['photo']['error']==0)
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
$message = 'Congratulations!!!!!!!.';
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'url.../1.jpg');
echo'Congratulations! Your file was accepted.';
$image = fopen('url.../1.jpg', "rb");
var_dump($image);
$ch = curl_init();
/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://url.../upload.php");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $image);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($image));
/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($image); //recommended to close the fileshandler after action
curl_close($ch);
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
else
{
echo"WORKS";
}

The most easiest way to send back the image to a browser is via using a URL.
Process the image
Save the image somewhere on your sever
Send the URL back to browser.
Use a tag at the browser and show your image.
<?PHP
$imgFile="";
if($_FILES['photo']['tmp_name'])
{
///Your existing code
$imgFile="http://" . $_SERVER['HTTP_HOST'] .'/Your image url here';
//Ex:\\ http://yourserver.com/images/1.jpg -
//you can take this from your move_upload_file
}
?>
<img src="<?PHP echo $imgFile; ?>" />
Useful links How to receive a file via HTTP PUT with PHP
Even for a restful service u can use json or xml to send the image url back. PUT is not a good idea unless u need to send back image data for some reason. May be u should rethink your logic?

The mistakes was:
strlen($image) strlen if wrong, must be filesize and in my url I had www. It's not netion in my post but it was mistake.
More experienced programmer helped me.
r.php to read stream:
$res = file_get_contents("php://input");
$file = fopen('1.txt', "w");
fputs($file, $res);
fclose($file);
var_dump($res);
s.php to get stream and to init r.php
$image = fopen('/var/www/testfiles/1.jpg', "rb");
var_dump($image);
$ch = curl_init();
/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://url withot www/r.php");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $image);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('/var/www/testfiles/1.jpg'));
/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($image); //recommended to close the fileshandler after action
curl_close($ch);
die("OK");

Related

Cannot grab picture from specific site with php, how to download image via php?

Cannot grab pictures from the specific site with PHP, but with PYTHON is working for this site, how to download images via PHP?
image URL is https://www.autoopt.ru/product_pictures/big/bcb/054511.jpg
If I paste another URL, of another site, the picture is downloading, but this site doesn't work.
i try with file put content and so on, my last code is
<?php
function downloadImage($img_url){
$image = file_get_contents($img_url);
$img_save_path = realpath(dirname(__FILE__)) . '/assets/upload_products/';
$image_name = basename($img_url);
$image_fullpath = $img_save_path.$image_name;
$ch = curl_init ($img_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($image_fullpath)){
unlink($image_fullpath);
}
$fp = fopen($image_fullpath,'x');
fwrite($fp, $raw);
fclose($fp);
return true;
}
downloadImage('https://www.autoopt.ru/product_pictures/big/bcb/054511.jpg');
You dont need to do all that to save the picture if your going to use file_get_contents. It can be done by only using:
file_put_contents($image_fullpath, file_get_contents($img_url));
Also, like mentioned by OMi Shash in the comments, you'll need to pass header info to file_get_contents for it to work with that url. I've just done the test and it worked.
//set header info
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
//Basically adding headers to the request
$context = stream_context_create($opts);
file_put_contents($image_fullpath, file_get_contents($img_url, false, $context));

How to download client-site a video with cURL / PHP?

If the following PHP is runnig, I would like to download the file with `cURL on the client-site. It means, if one of my website visitor run's an action, which starts this PHP file, it should download the file on this PC.
I tried with different locations, but without any success. If I run my code, it does always download it on my WebSever, which is not this, what I want.
<?php
//The resource that we want to download.
$fileUrl = 'https://www.example.com/this-is-a-example-video';
//The path & filename to save to.
$saveTo = 'test.mp4';
//Open file handler.
$fp = fopen($saveTo, 'w+');
//If $fp is FALSE, something went wrong.
if($fp === false){
throw new Exception('Could not open: ' . $saveTo);
}
//Create a cURL handle.
$ch = curl_init($fileUrl);
//Pass our file handle to cURL.
curl_setopt($ch, CURLOPT_FILE, $fp);
//Timeout if the file doesn't download after 20 seconds.
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
//Execute the request.
curl_exec($ch);
//If there was an error, throw an Exception
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
//Get the HTTP status code.
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Close the cURL handler.
curl_close($ch);
if($statusCode == 200){
echo 'Downloaded!';
} else{
echo "Status Code: " . $statusCode;
}
?>
How can I change the cURL downloading process to the client-site?
PHP cannot run client-side.
You could use cURL to download data to the server (without saving it to a file) and then output that data to the client.
Don't do this:
//Open file handler.
$fp = fopen($saveTo, 'w+');
or this:
//Pass our file handle to cURL.
curl_setopt($ch, CURLOPT_FILE, $fp);
Then capture the output:
//Execute the request.
curl_exec($ch);
Should be:
//Execute the request.
$output = curl_exec($ch);
Then you can:
echo $output;
… but make sure you set the Content-Type and consider setting the Content-Length response headers. You might also want Content-Disposition.
Under most circumstances, it would probably be better to simply send the browser to fetch the file directly instead of proxying it through the server.
$fileUrl = 'https://www.example.com/this-is-a-example-video';
header("Location: $fileUrl");

Save copy of a photo from Google Places API Place Photos using curl

I'm trying to grab a photo from Google Place Photos using curl and save it on my server.
The request format as per the Google API documentation is like this:
https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CoQBegAAAFg5U0y-iQEtUVMfqw4KpXYe60QwJC-wl59NZlcaxSQZNgAhGrjmUKD2NkXatfQF1QRap-PQCx3kMfsKQCcxtkZqQ&sensor=true&key=AddYourOwnKeyHere
So I tried this function:
function download_image1($image_url, $image_file){
$fp = fopen ($image_file, 'w+');
$ch = curl_init($image_url);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FILE, $fp); // output to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
// curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch); // closing curl handle
fclose($fp); // closing file handle
}
download_image1($photo, "test.jpg");
..where $photo holds the request url.
This is not working, it saves an empty image with header errors, it probably is because the request is not the actual url of the photo. Also, in the request url, it's not possible to know which image extension I'm going to get (jpg, png, gif, etc) so that's another problem.
Any help on how to save the photos appreciated.
EDIT: I get the header errors "Can't read file header" in my image viewer software when I try to open the image. The script itself doesn't show any errors.
I found a solution here:
http://kyleyu.com/?q=node/356
It gives a very useful function to return the actual URL after redirection:
function get_furl($url)
{
$furl = false;
// First check response headers
$headers = get_headers($url);
// Test for 301 or 302
if(preg_match('/^HTTP\/\d\.\d\s+(301|302)/',$headers[0]))
{
foreach($headers as $value)
{
if(substr(strtolower($value), 0, 9) == "location:")
{
$furl = trim(substr($value, 9, strlen($value)));
}
}
}
// Set final URL
$furl = ($furl) ? $furl : $url;
return $furl;
}
So you pass the Google Place Photo request uRL to this function and it returns the actual URL of the photo after the redirection which then can be used with CURL. It also explains that sometimes, the curl option curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); doesn't always work.
https://stackoverflow.com/a/23540352/2979237
We can minimize the above code to change as adding 1 as the second parameter of get_header() function like $headers = get_headers($url, 1);. that will return the associate values.

Saving an image from a PHP URL using curl and PHP

I have tried to download an image from a PHP link. When I try the link in a browser it downloads the image. I enabled curl and I set “allow_url_fopen” to true. I’ve used the methods discussed here Saving image from PHP URL but it didn’t work. I've tried "file_get_contents" too, but it didn't work.
I made few changes, but still it doesn’t work. This is the code
$URL_path='http://…/index.php?r=Img/displaySavedImage&id=68';
$ch = curl_init ($URL_path);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
$fp = fopen($path_tosave.'temp_ticket.jpg','wb');
fwrite($fp, $raw);
fclose($fp);
Do you have any idea to make it works? Please help. Thanks
<?php
if( ini_get('allow_url_fopen') ) {
//set the index url
$source = file_get_contents('http://…/index.php?r=Img/displaySavedImage&id=68');
$filestr = "temp_ticket.jpg";
$fp = fopen($filestr, 'wb');
if ($fp !== false) {
fwrite($fp, $source);
fclose($fp);
}
else {
// File could not be opened for writing
}
}
else {
// allow_url_fopen is disabled
// See here for more information:
// http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
}
?>
This is what I used to save an image without an extension (dynamic image generated by server). Hope it works for you. Just make sure that the file path location is fully qualified and points to an image. As #ComFreek pointed out, you can use file_put_contents which is the equivalent to calling fopen(), fwrite() and fclose() successively to write data to a file. file_put_contents
You can use it as a function :
function getFile($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$tmp = curl_exec($ch);
curl_close($ch);
if ($tmp != false){
return $tmp;
}
}
And to call it :
$content = getFile(URL);
Or save its content to a file :
file_put_contents(PATH, getFile(URL));
You're missing a closing quote and semicolon on the first line:
$URL_path='http://…/index.php?r=Img/displaySavedImage&id=68';
Also, your URL is in $URL_path but you initialise cURL with $path_img which is undefined based on the code in the question.
Why use cURL when file_get_contents() does the job?
<?php
$img = 'http://…/index.php?r=Img/displaySavedImage&id=68';
$data = file_get_contents( $img );
file_put_contents( 'img.jpg', $data );
?>

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