I newbie on PHP, REST and cURL. I'm try to build an application to do GET and POST request. I did some tutorials and read cURL documentations.
I did GET request and get some response but I could not get my actual need :)
Here is my code.
<?php
$url = 'https://ise.cisco.connect:9060/ers/config/portal';
$method = 'GET';
// headers and data (this is API dependent, some uses XML)
$headers = array(
'Accept: application/vnd.com.cisco.ise.identity.portal.2.0+xml'
);
$data = json_encode(array(
'firstName'=> 'John',
'lastName'=> 'Doe'
));
$username = 'sponsor';
$password = 'Password1';
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_USERPWD, $username.':'.$password);
curl_setopt($handle, CURLOPT_HEADER, 1);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
switch($method)
{
case 'GET':
break;
case 'POST':
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
case 'PUT':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
case 'DELETE':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
}
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
echo curl_getinfo($handle, CURLINFO_CONTENT_TYPE );
echo $code;
print_r ($response);
?>
CURLINFO_CONTENT_TYPE , CURLINFO_HTTP_CODE is working fine but I'm expecting also xml.
Also,
foreach( $response as $obj ):
$output .= '<pre>' . htmlspecialchars( print_r($obj, true) ) . '</pre>';
endforeach;
display anything and give warning as a
Warning: Invalid argument supplied for foreach()
All curl-getinfo functions work well. How can I reach my actual xml data?
That's the print_r($response) output
HTTP/1.1 200 OK Cache-Control: no-cache, no-store, must-revalidate Expires: Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie: JSESSIONIDSSO=55B8651BB47863C99C8B0450C61A84E2; Path=/; Secure; HttpOnly Set-Cookie: JSESSIONID=1BD1E6EB0CF6ED2D4CA6FCF019216431; Path=/ers/; Secure; HttpOnly Pragma: no-cache Date: Sat, 11 Apr 2015 13:24:11 GMT Content-Type: application/vnd.com.cisco.ise.ers.searchresult.1.0+xml;charset=utf-8 Content-Length: 1880 Server:
Kind Regards
Related
I'm trying to create a curl PUT request. However, for some reason the json data doesn't get send to the api server.
public function sendRequest($endpoint, $method, $params = [], $data = null)
{
$curl = curl_init();
$url = $this->host . "/" . $endpoint . "?" . http_build_query($params);
$data = array(
'ItemCode' => '3505180',
'SearchCode' => '123456',
);
$data_string = json_encode($data);
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_HTTPGET, 1);
break;
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);
if ($data) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
}
break;
default:
break;
}
curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:51290');
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'X-ApiKey: ' . $this->apiKey,
'administration: ' . $this->administration,
'Content-Type: application/json'
));
$result = curl_exec($curl);
if(curl_errno($curl))
{
$result = 'Curl error: ' . curl_error($curl);
}
curl_close($curl);
return $result;
This is how I use the sendRequest function:
public function updateItem($item)
{
$this->sendRequest("api/Item", "PUT", [], "some json data should go here");
}
If I look up the request in Fiddler, the JSON body or raw body is empty. This is the raw data:
PUT http://appsrv:889/api/Item HTTP/1.1
Host: appsrv:889
Accept: */*
Proxy-Connection: Keep-Alive
X-ApiKey: xxxxx
administration: 002
Content-Type: application/json
Content-Length: 44
Expect: 100-continue
I get the following as result:
HTTP/1.1 408 Request body incomplete
Date: Wed, 17 Aug 2022 07:18:01 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
Cache-Control: no-cache, must-revalidate
Timestamp: 09:18:01.979
The request body did not contain the specified number of bytes. Got 0, expected 44
What could be wrong here?
I'm trying to build a custom accounting report using the PayPal NVP API that will get all transactions for a specific date range.
My code:
$headers = array(
'USER' => $production_user,
'PWD' => $production_pass,
'SIGNATURE' => $production_sig
);
$nvp = array(
'METHOD' => 'TransactionSearch',
'TRANSACTIONCLASS' => 'RECEIVED',
'STARTDATE' => '2016-12-01T00:00:00Z',
'ENDDATE' => '2016-12-31T00:00:00Z'
);
$request_url = "https://api-3t.paypal.com/nvp?".http_build_query($nvp);
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, $headers);
curl_setopt($curl, CURLOPT_POST, 1);
$result = curl_exec($curl);
$result = explode("&", $result);
foreach($result as $f=>$v){
$t = explode("=", $v);
echo $t[0]." => ".urldecode($t[1]);
echo "<br>";
}
Here is what gets printed:
HTTP/1.1 200 OK Date: Fri, 10 Feb 2017 19:51:20 GMT Server: Apache X-PAYPAL-OPERATION-NAME: X-PAYPAL-API-RC: 10001 Connection: close Cache-Control: max-age => 0, no-cache, no-store, must-revalidate Pragma: no-cache HTTP_X_PP_AZ_LOCATOR: slcb.slc Paypal-Debug-Id: 484a759b46e4a Set-Cookie: X-PP-SILOVER
CORRELATIONID => some_random_characters
ACK => Failure
L_ERRORCODE0 => 10001
L_SHORTMESSAGE0 => Internal Error
L_LONGMESSAGE0 => Timeout processing request
Any assistance with this issue would be greatly appreciated!
You are using a post request and have not post data.
I do not know what PayPal wants to see but I'm guessing it's not what you are sending.
Some things to try:
If you need to pass the USER, PWD, and SIGNATURE in the Request Header do it like this:
$request = array();
$request[] = "USER: $production_user";
$request[] = "PWD: $production_pass";
$request[] = "SIGNATURE: $production_sig";
curl_setopt($ch, CURLOPT_HTTPHEADER, $request);
If the $nvp parameters need to be post data, try this:
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvp);
The $nvp can be passed as a query string in the post data also.
$query = http_build_query($nvp);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
The difference is the Content-Type.
The first method:
Content-Type: application/x-www-form-urlencoded
The second method:
Content-Type: multipart/form-data
To help in trouble shooting it would be good to see both the request and response header.
Use these options to get the headers:
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
The Request Header will be in the 'curl_getinfo()'
curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
var_export($info);
The above gives lots of other details of the request. If you only want to see the header:
$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
To get the response header:
$result = curl_exec($ch);
$skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$response = substr($result ,0,$skip);
$result = substr($result ,$skip);
I am trying to send a PATCH request through cURL and i get this response:
HTTP/1.1 400 Bad Request Server: nginx Date: Fri, 01 Apr 2016 09:16:03 GMT Content-Type: application/problem+json Content-Length: 198 Connection: keep-alive X-Powered-By: PHP/5.6.19 {"type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html","title":"Internal Server Error","status":500,"detail":"setValidationGroup() expects a list of valid input names; \"\" was not found"}
My code:
sendData("2016-10-01", "2016-10-02", "1234");
function sendData($from, $to, $property){
$data = array(
"from" => $from,
"to" => $to,
"booking_id" => 3
);
$data = json_encode($data);
echo $data . "<br>";
$url = "https://api.urlhost.com/property/".$property."/avail";
echo $url. "<br>";
$headers = array('Authorization: Basic dGVhQGJsdW1lbnJpdmllcmEuOIT6Qmx1bQVucm17aAKyzTtyfw==','Content-Type: application/json-patch+json');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, true);
$response = curl_exec($curl);
echo ($response) . PHP_EOL;
//print_r(curl_getinfo($ch));
curl_close($curl);
}
When i echo the data and url i get these:
{"from":"2016-10-01","to":"2016-10-02","booking_id":3}
https://api.urlhost.com/property/1234/avail
But still is giving me this error. Any suggestions why this might happen?
I am trying to communicate with anREST API using cURL and PHP. But, I am getting an issue from the API and I need to be able to see my HTTP request in plain text where I can analyses it and correct it.
I tried the following to write my request to a file
$file = fopen('request.txt', 'w');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $file);
But this does not show me the JSON data.
Here is what I get in the request.txt file
* Hostname servername was found in DNS cache
* Trying INTERNAL IP...
* Connected to servername (INTERNAL IP) port 8018 (#0)
> PUT /icws/1163386002/messaging/subscriptions/queues/blahblah HTTP/1.1
Host: servername:8018
Accept: */*
ININ-ICWS-CSRF-Token: WAhtYWxoYXlla1dBY2GHSDMNDFtjMDcwZmIyYy1mguc4LTQ3YjEtODgzMy1iOTBkM2ZhYWHfoyNmYTlYCjEwLjAuNC4xNjA=
ININ-ICWS-Session-ID: 1163386002
Cookie: icws_1163386002=232sggsdfgdabe-404c-8d8c-12345dfgdfg
Content-Length: 156
Content-Type: application/x-www-form-urlencoded
* upload completely sent off: 156 out of 156 bytes
< HTTP/1.1 500 Internal Server Error
< Cache-Control: no-cache, no-store, must-revalidate
< Pragma: no-cache
< Expires: 0
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Credentials: true
< Content-Type: application/vnd.inin.icws+JSON; charset=utf-8
< Date: Tue, 12 May 2015 17:52:52 GMT
< Server: HttpPluginHost
< Content-Length: 90
<
* Connection #0 to host servername left intact
I would like to see the JSON string in plain text.
Here is how I am doing my cURL call using PHP
private function _processRequest($method, $uri, $data = false, $header = NULL, &$httpRespond = array(), &$httpCode = NULL)
{
$ch = curl_init();
$url = $this->_baseURL . $uri;
if(
($method == 'POST' || $method == 'PUT')
&& $data
){
$jsonString = json_encode( $data );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $jsonString );
}
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, true);
} elseif( $method == 'PUT'){
//curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
} else {
if ($data){
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
//disable the use of cached connection
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
//return the respond from the API
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//return the HEADER respond from the API
curl_setopt($ch, CURLOPT_HEADER, true);
//add custom headers
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
//enable SSL
if( $this->_protocol == 'https' ){
curl_setopt($ch, CURLOPT_CAINFO, $this->_cainfo);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
}
//set the URL
curl_setopt($ch, CURLOPT_URL, $url);
$file = fopen('request.txt', 'w');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $file);
$respond = curl_exec($ch);
//throw cURL exception
if($respond === false){
$errorNo = curl_errno($ch);
$errorMessage = curl_error($ch);
throw new ApiException($errorMessage, $errorNo);
}
list($header, $body) = explode("\r\n\r\n", $respond, 2);
$httpRespond = $this->_http_parse_headers($header);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result = json_decode($body, true);
return $result;
}
How do I see the entire HTTP request in a plain text?
You can use Fiddler (http://www.telerik.com/fiddler) to see your complete request/response in plain text and to test your REST API as well.
Also, you can use Wireshark (https://www.wireshark.org/) applying a HTTP filter.
My recommendation is Fiddler, I use it a lot to test and debug my REST API.
Hope this helps
Running Out Of Sanity
I have looked high and low and lost a bit of my life and a lot of my sanity trying to return a cURL POST request. Everything works fine except I cannot remove the headers. Oh yes I have tried
curl_setopt($ch, CURLOPT_HEADER, false);
What worse is that when I try
$headerLength = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
I get a return of 25 which is completely wrong. Please help I am at my wits end with this one.
So I call this method
$service = new RestfulService($Url1);
$response = $service->request('', 'POST', $tokenXml, null,
array(CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING =>'UTF-8'));
Which in turn calls (using SilverStripe framework)
public function curlRequest($url, $method, $data = null, $headers = null, $curlOptions = array()) {
$ch = curl_init();
$timeout = 5;
$sapphireInfo = new SapphireInfo();
$useragent = 'SilverStripe/' . $sapphireInfo->Version();
$curlOptions = $curlOptions + (array)$this->config()->default_curl_options;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
if(!ini_get('open_basedir')) curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
//include headers in the response
curl_setopt($ch, CURLOPT_HEADER, true);
// Add headers
if($this->customHeaders) {
$headers = array_merge((array)$this->customHeaders, (array)$headers);
}
if($headers) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Add authentication
if($this->authUsername) curl_setopt($ch, CURLOPT_USERPWD, $this->getBasicAuthString());
// Add fields to POST and PUT requests
if($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
} elseif($method == 'PUT') {
$put = fopen("php://temp", 'r+');
fwrite($put, $data);
fseek($put, 0);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_INFILE, $put);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
}
// Apply proxy settings
if(is_array($this->proxy)) {
curl_setopt_array($ch, $this->proxy);
}
// Set any custom options passed to the request() function
curl_setopt_array($ch, $curlOptions);
// Run request
$rawResponse = curl_exec($ch);
if (curl_error($ch)) var_dump(curl_error($ch));
$response = $this->extractResponse($ch, $rawResponse);
curl_close($ch);
return $response;
}
When I dump the response, the remove header command only removes the first few characters. Like so...
object(RestfulService_Response)[1065]
protected 'simpleXML' => null
protected 'cachedResponse' => boolean false
protected 'statusCode' => int 100
protected 'statusDescription' => string 'Continue' (length=8)
protected 'headers' =>
array (size=0)
empty
protected 'body' => string 'ontrol: no-cache
Pragma: no-cache
Content-Length: 3593
Content-Type: application/soap+xml; charset=utf-8
Expires: Fri, 20 Sep 2013 01:14:14 GMT
Server: Microsoft-IIS/7.5
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
X-XSS-Protection: 0
PPServer: PPV: 30 H: CO1IDOLGN62 V: 0
Date: Fri, 20 Sep 2013 01:15:13 GMT
Connection: close
�<?xml version="1.0" encoding="utf-8" ?><S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envel
Has it got anything to do with the strange character before the
Update: I have checked this code on my colleagues computer, he doesn't have any problems. I am running WAMP my colleague is on a MAC, could there be any set up issues? I have downloaded the most recent curl.dll and added it to my php library, still no cigar.
Any ideas???
In my case the encoding was incorrect I needed to add the following option
curl_setopt($ch, CURLOPT_SSLVERSION, 3)
Works fine now