Send cURL request from URL? - php

Greetings,
I'm looking for a way to send a curl request given a full url. All of the examples and documentation I can find look something like this:
$fullFilePath = 'C:\temp\test.jpg';
$upload_url = 'http://www.example.com/uploadtarget.php';
$params = array(
'photo'=>"#$fullFilePath",
'title'=>$title
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);
The problem is that the file, "test.jpg" is actually generated dynamically by a script on the server (so it doesn't exist on the file system).
How can I send the request, instead using $file = "http://www.mysite.com/generate/new_image.jpg"
One solution that came to mind was loading "new_image.jpg" into memory with fopen or file_get_contents() but once I get to that point I'm not sure how to send it as POST to another site

By far the easiest solution is going to be to write the file to a temporary location, then delete it once the cURL request is complete:
// assume $img contains the image file
$filepath = 'C:\temp\tmp_image_' . rand() . '.jpg'
file_put_contents($filepath, $img);
$params = array(
'photo'=>"#$filepath",
'title'=>$title
);
// do cURL request using $params...
unlink($filepath);
Note that I am inserting a random number to avoid race conditions. If your image is not particularly big, it would be better to use md5($img) in your filename instead of rand(), which could still result in collisions.

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));

Curl and php download file from url not working

I'm trying do retrieve and download a file (image) from a remote location.
Inside the php.ini the allow_url_fopen is enabled, but i can't download the image.
Code i'm using is described below
$local_file = "test.jpg";
$remote_file = "http://somehost:6346/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=xxxx&pwd=xxxx";
$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);
with any other url that contains a real jpg file, it's working perfectly, i suppose that the issue is that the url use some special characters that doesn't like to curl.
If i try to execute the php snippet above,page load for almost 1 minute,and it seems that no error are displayed,the image test.jpg is created, but it's empty.
Do you have any suggestion?
Thanks!
Try this
$local_file = "test.jpg";
$remote_file = "http://somehost:6346/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=xxxx&pwd=xxxx";
function getPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function saveToFile($base, $decode=false, $output_file)
{
$ifp = fopen($output_file, "wb");
if ($decode){
fwrite($ifp, base64_decode($base));
}else{
fwrite($ifp, $base);
}
fclose($ifp);
return($output_file);
}
$remote_page = getPage($remote_file);
$saved_file = saveToFile($remote_page , false, $local_file);
when debugging issues like this, set CURLOPT_VERBOSE, it will probably reveal why the page loaded for almost 1 minute, with no apparent output.
i suppose that the issue is that the url use some special characters - this is fully possible, for example your username and password, they're supposed to be urlencoded. urlencoding is binary safe, meaning you can have any special characters you'd like, you just need to encode it properly. use urlencode() or http_build_query() for that, eg
$remote_file = "http://somehost:6346/cgi-bin/CGIProxy.fcgi?" . http_build_query ( array (
'cmd' => 'snapPicture2',
'usr' => 'username',
'pwd' => 'password'
) );
now http_build_query will properly urlencode any special characters in your username and password (for example, if your username is an email address, the # becomes %40).
if that doesn't fix it, what does CURLOPT_VERBOSE say?
also, final note, here you're sending the download request with credentials in a GET request. that's very unusual, the vast majority of websites want you to login with a POST request, and there are good security-related reasons for that, are you sure your website allows sending credentials in GET parameters? the vast majority of websites doesn't allow it... (and the best way to find out, is to record a browser logging in, does the browser use GET parameters, or POST parameters?)

Curl/PHP challenge transferring image and base64_encode/decode

I am transfering data from one linux-box to another. In generel this works fine, BUT I am having trouble when it comes to transferring images. I have tested all kinds of stuff. I hope some one may be able to help me out.
$filename = "/home/user/image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$data = base64_encode($data);
# Transfer reading
#$arrIn['changeCharset'] = "true";
$arrIn['postFields'] = "action=test&data=$base64";
$test = curlServerPost($arrIn);
Here is my CURL-function:
function curlServerPost($arrIn)
{
$postFields = $arrIn['postFields'];
$url = "$GLOBALS[remoteSite]"; // Where you want to post data
$ch = curl_init(); // Initiate cURL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); // Define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepter alle certifikater, se: http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
$res = curl_exec($ch); // Execute
curl_close($ch); // Close cURL handle
return($res);
}
Finally, here is the receiver (server) part
$data = $_POST[data];
$data = base64_decode($data);
$stmt = $GLOBALS[pdo]->prepare("INSERT INTO cameraImages (cameraImagesId) VALUES ('')");
$stmt->execute();
$cameraImagesId = $GLOBALS[pdo]->lastInsertId();
$stmt = $GLOBALS[pdo]->prepare("UPDATE cameraImages SET cameraImagesFile='$data' WHERE cameraImagesId='$cameraImagesId'");
$stmt->execute();
Some last remarks:
- If I don't base_decode on server-side I receive (but completely wrong format. Errors in image)
If I base_decode om server-side. Nothing is received.
I would like to don't encode/decode at all. If I do that. Only a small part of the image is stored (corrupted image)
My datafield is LONGBLOB (mysql)
PHP on server side is: PHP 5.3.3
PHP on client side is: PHP 7.0.27-0+deb9u1
I have tried all kinds of stuff. Followed all kinds of tutorials. It just won't work for me :-/
So if anyone can come up with ideas I am more than willing to test and try :)
Loooking forward to hear from you.
Succes. I just needed
urlencode($data);
And removed base64_encode($data); / base64_decode($data);
I have dropped putting images in database since many ppl don't recommend it.

Get file contents without file_get_contents

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.

Updating Twitter background via API

I'm having a little trouble updating backgrounds via Twitter's API.
$target_url = "http://www.google.com/logos/11th_birthday.gif";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
$content = $to->OAuthRequest('http://twitter.com/account/update_profile_background_image.xml', array('profile_background_image_url' => $html), 'POST');
When I try to pull the raw data via cURL or file_get_contents, I get this...
Expectation Failed The expectation given in the Expect request-header
field could not be met by this server.
The client sent
Expect: 100-continue but we only allow the 100-continue expectation.
OK, you can't direct Twitter to a URL, it won't accept that. Looking around a bit I've found that the best way is to download the image to the local server and then pass that over to Twitter almost like a form upload.
Try the following code, and let me know what you get.
// The URL from an external (or internal) server we want to grab
$url = 'http://www.google.com/logos/11th_birthday.gif';
// We need to grab the file name of this, unless you want to create your own
$filename = basename($url);
// This is where we'll be saving our new file to. Replace LOCALPATH with the path you would like to save the file to, i.e. www/home/content/my_directory/
$newfilename = 'LOCALPATH' . $filename;
// Copy it over, PHP will handle the overheads.
copy($url, $newfilename);
// Now it's OAuth time... fingers crossed!
$content = $to->OAuthRequest('http://twitter.com/account/update_profile_background_image.xml', array('profile_background_image_url' => $newfilename), 'POST');
// Echo something so you know it went through
print "done";
Well, given the error message, it sounds like you should load the URL's contents yourself, and post the data directly. Have you tried that?

Categories