Flickr photo search API not returning anything - php

I tried to do a flickr search using cURL and Flickr API. When trying to print the response, it prints "1". What is wrong with my code?
$params = array(
'api_key' => 'b838e46f6e8eada6a62fac7e2b25ffcc',
'method' => 'flickr.photos.search',
'format' => 'php_serial',
'text' =>'cars'
);
$encoded_params = array();
foreach($params as $k => $v){
$encoded_params[] = urlencode($k).'='.urlencode($v);
}
$ch = curl_init();
$timeout = 0; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, 'https://api.flickr.com/services/rest/?'.implode('&', $encoded_params));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
print_r($file_contents);
curl_close($ch);
$rsp_obj = unserialize($file_contents);
//echo 'https://api.flickr.com/services/rest/?'.implode('&', $encoded_params);
echo print_r($rsp_obj);

If cURL can not verify the certificate of the remote site, then you can set the option CURLOPT_SSL_VERIFYPEER to false, so that it will not try to do that.
This has of course some security implications – the remote site might not be who they pretend they are, but if you’re only doing a search that’s a rather minor concern, especially when you’re only testing locally for now. For a production app on a server you should maybe look into getting that fixed though, especially when you’ll be doing something that isn’t a pure search later on.

Related

Getting images from Instagram, always null

I develop a small script on localhost (WAMP server, CURL enabled) to retrieve images from Instagram. Based on this script: see tutorial I have also set up the variables on Instagram. I'm not sure what is wrong more specifically or how to solve it (probably with authentication).
USER ID
CLIENT ID
CLIENT SECRET
WEBSITE URL
REDIRECT URI
This is my user
http://instagram.com/krondorl
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/280766222/media/recent/?access_token=df04c6989eaf4490bdac1f82554182bb");
$result = json_decode($result);
var_dump($result);
Try the code below which works for me. Make sure your URL is correct.
$json_url ='https://api.instagram.com/v1/users/280766222/media/recent/?access_token=df04c6989eaf4490bdac1f82554182bb';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json')
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$results = curl_exec($ch); // Getting jSON result string
$json_decoded = json_decode($results);
By the way I check your URL which happens to be incorrect and give me the below error.
{"meta":{"error_type":"OAuthAccessTokenException","code":400,"error_message":"The \"access_token\" provided is invalid."}}
Before you trying the code, try the URL on the browser and see whether the URL is correct.

Asynchronous cURL using POST

