How to get response using cURL in PHP
Just use the below piece of code to get the response from restful web service url, I use social mention url.
$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
How to get response from server using curl in php
a http connection that never close? don't think php's curl bindings are suitable for that. but you could use the socket api,
$sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_set_block($sock);
socket_connect($sock,"192.168.1.4",1818);
$data=implode("\r\n",array(
'GET /online?user=dneb HTTP/1.0',
'Host: 192.168.1.4',
'User-Agent: PHP/'.PHP_VERSION,
'Accept: */*'
))."\r\n\r\n";
socket_write($sock,$data);
while(false!==($read_last=socket_read($sock,1))){
// do whatever
echo $read_last;
}
var_dump("socket_read returned false, probably means the connection was closed.",
"socket_last_error: ",
socket_last_error($sock),
"socket_strerror: ",
socket_strerror(socket_last_error($sock))
);
socket_close($sock);
or maybe even http fopen,
$fp=fopen("http://192.168.1.4:1818/online?user=dneb","rb");
stream_set_blocking($fp,1);
while(false!==($read_last=fread($fp,1))){
// do whatever
echo $read_last;
}
var_dump("fread returned false, probably means the connection was closed, last error: ",error_get_last());
fclose($fp);
(idk if fopen can use other ports than 80. also this won't work if you have allow_url_fopen
disabled in php.ini)
Getting HTTP code in PHP using curl
First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
return false;
}
Make sure you only fetch the headers, not the body content:
@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body
For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):
- How can I check if a URL exists via PHP?
As a whole:
$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo 'HTTP code: ' . $httpcode;
Retrieve the response code from header cURL php
I think you need to pass $curl
to the curl_getinfo
method, not the $response
$response = curl_exec($curl);
$theInfo = curl_getinfo($curl);
$http_code = $theInfo['http_code'];
You can see the doco here.. https://www.php.net/manual/en/function.curl-getinfo.php
PHP - Get specific values from curl response
<?php
$url = 'hxxp://domain.com/univ/v8?q=tas+wanita';
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$r=curl_exec($ch);
curl_close($ch);
$data = json_decode($r, true);
$i=0;
foreach($data['data'] as $val) {
foreach($val['items'] as $key => $item) { //it may give warning because empty array (i.e items = [].
$keywords[$i] = $item['keyword']; // this will store keyword in $keywords array.
$i++;
}
}
$message = '<html><body>';
$message .= '<table border="1" cellpadding="10">';
$message .= "<tr><th><strong>Sr. No.:</strong> </th><th>
<strong>Keyword</strong> </th></tr>";
foreach ($keywords as $key => $value) {
$message .= "<tr><td>".$key." </td><td>" .$value. "</td></tr>";
}
$message .= "</table>";
$message .= "</body></html>";
echo $message;
?>
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialised variable.
PHP Curl get server response
$ch=curl_init("www.example.org/example.pdf");
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result=curl_exec($ch);
curl_close($ch);
with curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
it will return the result on success, FALSE on failure.
with curl_setopt($ch,CURLOPT_RETURNTRANSFER,false);
it will return TRUE on success or FALSE on failure.
Moreover, for file not found
:
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($http_code == 404)
{
/*file not found*/
}
Trying to get response using curl exec
The curl
runs on the server and not in the client. Any HTTP command issued by curl will use the server IP as the requester.
Depending on the service you are invoking, probably you can use the
X-Forwarded-For
HTTP header used in the Internet Proxies.$URL = "https://drive.google.com/get_video_info?docid=".$_SERVER["QUERY_STRING"];
$curl = curl_init();
// set the command as requested by the client IP
curl_setopt($curl,CURLOPT_HTTPHEADER,array('X-Forwarded-For: '. $_SERVER['REMOTE_ADDR']));
curl_setopt($curl, CURLOPT_URL, $URL);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 2);
$response_data = urldecode(urldecode(curl_exec($curl)));
The service you are invoking may use the header to determine the ip of the originator. Using the X-Forwarded-For
will not work with all the services and server-side frameworks.
- If you want to make a request from the client, probably you need to use javascript (e.g. by using
XMLHttpRequest
or some functions in JQuery or Angular) to make the request.
You may check:
- more on obtaining the client IP in PHP, for instance when the client is behind a proxy or a
X-Forwarded-For
: Get the client IP address using PHP - more about using
X-Forwarded-For
with curl: How can I spoof the sender IP address using curl?
Post data and retrieve the response using PHP Curl?
You'll have to set the CURLOPT_RETURNTRANSFER option to true.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
The response to your request will be available in the $result variable.
Unable to get the json response from API using curl in PHP
Perhaps the following might help - as the endpoint is https you ought to have additional options set in the curl request function to deal with SSL. The curl function below is a simplified version of something I use frequently
<?php
/* https://stackoverflow.com/questions/55339967/unable-to-get-the-json-response-from-api-using-curl-in-php */
/* jsonplaceholder.typicode.com api experiments */
if( isset( $_GET['todoid'] ) ){
$id=filter_input( INPUT_GET, 'todoid', FILTER_SANITIZE_NUMBER_INT );
/* utility to quickly display data in readable fashion */
function pre( $data=false, $header=false, $tag='h1' ){
if( $data ){
$title = $header ? sprintf('<'.$tag.'>%s</'.$tag.'>',$header) : '';
printf('%s<pre>%s</pre>',$title,print_r($data,1));
}
}
/* basic curl request helper */
function curl( $url ){
/* set an appropriate path to YOUR cacert.pem file */
$cacert='c:/wwwroot/cacert.pem';
$curl=curl_init();
if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
}
curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
$res=(object)array(
'response' => curl_exec( $curl ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
curl_close( $curl );
return $res;
}
function callapi( $id ){
$url=sprintf( 'https://jsonplaceholder.typicode.com/todos/%s',$id );
return curl( $url );
}
/* call the api */
$res = callapi( $id );
/* process response data */
if( $res && $res->info->http_code==200 ) {
/* to debug */
pre( $res->response, 'Response data' );
/* live */
#exit( $res->response );
}
}
?>
Example output:
Response data
{
"userId": 2,
"id": 23,
"title": "et itaque necessitatibus maxime molestiae qui quas velit",
"completed": false
}
Related Topics
Retrieving Multiple Result Sets With Stored Procedure in PHP/MySQLi
Fatal Error: Call to Undefined Function Mb_Detect_Encoding()
How to Find the Dates Between Two Specified Date
Strtotime With Different Languages
Update Fee Dynamically Based on Radio Buttons in Woocommerce Checkout
What Is the Syntax For Accessing PHP Object Properties
MySQLi Bind Param With an Array For In
Inserting Data to Table (MySQLi Insert)
Gcm Notifications Not Receiving When App Is in Background Mode in Ios
PHP Install Ssh2 on Windows Machine
Ternary Operator and String Concatenation Quirk