rest echo vs return in GET - php

I am a newbie in php and rest and I'm trying to understand what is going on in my API when using echo vs return....
I've tried to get down to the simplest possible scenario to isolate an issue of my rest API not returning any value, so here is goes:
I have a test.php file on my server with following content:
<?php
if(function_exists($_GET['t1'])) {
echo $_GET['t1']();
}
else if(function_exists($_GET['t2'])) {
return $_GET['t2']();
}
function test() {
return json_encode("test...");
}
?>
I then make a simple request using, as unique header 'Content-Type: application/json`
https://www.eswys.ch/tmp/test.php?t1=test
https://www.eswys.ch/tmp/test.php?t2=test
And results are, respectively
"test..."
""
I really struggle to understand this, why is my returned value somehow "lost" - is there any explanation to this?!

Returning from a function does not actually render any content to the response. You may have seen people returning data in different frameworks but the framework is actually echoing the data for you behind the scenes.

return assigns a value to a function call (like a variable) and echo is simply output to the html page or possibly a terminal window.

Related

Get PHP response into Zapier webhook

I am connecting PipeDrive with Post Affiliate Pro (with it's API) and am using Zapier webhooks (POST). Therefore I use PHP scripts on my server in which I talk to Post Affiliate Pro. So I have variables in my PHP script which I need to return in order to use them in another webhook/or general action step. In Zapier the only variable I get when testing the step is a String with my response message (and whatever variable I put in there). But I need to get all variables on their own (I guess all in a JSON).
So my question is: How can I return variables in an HTTP POST request to make them available (in the dropdown list?) in Zapier to use them in the next webhook?
At the moment I have something like this:
if ($result->isError()) {
echo 'Error: '.$result->getErrorMessage();
} else {
//echo 'Ok: '.$result->getInfoMessage();
echo json_encode($orderID);
I am using 'echo' but I've also tried to use 'return' which didn't lead to any results. I've also tried to use json_encode to return a JSON but without luck. Or do I even need to use another Zapier step? Or am I not able to return values with a POST webhook at all? Do I need to use a "Catch Hook" webhook? I am completely new to Zapier and PHP.
Image shows just two Strings ('Text' & 'Text Transaktion') available in Zapier but no other variables
Thanks for your help!
I finally found it out by myself. I have to return one JSON, which includes everything. It's also not possible to echo anything at the same time as this would result in the output of just one string with all the values in it (like I had it before).
So something like this does the job:
if (!isset($returnValue)) {
$returnValue = new stdClass();
$returnValue->order_id = $orderID;
$returnValue->result_message = $resultMessage;
}
print_r(json_encode($returnValue));

PHP Error handler triggers when using die in outputbuffer context

im developing my PHP framework and at the moment im stuck with a strange behaviour in my error-dispatching page.
The page itself is beautiful, it catches and lists all error using a custom error-handler registered with "set_error_handler()" and can print the line, file, invoked variables and such. It even triggers multiple errors perfectly (except for fatal or syntax-errors which causes the script to hold) but still the dispatches the fatal or even syntax error in this case and even shows me, even when its a null-pointer in a template where the error is located which is beautiful and works awesome.
This system works "using set_error_handler"! The entire output (rendering html /php templates) is realised using "ob_start" and "ob_get_clean" - outputbuffer context.
Next I check if the error-handler catched any errors (will be written in an array in the error-handler's class) and if there are errors and error-display is enabled (developer mode = on) the error-dispatcher page will be displayed instead of the page's content.
However since I implemented that I have one strange behaviour which I do not want:
Whenever I use die() inside of outputbuffer context ((ob_start() ... ob_get_clean()) ) The registered error-handler method is called with an empty error-list displayed and even error_get_last() is empty, but still he triggers that damn function.
This is very disturbing as you cant use die to hold the script to test the output of certain variables which is disturbing in development and seems to be an unusual behaviour to me.
I think posting my entire code is making the thing a little bit too complicated for you to understand thatswhy I leave a little draft explaining the situation, its basically same as it looks in my classes:
//index.php
$errorList = array();
function myErrorHandler($errorType, $errorString, $errorFile, $errorLine, array $errorContext) {
global $errorList;
$errorList[] = $errorString;
}
set_error_handler("myErrorHandler");
//Here my classses and entire rest of framework is loaded...()
//Initialise output
$output = "";
//This method parses templates, it remotely close works like that...
function includeTemplate($templatePath) {
global $output;
ob_start("myErrorHandler");
include($templatePath);
$output .= ob_get_clean(); //Attach to output
}
//This method is called at the very end, it flushes the output, wether by displaying error-dispatcher or page content to be shown.
function flush() {
global $output;
if(count($errorList) > 0) {
echo implode("<br />", $errorList);
} else {
echo $output;
}
}
//Template file: registerTemplate.php
<div class="container">
<Some template output here, doesnt matter if an error occured...>
<?php die($var); ?> //<- Error rised -> Entering "myErrorHandler()" -> but why????
</div>
-> This die() above would rise an error because registerTemplate.php was somewhen parsed using includeTemplate("reigsterTemplate"); which is as located within an ob_start() context. It does not matter if an error occured before or not or even if I just place die("!"); without any invoked variable, it will riase an error.
If I put the die() before or after the include_template context, in upper scope it works as usual and the error_handler does not trigger, as it should work.
Can anyone tell me why this is happening? Thanks alot!
(Important: again this code is not realistic I know its just a draft from how the things look like very barely, dont bother with that giving me hints that this is a bad way to do things. The entire thing is perfectly object oriented and very well structured. I just made this little draft to make you guys understand in what order the methods are called and how my problem comes up because posting my code would waste me and you alot of time as it would be too huge and complex here).

PHP json_encode on a SOAP response returns array if multiple, but object if single?

I have a Windows Desktop Gadget that, for a small number of my users, suddenly stopped working a few months back. Seemed to be that they suddenly didn't like cross-domain requests (even though all servers are on our intranet here). So, I'm rewriting the thing so that it goes to a single backend server that I have a lot of control over... and its Ajax queries to the backend are set to use data Type: jsonp. Meanwhile, the php script that the gadget queries a la Ajax calls a SOAP service, gets the data back, turns it into an array, and then uses json_encode to turn it into a string and add a reference to a callback function on the Gadget / javascript side.
My problem seems to be with json_encode. If the SOAP response includes a single data record, it sends it as an object. If the SOAP response contains multiple records, it's slapping brackets around it, like an array.
Examples:
Single record:
`{
"SmeDetail": {
"SipAddress": "jane.smith#whatever.com",
"SubjectExpert": "Smith,Jane",
"SubjectMatter": "Unix"
}
}`
Multiple records:
`{
"SmeDetail": [
{
"SipAddress": "fred.flintstone#whatever.com",
"SubjectExpert": "Flintstone,Fred",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "barney.rubble#whatever.com",
"SubjectExpert": "Rubble,Barney",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "wilma.flintstone#whatever.com",
"SubjectExpert": "Flintsone,Wilma",
"SubjectMatter": "Bedrock"
}
]
}`
In the php script, a typical SOAP call goes like this:
$Service_URL = 'http://server/PROD/OurWcfService/WcfService.svc?wsdl';
$client = new SoapClient($Service_URL);
$res= $client->GetSMEDetails($params)->GetSMEDetailsResult;
and then $res is fed to this routine:
$json_data = json_encode((array)$res);
echo $_GET['callback_name'].'('.$json_data.');';
And that echo is what's fed back as the Ajax response.
I'm not sure where I even read about using this json_encode((array)$res) to do the conversion from the Soap response into an array, then the json encoded string. But I'm wondering if I'm doing something wrong here? I guess I need to make sure that single records are pushed through as an array. And I'd rather fix that the "right way" rather than do some sort of hack on the string.
Any thoughts?
I think the problem occurs cause GetSMEDetailsResult returns not array(singlerecord) but singlerecord itself.
What about checking "is SmeDetail associative"?
hint: How to check if PHP array is associative or sequential?
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($res['SmeDetail'])) $res['SmeDetail'] = array($res['SmeDetail']);
This solution is ugly but it should work.
Another way is to check "is SipAddress set":
if(isset($res['SmeDetail']['SipAddress'])) $res['SmeDetail'] = array($res['SmeDetail']);

How to return a response via php

I'm writing a php api with methods wired together by php routing, such that
dev.myphp.com/user/login?email=sdfsdf#fdfd.com&password=d514
will return a json/xml response.
However, I do not know how to return this response, even if I use json_encode or xml_encode to conver the data string.
Do I just need to uniquely echo the JSON string out?
Always try to take data using POST method not GET , untill unless you don't find it less useful in caompare to POSt.
use simply
<?Php
--- php code
return json_encode($resultdata);
?>
it would be enough.

get a JS value in php

I have a js function to return a title of a song and another one to return the artist of the same song. then I have another function which makes a string combining the name and the artist. finally I want to print that string in php.
this is my js:
function getName(){
return artist+ ", " + title;
}
and this is my php:
echo '<script>getName();</script>';
but this doesnt return anything. what am I missing??
You must still output the return value:
echo '<script>document.write(getName());</script>'; does not need jQuery, but is simple vanilla javascript.
You're not putting it on screen.
alert(getName()); would work. Same goes for $('.element').text(getName()); or something similar.
There's not a plausible way of doing this on a standard configuration. Javascript is evaluated after the PHP is. The PHP executes, then the server sends the results to the clients browser. The browser then renders that result, and THEN executes javascript. May I ask why you are doing this? It seems overly complicated. Why not just: document.write(getName());?

Categories