so I'm trying to make a small API here. I'll be only sending some information via header (get params) and I'm not using any POST parameters.
Here's the code that I've written.
function sendSMS($message, $number)
{
/*** Connection Params **/
/*** Build the request parameters ***/
$service="sms_api_call_receiver.php";
$number="1212";
$message="asas";
$result = sendPost("https://www.domain.com/smsapp/" . $service . "?message=".urlencode($message)."&number=".$number);
return $result;
}//function
function sendPost($Url)
{
// Initialisation
$ch=curl_init();
// Set parameters
curl_setopt($ch, CURLOPT_URL, $Url);
// Return a variable instead of posting it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Active the POST method
//curl_setopt($ch, CURLOPT_POST, 1) ;
// Request
//curl_setopt($ch, CURLOPT_POSTFIELDS, $strRequest);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// execute the connexion
$result = curl_exec($ch);
// Close it
//return curl_error($ch);
curl_close($ch);
return $result;
}
On the receiver file, I have this code :-
if(isset($_GET['message']))
{
return true;
}
else
{
return "12212";
}
But when I test, the output I get is :-
string '' (length=0)
What am I doing wrong here?
Troubleshooting
I tried to see if curl_error returned anything. But I could see nothing.
Any suggestions here would be helpful.
Are you sure there is something wrong there? If $_GET['message'] is set (in your test example it is) the script (sms_api_call_receiver.php) returns true and stops the execution.
Because it is HTTP request, and the response is empty, you'll get as result in the sendSMS() function string with 0 length.
to get something as response in sendSMS you need to print in sms_api_call_receiver.php instead of using return
Related
I have the following code that makes an API call to a URL. The response is in json format.
When the response data is received, I want to further process the data using another function and NOT display the data in the console (I want to display only the final processed output). But currently, the response from the API call is being displayed in the console along with the final processed output.
The processed final data will be saved in $processedData variable.
<?php
function getDataFromApi(){
$url = 'https://www.myurl.com/data.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function processData($data){
/**
* Do the processing and save processed data in $processedData variable.
*/
// Finally display the data
echo $processedData;
}
$result = getDataFromApi();
processData($result);
How do I NOT display the intermediate cURL resplonse but only the final response?
you are passing data variable but echoing the process data variable
function getDataFromApi(){
$url = 'https://www.myurl.com/data.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
$processdata = processData($data);
return $processdata;
}
function processData($data){
/**
* Do the processing
*/
// Finally display the data
echo $data;
}
echo $getDataFromApi();
I found answer to my question myself so I am posting it here so that it can help others.
My code as stated in the question, by default executes the curl request and prints the output in the screen.
In the current form, the line $result = curl_exec($ch); will execute the cURL request and returns true or false based on whether the request was successful or not. So, the $result variable will NOT hold the response data (as opposed to what I assumed earlier), but either true or false.
In order not to display the response and save it in a variable (and pass it to another function), CURLOPT_RETURNTRANSFER option needs to be set to true as follows:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This line instructs cURL to Return the response as a string instead of outputting it to the screen.
The final code would be as follows:
<?php
function getDataFromApi(){
$url = 'https://www.myurl.com/data.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function processData($data){
/**
* Do the processing and save processed data in $processedData variable.
*/
// Finally display the data
echo $processedData;
}
$result = getDataFromApi();
processData($result);
Use below
function processData($data){
/** * Do the processing */
// Finally display the data echo $data;
}
I wanted to try to get data from a JSON string which is loaded from another page. I currently have used Curl to get the data from the webpage but I can't acces the data in it.
I've already tried:
var_dump(json_decode($result->version, true));
var_dump(json_decode($result[3][0]["date"], true));
But this does't seem to work as it always returns NULL
$url="https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
First decode the JSON, then get the properties you want. Like this:
$yourObject = json_decode($result);
var_dump($youObject->version);
this is working for me.
<?php
$url = "https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
$result = curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
$data = json_decode($result);
//echo $data->data[0]['date'];
echo "<pre>";
print_r($data->data[0]->date);
}
?>
if you want to get date of all index then try this in loop.
Firstly if your using GET there is no need to use CURL,
$result = file_get_contents(https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201);
Will work just as well without any of the overhead. I suspect that your CURL isn't returning the page content so using file_get_contents() will fix it.
I have a function that will give some results.
Suppose anyone connecting to my url with CURL and trying to get result, how should I return result for the CURL.
I need to pass JSON in return of that CURL
Is that I need to echo the result or return?
I tested with,
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $myURL); // here passed my url
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$result = curl_exec($ch);
$info = curl_getinfo($ch);
// close cURL resource, and free up system resources
curl_close($ch);
In the url I am doing this,
$model = new Application_Model_Listings();
$result['communtityDetails'] = $model->getCommunityWidgetDetails();
$result = json_encode($result['communtityDetails']);
// return $result; or echo $result ??
CURL connection is happening, but result is not getting.
How should I pass this result??
:)
I'm trying to send an XML using curl but not as post parameter. what I mean is this.
for example.
the receiving side of that XML won't be able to recieve the XML using $_POST variable.
he will need to use the following code:
$xmlStr=null;
$file=fopen('php://input','r');
$xmlStr=fgets($file);
I want to be able to send an xml string using curl via https.
so the following would be wrong:
public static function HttpsNoVerify($url,$postFields=null,$verbose=false) {
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($postFields !=null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if ($verbose) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
because here i can use HttpsNoVerify($url,array('xml_file'=>'xml..')); and that
will paste it as post parameter. and i want it as post output.
so please I hope i explained myself properly and I explained exactly what I don't want to do.
how can I do what i want to do?
thanks! :)
kfir
Just directly pass the xml string as second parameter instead of an associative array item,
HttpsNoVerify($url, 'xml ..');
This will eventually call
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml ...");
Which will be put in php://input for the remote server.
I have a slight issue whereby the API I'm using for part of my service uses a rsp stat to handle the success / error messages in XML.
So we use a form to post it data and it returns the data like the following example:
<rsp stat="ok">
<success msg="accepted" transactionid="505eeb9c43969d4919c0a6b3f7a4dfbb" messageid="a92eff8d65cf48e9c6e96702a7b07400"/>
</rsp>
The following is most of the script used :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
// ToDo: Replace the placeholders in brackets with your data.
// For example - curl_setopt($ch, CURLOPT_UsERPWD, 'SMSUser:PassW0rD#');
curl_setopt($ch, CURLOPT_USERPWD, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
$xml = curl_exec($ch);
if (curl_error($ch)) {
print "ERROR ". curl_error($ch) ."\n";
}
curl_close($ch);
print_r($xml);
The only problem is that when it is parsed and displayed via the print_r command , it only displays via source code for some strange reason and we have no idea how to display it via the page
Basically we would like a system whereby if rsp stat="ok" then "Sent" else "unsent".
Well, a simple way could be:
if (strpos($xml, 'stat="ok"') !== false) {
echo "sent";
} else {
echo "unsent";
}
http://codepad.org/pkzsfsMk
This would replace print($xml);.
Put that code in a function, and have the function return your $xml.
Assuming you had a function called getRspStat() you could just do like:
echo getRspStat();
If you do something like that:
(see also on CodePad.org)
function xmlRequestWasSuccessful($xml) {
$result = simplexml_load_string($xml);
$result = (string)$result['stat'];
if ($result == 'ok') {
return true;
} else {
return false;
}
}
$xml = '<rsp stat="ok">
<success msg="accepted" transactionid="505eeb9c43969d4919c0a6b3f7a4dfbb" messageid="a92eff8d65cf48e9c6e96702a7b07400"/>
</rsp>';
$stat = xmlRequestWasSuccessful($xml);
you will receive 'true' boolean in the result ($stat variable). Adapt it to support the case when there is an error. Since no details on how it looks when error occurs, this is how you can do it now:
if ($stat) {
// do something on success ('sent' something)
} else {
// do something on success (display 'unsent' message for example)
}