API not executing? Confusion - php

I'm trying to get the Sentiment Analysis of a piece of texting using the Lymbix tutorial.
From research, I can use curl and when I want to execute the curl, use curl_exec();
But, I used a tutorial and have this piece of code:
function sentimentToken($programming)
{
$ch = curl_init();
$data = array('article' => $programming);
$headers = array ('AUTHENTICATION'=>'MY_API_KEY','ACCEPT'=>'application/json','VERSION'=>'2.1');
curl_setopt($ch, CURLOPT_URL, "http://gyrus.lymbix.com/tonalize");
curl_setopt($ch, CURLOPT_HTTPHEADERS,$headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
}
But var_dump($result) Does not return anything. Does anyone have any ideas?

Josh here from Lymbix - we have several client libraries available to make it easier:
http://lymbix.com/client-libraries?client_library=ruby&__lsa=c4bbd4e8 for our list of client libraries
or
Straight from our github page:
https://github.com/lymbix/
Let me know if you need any help!

According to the documentation:
curl_exec returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
Given your actual options, you are not expected to have any data as a result, but rather an indication of success or failure.

Related

Curl showing but not returning data

I'm trying to write a simple curl function that queries the freegeoip.net site with the IP address of a site visitor. This is usually done by typing "https://freegeoip.net/csv/{IP Address}" in the browser address line. The site then processes the request and returns a csv file that can be opened or saved. I'm trying to access the csv data directly so that I can parse and use it. This is the code that I am using:
<?php
$ip=$_SERVER["REMOTE_ADDR"];
$geturl = "http://freegeoip.net/csv/".$ip;
$data = curl_get_contents($geturl);
echo ("<br>Data = '".$data."'<br>");
function curl_get_contents($url)
{
$ch = curl_init($url);
if($ch)
{
$tmp = curl_exec($ch);
curl_close($ch);
return $tmp;
}
else
{
echo "Curl not loaded!<br>";
}
}
?>
This is what I am getting back:
...,US,United States,ST,State,City,?????,America/New_York,.*****,-.****,***
Data = '1'
As you can see, my function is accessing and showing the csv data but not returning it to the $data variable. Apparently, the data is being shown when the "curl_exec($ch);" command is being executed. I want to parse and use the returned data but can't until the data is returned. What am I doing wrong?
The documentation of curl_exec() says:
Return Values
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
What it doesn't say is explained in the documentation page of curl_setopt(), on the CURLOPT_RETURNTRANSFER option:
Option: CURLOPT_RETURNTRANSFER
Set value to: TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
That is, by default, curl_exec() outputs the body of the response it gets. In order to make it return the value and not output it, you have to use curl_setopt():
$ch = curl_init($url);
curl_exec($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
you need to add following line before curl_exec other wise the result will output instead of returning it to $tmp variable.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
You aren't telling Curl that you want the data to be returned rather than output:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
curl_setopt($ch, CURLOPT_URL, "http://freegeoip.net/csv/".$ip);
$csv=curl_exec($ch);
But this is rather verbose when, depending on your config, you can:
$csv=file_get_contents("http://freegeoip.net/csv/".$ip);

Getting multiple http response codes using cURL?

Please take a look at this sample code:
function http_response($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $httpCode ;
}
this code will print the httpCode of the given url. I have couple of questions:
Can I get rid of some setopt() lines here and still getting httpCode?
What about if I want to check multiple urls at the same time? Can I modify the code to do that?
Can I do the same functionality in a simpler way using libraries different than cURL?
Thanks :)
You should be able to remove CURLOPT_HEADER and CURLOPT_NOBODY and still get the same result.
You could do that like this:
$urls = array(
'http://google.com',
'http://facebook.com'
);
$status = array();
foreach($urls as $url){
$status[$url] = http_response($url);
}
Try print_r($status); after this and you'll see the result.
You could do this with file_get_contents and $http_response_header, to learn more: http://www.php.net/manual/en/reserved.variables.httpresponseheader.php I would however recommend using cURL anyway.
*2. to check multiple urls you have to use this function in a loop, in any programming language 1 response from a server = 1 connection to that server. If you want to use 1 function to get responses from multiple servers you can always pass an array to the function and do the loop inside the function
*3. you can try this way:
function get_contents() {
file_get_contents("http://example.com");
var_dump($http_response_header);
}
get_contents();

Why does cURL always return a status code?

I have some PHP code that calls into the cURL library. I'm using it to get JSON data.
I have set cURL opt 'CURLOPT_RETURNTRANSFER' to 1, but still get status code..
Code follows:
<?php
function fetch_page($url)
{
$ch = curl_init();
$array = array(
'include'=>'ayam'
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
$return = fetch_page(MY_LINK_URL);
echo json_decode($return);
?>
The code looks totally correct. Try var_dump($result) before returning it to see what it is exactly.
Also, set CURLOPT_HEADER to 1 and check the view source of the output in your browser; both of these can help debug the issue. Edit the question and post the results if so we can help more effectively.
Update: Since you are using HTTPS, also add
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
That looks correct. I actually have the same problem, but when I added
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
it returns json code correctly instead of returning 1(True).
According to the PHP docs,
Returns TRUE on success or FALSE on
failure. However, if the
CURLOPT_RETURNTRANSFER option is set,
it will return the result on success,
FALSE on failure.
So that means you should get
success: the result
failure: FALSE (which is echoed as 0)
Also, if you are fetching JSON, and need to access it, use json_decode() not json_encode().
Well, you should tell us wich url you're pointing (and wich version of php you are running).
I've tried with php 5.3 on "www.google.com" and it worked as expected ($result contains the whole webpage)
Might of had a similar problem:
- cURL on local dev network problem with virtual host naming
Before you close your curl handle output this:
$result = curl_exec ($ch);
print_r(curl_getinfo($ch));
curl_close ($ch);
Here was my solution for getting around the virtual host
// This is your Virtual Hosts name
$request_host = 'dev.project';
// This is the IP
$request_url = '192.168.0.1';
$headers = array("Host: ".$request_host);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $request_url.'?'.$request_args);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
There seems to be a number of reasons why CURLOPT_RETURNTRANSFER can be ignored, and SSL certificate checking is only one of them:
In my case the culprit was CURLOPT_POST which I had set to true. I was expecting to get back a string consisting of the HTTP response header plus the response itself. Instead I was getting status code 1. Go figure. Thankfully I did not need the HTTP header so the solution for me was:
curl_setopt($ch, CURLOPT_HEADER, false);
If I did need the header info, I don't know what I would do. I've wasted an insane amount of time tracking down the problem.
Damn you PHP curl! (waves fist in anger)

php script for in-app purchase

i'm doing an application for iPhone/iPad which uses the in-app purchase functionality. On the server side i load a php script for the receipt verification. Here is the content of the script:
<?php
$receipt = json_encode(array("receipt-data" => $_GET["receipt"]));
// NOTE: use "buy" vs "sandbox" in production.
$url = "https://sandbox.itunes.apple.com/verifyReceipt";
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_HEADER, 0);
curl_setopt($curl_handle, CURLOPT_POST, true);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $receipt);
$response_json = curl_exec($curl_handle);
$response = json_decode($response_json);
curl_close($curl_handle);
print $response->{'status'};
?>
My problem is that the response variable is always empty, i can't receive any response. Also the response_json is empty and i can't understand which is the problem. I think is something server side, but i'm not an expert of php and the server is not under my direct control. Can anyone suggest me a way to resolve the problem or to test which coulod be?
Thank's
If curl_exec() fails, it will return a boolean FALSE. You blindly feed the response to json_decode and assume you'll get something out. Decoding boolean false gives you an empty var. Instead, try this:
...
$response_json = curl_exec($curl_handle);
if ($response_json === FALSE) {
die(curl_error($curl_handle));
}
$response = json_decode($response_json);
...

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