I'm created a simple PHP curl client that call a external webservice. This webservice return the XML.
<?php
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
$response = CallAPI('GET','https://s1-en.ogame.gameforge.com/api/universes.xml');
var_dump($response);
//print string(1121) " "
?>
But it always gives me back the wrong value. I print string(1121) " ".
How can I get the call data? (line 41 in the test.php).
This is because you are viewing the result in browser and the browser parses the xml as valid html tag. So you get empty result.
Its not your code issue. you can press ctrl + u (view source) in browser to see the actual result.
Or you can edit your var_dump to echo htmlentities($response); on line 41.
Related
I have rest API of Nodejs Server, I'm trying to make a POST call to it using PHP.
My php code is:
function post_url($apiRoute,$data) {
$request_url = 'http://test-app.herokuapp.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
echo $data ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I have tried calling this function with diff forms of data:
$g = array("_id" => "111");
$postapiresponse = post_url('/CCTRequest/get',json_encode($g));
OR
$postapiresponse = post_url('/CCTRequest/get',json_encode(array("_id" => "111"));
But on server side which Node.js, when I console log req.body I get data like this:
{ '{"_id":"111"}': '' }
How should I pass the data in PHP so I can get proper obj in node.js i.e:
{ '_id': '111' }
See the PHP document:
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_POST:
TRUE to do a regular HTTP POST. This POST is the normal
application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_POSTFIELDS:
If value is an array, the Content-Type header will be set to multipart/form-data.
So you can pass a query string returned by http_build_query() into CURLOPT_POSTFIELDS:
post_url('/CCTRequest/get', http_build_query($g, null, '&'));
and remove curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));. (In fact, the varieble should be $ch, but you typed $curl, so this line doesn't work.)
In the other way, you can replace curl_setopt($ch, CURLOPT_POST, 1); with
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');, it can prevent the data be encoded automaticlly. And then send json_encode() data.
I have solved by using http_build_query($g, null, '&') for making data.
$g = array("_id" => "111");
$g = http_build_query($g, null, '&');
$postapiresponse = post_url('/CCTRequest/get', $g);
You have a typo in the code, which will prevent it setting the header $curl should be $ch:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
You also need CURLOPT_RETURNTRANSFER uncommented.
function post_url($apiRoute, $data) {
$request_url = 'www.example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
This question has been asked. But any of those didn't work out for me. I am getting NULL when CURL call is made all the time.
The following is my list_clients.php file.
<?php
require_once 'init.php';
header('Content-Type: application/json');
$clientResults = mysqli_query($link, "SELECT * FROM clients");
$clients = array();
while($client = mysqli_fetch_assoc($clientResults)){
$clients[] = $client;
}
echo json_encode($clients);
exit;
So the output of the above is :
[{"ip_address":"192.168.177.137","mac_address":"3a:1a:cf:7c:92:89","added_on":"2017-08-19 12:48:34"},{"ip_address":"192.168.177.137","mac_address":"3a:1a:cf:7c:92:89","added_on":"2017-08-20 08:09:29"}]
The following is my curl_call.php file
<?php
$url = 'http://127.0.0.1/testing/list_clients.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
curl_setopt($curl, CURLOPT_HEADER, 0);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type : application/json',
'Accept: application/json'
));
$clientResult = curl_exec($curl);
if($clientResult == FALSE) {
var_dump(curl_error($curl));
}
curl_close($curl);
var_dump($clientResult); //For this line I am getting the following image eror
$clients = json_decode($clientResult, TRUE);
var_dump($clients);
If I var_dump($clientResult); then I am getting the following error
It's displaying NULL all the time. What might be causing the error.
You are missing a warning being thrown about $ch. It's undeclared, yet you reference it on line 17:
if($clientResult == FALSE) {
var_dump(curl_error($ch));
}
(As a side note, I'd use === FALSE, so valid return values which cast to FALSE don't wrongly trigger that code.)
You're also then carrying on with execution after the error is (failed to be) handled. The NULL you're seeing could be because the curl request failed.
Correct the typo in your code and stop (or do appropriately) if an error is thrown:
if($clientResult == FALSE) {
var_dump(curl_error($curl));
exit();
}
Update in response to the OP being updated:
The other reason NULL might be returned is because the response is not valid json. Check the PHP documentation:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
That HTML output you're debugging now shows (in your question update) won't parse as JSON.
Just now figured out. If I comment the following line of code in the curl_call.php it will work fine.
<?php
$url = 'http://127.0.0.1/testing/list_clients.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
/* curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type : application/json',
'Accept: application/json'
)); */
$clientResult = curl_exec($curl);
if($clientResult == FALSE) {
var_dump(curl_error($curl));
}
curl_close($curl);
var_dump($clientResult);
$clients = json_decode($clientResult);
var_dump($clients);
I am using codeigniter framework.
I want to retrieve the data from the URL provided. I already tried this answers: tried.
Problem is that when i access the url that time it is printing the data. but when i try it with file_get_contents function, it is not going to print any data.
<?php
$url ='https://test.com/getSessionData';
$test = file_get_contents($url);
$t = json_decode($test);
var_dump($t);
?>
That url returns json data like:
{
"email": "test#t.com",
"LOGIN": true,
"name": "testing",
"logintype": "ca"
}
Also tried using cURL:
<?php
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$curl_response = curl_exec($curl);
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
?>
But it is not working and it returns empty. i have checked that allow_url_fopen is on.
This might helpful
http://php.net/manual/en/migration56.openssl.php
So code looks like this:
<?php
$arrContextOptions=array(
"ssl"=>array(
"cafile" => "/path/to/bundle/ca-bundle.crt",
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents("https://test.com/getSessionData", false, stream_context_create($arrContextOptions));
echo $response; ?>
This is the class I said:
/**
* Created by PhpStorm.
* User: rain
* Date: 15/11/2
* Time: 下午4:08
*/
class MyCurlLibrary{
public static function getRequest($url,Array $data=array(),$isNeedHeader=0){
$ch = curl_init();
if($data){
$bindQuery = http_build_query($data);
$url.="?".$bindQuery;
}
curl_setopt($ch, CURLOPT_URL, $url);
//if need return
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//this is for https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, $isNeedHeader);//if contains header
//this is for web redirect problem
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
public static function postRequest($url,Array $data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post Data
curl_setopt($ch, CURLOPT_POST, 1);
// post variable
if($data){
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($ch);
curl_close($ch);
//return data
return $output;
}
}
/**
* sample
*
* //test Data
$url = "http://localhost:8080/test/test.php";//改文件有代码 print_r($_GET); print_r($_POST)
$data = array('a'=>'b','c'=>'d',8=>666,888);
//test get function
$result = MyCurl::getRequest($url,$data);
//test post function
$result = MyCurl::postRequest($url,$data);
//print result
var_dump($result);
*
*
*/
[Solved] I have an HBase 1.1.2 standalone installation on Ubuntu 14 and I need to retrieve and update data by PHP POST request (I cannot use GET because of length limit) through a REST server. I was going to use a curl PHP object but my problem is I don't understand how to format the request (in JSON or XML) to be submitted in POST at REST server.
Can anyone help me?
Thanks
Let me add my object i would like to use for all the request: getting rows by key and set\create row. My problem is how make $DATA field according different action.
function method($method, $data=NULL, & $http_code, & $response)
{
$ch = curl_init();
if(isset($header))
{
curl_setop(CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_URL, "http://" . $GLOBALS['DBDW']['hostname'] . $GLOBALS['DBDW']['port']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//nuovi
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'Connection: ' . ( $this->options['alive'] ? 'Keep-Alive' : 'Close' ),
));
// fine nuovi
switch(strtoupper($method)){
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
// i have to set CURLOPT_POSTFIELDS and if yes how?
break;
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// how setting CURLOPT_POSTFIELDS and if yes how?
break;
case 'GET':
curl_setopt($curl, CURLOPT_HTTPGET, 1);
// i have to set CURLOPT_POSTFIELDS and if yes how?
break;
}
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->log(LOG_DEBUG, "HTTP code: " . $http_code, __FILE__, __LINE__, __CLASS__);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($response === false)
{
$this->log(LOG_ERR, "HTTP " . $method . " failed on url '" . $url . "'", __FILE__, __LINE__, __CLASS__);
$this->log(LOG_ERR, "cURL error: " . $curl_errno . ":" . $curl_error, __FILE__, __LINE__, __CLASS__);
$http_code=ERR_COMMUNICATION_FAILED;
return false;
}
return true;
}
CURLOPT_POSTFIELDS is only required if you're using post, so you switch/case is correct as is.
If you want to make GET requests, you just append the GET stuff to the url, just like you would see it in your broswer. This function is handy for that purpose: http_build_query.
// define the url in a variable above the switch
$url = "http://" . $GLOBALS['DBDW']['hostname'] . $GLOBALS['DBDW']['port'];
switch(strtoupper($method)){
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
// append the GET parameters if any
if(!empty($data)) $url .= "?".http_build_query($data);
break;
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case 'GET':
curl_setopt($curl, CURLOPT_HTTPGET, 1);
// append the GET parameters if any
if(!empty($data)) $url .= "?".http_build_query($data);
break;
}
// move this line below the switch
curl_setopt($ch, CURLOPT_URL, $url);
This is the function I use for cURL stuff. You can refer to it (or use it) if you want.
I'm trying to do a DELETE http request using PHP and cURL.
I have read how to do it many places, but nothing seems to work for me.
This is how I do it:
public function curl_req($path,$json,$req)
{
$ch = curl_init($this->__url.$path);
$data = json_encode($json);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data)));
$result = curl_exec($ch);
$result = json_decode($result);
return $result;
}
I then go ahead and use my function:
public function deleteUser($extid)
{
$path = "/rest/user/".$extid."/;token=".$this->__token;
$result = $this->curl_req($path,"","DELETE");
return $result;
}
This gives me HTTP internal server ERROR.
In my other functions using the same curl_req method with GET and POST, everything goes well.
So what am I doing wrong?
I finally solved this myself. If anyone else is having this problem, here is my solution:
I created a new method:
public function curl_del($path)
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $result;
}
Update 2
Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:
/**
* #desc Do a DELETE request with cURL
*
* #param string $path path that goes after the URL fx. "/user/login"
* #param array $json If you need to send some json with your request.
* For me delete requests are always blank
* #return Obj $result HTTP response from REST interface in JSON decoded.
*/
public function curl_del($path, $json = '')
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
return $result;
}
To call GET,POST,DELETE,PUT All kind of request, i have created one common function
function CallAPI($method, $api, $data) {
$url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "POST":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
break;
}
$response = curl_exec($curl);
$data = json_decode($response);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check the HTTP Status code
switch ($httpCode) {
case 200:
$error_status = "200: Success";
return ($data);
break;
case 404:
$error_status = "404: API Not found";
break;
case 500:
$error_status = "500: servers replied with an error.";
break;
case 502:
$error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
break;
case 503:
$error_status = "503: service unavailable. Hopefully they'll be OK soon!";
break;
default:
$error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
break;
}
curl_close($curl);
echo $error_status;
die;
}
CALL Delete Method
$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);
CALL Post Method
$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);
CALL Get Method
$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);
CALL Put Method
$data = array('id'=>$_REQUEST['eid'],'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);