I am making a command line application. I need to send out multiple POST requests via cURL simultaneously after I have performed log in procedures - meaning outgoing requests must send session id etc.
The chain of events is as follows:
I open cURL connection with curl_init
I log in to remote site sending POST request with curl_exec and get returned HTML code as response
I send multiple POST requests to same site simultaneously.
I was thinking of using something like that:
// Init connection
$ch = curl_init();
// Set curl options
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
// Perform login
curl_setopt($ch, CURLOPT_URL, "http://www.mysite/login.php");
$post = array('username' => 'username' , 'password' => 'password');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$result = curl_exec($ch);
// Send multiple requests after being logged on
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
for($i = 0 ; $i < 10 ; $i++){
$post = array('myvar' => 'changing_value');
curl_setopt($ch, CURLOPT_URL, 'www.myweb.ee/changing_url');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_exec($ch);
}
But this doesn't seem to work as only the first request in loop seems to be sent.
Using curl_multi_init would probably one solution but I don't know if i can pass it the same cURL handle multiple times with changed options for each.
I don't need any response from server for those simultaneous requests but it would be awesome if it also can be done somehow.
It would be perfect if someone could push me in the right direction how to do it.
You'll need to create a new curl handle for every request, and then register it with http://www.php.net/manual/en/function.curl-multi-add-handle.php
here is some code i ripped out and adapted from my code base, have in mind that you should add error checking in there.
function CreateHandle($url , $data) {
$curlHandle = curl_init($url);
$defaultOptions = array (
CURLOPT_COOKIEJAR => 'cookies.txt' ,
CURLOPT_COOKIEFILE => 'cookies.txt' ,
CURLOPT_ENCODING => "gzip" ,
CURLOPT_FOLLOWLOCATION => true ,
CURLOPT_RETURNTRANSFER => true ,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($curlHandle , $defaultOptions);
return $curlHandle;
}
function MultiRequests($urls , $data) {
$curlMultiHandle = curl_multi_init();
$curlHandles = array();
$responses = array();
foreach($urls as $id => $url) {
$curlHandles[$id] = CreateHandle($url , $data[$id]);
curl_multi_add_handle($curlMultiHandle, $curlHandles[$id]);
}
$running = null;
do {
curl_multi_exec($curlMultiHandle, $running);
} while($running > 0);
foreach($curlHandles as $id => $handle) {
$responses[$id] = curl_multi_getcontent($handle);
curl_multi_remove_handle($curlMultiHandle, $handle);
}
curl_multi_close($curlMultiHandle);
return $responses;
}
There's a faster, more efficient option ... that doesn't require that you use any curl at all ...
http://uk3.php.net/manual/en/book.pthreads.php
http://pthreads.org
See github for latest source, releases on pecl ....
I will say this, file_get_contents may seem appealing, but PHP was never designed to run threaded in this manner, it's socket layers and the like give no thought to consumption you might find that it's better to fopen and sleep inbetween little reads to conserve CPU usage ... however you do it it will be much better ... and how you do it depends on what kind of resources you want to dedicate the task ...

Warning: file_get_contents: failed to open stream: Redirection limit reached, aborting

I read over 20 related questions on this site, searched in Google but no use. I'm new to PHP and am using PHP Simple HTML DOM Parser to fetch a URL. While this script works with local test pages, it just won't work with the URL that I need the script for.
Here is the code that I wrote for this, following an example file that came with the PHP Simple DOM parser library:
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.farmersagent.com/Results.aspx?isa=1&name=A&csz=AL');
foreach($html->find('li.name ul#generalListing') as $e)
echo $e->plaintext;
?>
And this is the error message that I get:
Warning: file_get_contents(http://www.farmersagent.com/Results.aspx?isa=1&name=A&csz=AL) [function.file-get-contents]: failed to open stream: Redirection limit reached, aborting in /home/content/html/website.in/test/simple_html_dom.php on line 70
Please guide me what should be done to make it work. I'm new so please suggest a way that is simple. While reading other questions and their answers on this site, I tried cURL method to create a handle but I failed to make it work. The cURL method that I tried keeps returning "Resources" or "Objects". I don't know how to pass that to Simple HTML DOM Parser to make $html->find() work properly.
Please help!
Thanks!
Had a similar problem today. I was using CURL and it wasn't returning my any error. Tested with file_get_contents() and I got...
failed to open stream: Redirection limit reached, aborting in
Made a few searches and I'v ended with this function that works on my case...
function getPage ($url) {
$useragent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36';
$timeout= 120;
$dir = dirname(__FILE__);
$cookie_file = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
$content = curl_exec($ch);
if(curl_errno($ch))
{
echo 'error:' . curl_error($ch);
}
else
{
return $content;
}
curl_close($ch);
}
The website was checking for a valid user agent and for cookies.
The cookie issue was causing it! :)
Peace!
Resolved with:
<?php
$context = stream_context_create(
array(
'http' => array(
'max_redirects' => 101
)
)
);
$content = file_get_contents('http://example.org/', false, $context);
?>
You can also inform if you have a proxy in the middle:
$aContext = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
$cxContext = stream_context_create($aContext);
More details on: https://cweiske.de/tagebuch/php-redirection-limit-reached.htm (thanks #jqpATs2w)
Using cURL you would need to have the CURLOPT_RETURNTRANSFER option set to true in order to return the body of the request with call to curl_exec like this:
$url = 'http://www.farmersagent.com/Results.aspx?isa=1&name=A&csz=AL';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// you may set this options if you need to follow redirects. Though I didn't get any in your case
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$content = curl_exec($curl);
curl_close($curl);
$html = str_get_html($content);
I also needed to add this HTTP context options ignore_errors :
see : https://www.php.net/manual/en/context.http.php
$arrContextOptions = array(
"ssl" => array(
// skip error "Failed to enable crypto" + "SSL operation failed with code 1."
"verify_peer" => false,
"verify_peer_name" => false,
),
// skyp error "failed to open stream: operation failed" + "Redirection limit reached"
'http' => array(
'max_redirects' => 101,
'ignore_errors' => '1'
),
);
$file = file_get_contents($file_url, false, stream_context_create($arrContextOptions));
Obviously, I only use it for quick debugging purpose on my local environment. It is not for production.
I'm not sure exactly why you redefined the $html object with a string from get html, The object is meant to be used for searching the string. If you overwrite the object with a string, the object no longer exists and cannot be used.
In any case, to search the string returned from curl.
<?php
$url = 'http://www.example.com/Results.aspx?isa=1&name=A&csz=AL';
include('simple_html_dom.php');
# create object
$html = new simple_html_dom();
#### CURL BLOCK ####
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
# you may set this options if you need to follow redirects.
# Though I didn't get any in your case
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$content = curl_exec($curl);
curl_close($curl);
# note the variable change.
$string = str_get_html($content);
# load the curl string into the object.
$html->load($string);
#### END CURL BLOCK ####
# without the curl block above you would just use this.
$html->load_file($url);
# choose the tag to find, you're not looking for attributes here.
$html->find('a');
# this is looking for anchor tags in the given string.
# you output the attributes contents using the name of the attribute.
echo $html->href;
?>
you might be searching a different tag, the method is the same
# just outputting a different tag attribute
echo $html->class;
echo $html->id;

emulate XMLHttpRequest client using PHP

For testing where should i give the url of the site, can you show me with the example in the above code?
$r = new HTTPRequest("server.php", HTTP_METH_POST);
$r->addPostFields(array('omg' => 'wtf'));
$r->send();
var_dump($r->getResponseCode());
var_dump($r->getResponseBody());
Simply use addHeaders().
The XMLHttpRequest is the value of the X-Requested-With header, so you just have to do:
$r = new HTTPRequest("http://mywebservices.com/somewebserver.php", HTTP_METH_POST);
$r->addHeaders(array('X-Requested-With' => 'XMLHttpRequest'));
Instructions for installing HTTP from PECL: http://www.php.net/manual/en/http.setup.php
phpdev has answered your question very well, and if you install the HTTP extension and do it as according to the answer it will surely work.
$r = new HttpRequest('http://your-required-url-here', HttpRequest::METH_POST);
$r->addPostFields(array('omg' => 'wtf'));
echo $r->send()->getBody();
The urls given by you in the previous comments are not well formed, it seems that you have pasted some random URL.
This is just another way to do it with php CURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.openfirms.com/index.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array('omg' => 'wtf');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
print_R($output);
This will output the contents of specified url. Hope it will help

cURL POST to REST Service

I am trying to post to a REST service using PHP cURL but I'm after running into a bit of difficulty (this being that I've never used cURL before!!).
I've put together this code:
<?php
error_reporting(E_ALL);
if ($result == "00")
{
$url = 'http://127.0.0.1/xxxxxx/AccountCreator.ashx'; /*I've tried it a combination of ways just to see which might work */
$curl_post_data = array(
'companyName' =>urlencode($companyName),
'mainContact' =>urlencode($mainContact),
'telephone1' =>urlencode($telephone1),
'email' => urlencode($email),
'contact2' => urlencode($contact2),
'telephone2' => urlencode($telephone2)
'email2' => urlencode($email2);
'package' => urlencode($package)
);
foreach($curl_post_data as $key=>$value) {$fields_string .=$key. '=' .$value.'&';
}
rtrim($fields_string, '&');
die("Test: ".$fields_string);
$ch = curl_init();
curl_setopt ($ch, CURLOPT, $url);
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
Following this, my code sends an email and performs an IF statement. I know this works okay, I only started running into trouble when I tried to insert this cURL request.
I've tried this however it doesn't run. As I am integrating with payment partners, it just says:
Your transaction has been successful but there was a problem connecting back to the merchant's web site. Please contact the merchant and advise them that you received this error message. Thank you.
The exact error that was received was a HTTP 500 error.
Thanks.
foreach($curl_post_data as $key=>value) {$fields_string .=$key. '=' .value.'&';
value here is missing a dollar i guess
foreach($curl_post_data as $key => $value) {$fields_string .=$key. '=' .$value.'&';
have you tried die($fields_string); to see what are you actually sending to the merchant?
First of all: are you testing locally? Because that IP you're using is not a valid server address.
The constant to set the URL is called CURLOPT_URL:
curl_setopt ($ch, CURLOPT_URL, $url);
Also CURLOPT_POST must be true or false ( http://php.net/curl_setopt ), not a number (except for 1 maybe):
curl_setopt ($ch, CURLOPT_POST, true);
Here's some POST sample code: PHP + curl, HTTP POST sample code?
It would be best if you can provide your PHP version.
As of PHP 5, some handy functions are bundled in the core instead of separate PECL libraries.
// If you are working with normal HTTP requests, simply do this.
$curl_post_data = http_build_query($curl_post_data);
curl_setopt($ch, CURLOPT, $url);
// This is a boolean option, although passing non-zero integer
// will be type-casted to TRUE, count() is not the proper way.
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_post_data);
// If you really want the next statement be meaningful, do this.
// Otherwise your HTTP response will be passed directly into
// the output buffer.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
Keep in mind that CURLOPT_POSTFIELDS in PHP supports file uploads, by adding a '#' character followed by a full file path as the value.
You don't want to call http_build_query() on such situations.
Sample code for file upload
$curl_post_data = array('file1' => '#/home/user/files_to_be_uploaded');
While you can optionally specify MIME type, see the documentation for more information.
As said, check your PHP version first. This feature only works in PHP 5, AFAIK there are companies still hosting PHP 4.x in their servers.
Have a look at http_build_query

Categories