displaying curl results using php - php

I am new to elastic search. I have one URL. Directly when executing that URL, I am getting results. But when I am trying to run this using curl, I am not getting any data. Below is my link
http://localhost:9200/bank/_search?q=address:mill
and the sample response from above link I am getting is
{"took":1,"timed_out":false,"_shards": {"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":4.8004513,"hits":[{"_index":"bank","_type":"account","_id":"136","_score":4.8004513,"_source":{"account_number":136,"balance":45801,"firstname":"Winnie","lastname":"Holland","age":38,"gender":"M","address":"198 Mill Lane","employer":"Neteria","email":"winnieholland#neteria.com","city":"Urie","state":"IL"}
}]}}
below is the curl program for above url.
$url = "localhost:9200/bank/account/_search?q=mill";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
var_dump($data);

You need to use HTTPGET option of CURLOPT and then You need to append your parameters with the url.
Try below code :
<?php
try {
$url = "http://localhost:9200/bank/_search";
$search_val = 'mill';
$str = "q=address:".$search_val;
$url_final = $url.'?'.$str;
$ch = curl_init();
if (FALSE === $ch)
throw new Exception('failed to initialize');
curl_setopt($ch, CURLOPT_URL, $url_final);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
if (FALSE === $return)
throw new Exception(curl_error($ch), curl_errno($ch));
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
curl_close ($ch);
echo $return;
?>

Related

cURL PHP to Plain cURL

I'm trying to connect my Rails app to a third-party API. In their example code, the code to connect to their service is all in PHP. I'm not familiar with PHP.
This is the code:
<?php
// Token generation
$timestamp = time();
$uri = "https://api.website.com/post.json";
$password = "somePassword";
$security_token = sha1($timestamp.$uri.$password);
// Webservice call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$post = array();
$post["timestamp"] = $timestamp;
$post["security_token"] = $security_token;
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_POST, true);
// USE THIS CODE TO CHECK THAT SSL CERTIFICATE IS VALID:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, "path/to/certifcate/file/certificate.crt");
$ret = curl_exec($ch);
// Check response
if(curl_errno($ch)) {
curl_close($ch);
die("CURL error: ".curl_error($ch));
}
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($http_code != 200) {
die("Server error, HTTP code: $http_code");
}
curl_close($ch);
// Parse response
try {
$json = json_decode($ret);
var_dump($json);
}
catch(Exception $e) {
die("Failed to decode server response");
}
?>
Any help to convert this to plain cURL would be appreciated and thanks in advance!
This is how I did it and it worked good.
uri = URI.parse("https://apilink/post.json")
pass = 'supper-password'
timestamp = Time.now
token = Digest::SHA1(timestamp + uri + pass)
request = Net::HTTP::Post.new(uri)
# request.body = "timestamp&security_token"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
render json: response.code

Duplicate data stored when using cURL

I am trying to post data using cURL to my web services to store data into database there, but it's storing the same data two times, instead of one. I applied condition there and it's working but i can not find the reason behind that behavior.
$postedArray['login_credentials'] = $this->login_data;
$postedArray['post_data'] = $this->arrPostData;
$str = http_build_query($postedArray);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_URL, $this->requestUrl);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 999);
curl_setopt($ch, CURLOPT_TIMEOUT, 999);
if (curl_exec($ch) === false) {
echo 'Curl error: ' . curl_error($ch);
return false;
}
$response = curl_exec($ch);
$response = json_decode($response, true);
curl_close($ch);
return $response;
Because you are actually calling curl_exec 2 times:
if (curl_exec($ch) === false) {
echo 'Curl error: ' . curl_error($ch);
return false;
}
$response = curl_exec($ch);
The first time while evaluating the response inside the if, and then again after the if. One should be dropped.
use curl_exec($ch) only once, code should look like this:
// code goes here
$response = curl_exec($ch);
if ($response === false)
{
echo 'Curl error: ' . curl_error($ch);
return false;
}
else
{
$json_response = json_decode($response, true);
}
curl_close($ch);
return $json_response;

How do I capture response from CURL

I use this piece of code below to send data to another server via a url and it work successfully. I want to capture the response from the server and process it but I can't seem to capture it.
CODE
$url="http://www.example.com/com_spc/api.php?username=".urlencode($uname)."&password=".urlencode($pwd);
$ch = curl_init(); // create cURL handle (ch)
if (!$ch) {
die("Couldn't initialize a cURL handle");
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL, $url);
$ret = curl_setopt($ch, CURLOPT_HEADER, 0);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// execute
$ret = curl_exec($ch);
if (empty($ret)) {
// some kind of an error happened
die(curl_error($ch));
curl_close($ch); // close cURL handler
} else {
$info = curl_getinfo($ch);
curl_close($ch); // close cURL handler
if (empty($info['http_code'])) {
die("No HTTP code was returned");
} else {
}
}
Make sure to set CURLOPT_RETURNTRANSFER to 1. Otherwise curl_exec will not return anything

php - curl empty response while browser display json output

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://itunes.apple.com/search?term=Clean%20Bandit%20-%20Rather%20Be&entity=song&limit=10&lang=fr_fr');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_errno($ch))
echo 'Curl error: '.curl_error($ch);
$CurResult = curl_exec($ch);
curl_close($ch);
echo 'Result:'.$CurResult;
$url = 'https://itunes.apple.com/search?term=Clean%20Bandit%20-%20Rather%20Be&entity=song&limit=10&lang=fr_fr';
$content = file_get_contents($url);
print_r($content);
Use this code to get the response curl is not needed in this case
from php manual
curl_errno()
does not return true or false, it returns error number 0, if no errors.
so you either change the condition to
if(curl_errno($ch)!=0)
or use curl_error()
if(curl_error($ch)!=''){
echo "error: ".curl_error($ch);
}
http://se2.php.net/manual/en/function.curl-errno.php

Handling cURL error inside a function?

I've seen the documentation, and several tutorials. However I can't get my code work handling errors. I just want to print "Error.", whatever error is.
Here's my code without handling error,
function get_data($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$page = get_data('http://....');
$doc = new DOMDocument();
#$doc->loadHTML($page);
echo $doc->saveHTML();
EDIT: The next one prints the default error message, but not mine.
function get_data($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
if($data === FALSE) {
$msg = curl_error($ch);
curl_close($ch);
throw new Exception($msg);
}
curl_close($ch);
return $data;
}
try {
$page = get_data('wrong-url');
$doc = new DOMDocument();
#$doc->loadHTML($page);
$div = $doc->getElementById('cuerpo');
echo $doc->saveHTML($div);
} catch (Exception $e) {
echo 'Error ', $e->getMessage();
}
curl_exec() will return false on errors. You can throw an Exception in this case:
function get_data($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
if($data === FALSE) {
$msg = curl_error($ch);
curl_close($ch);
throw new Exception($msg);
}
curl_close($ch);
return $data;
}

Categories