Calling a python script in Cakephp - php

I wrote a service class called search_categorization_service.php. Now I am making a call to python scrpt in this class
class SearchCategorizationService
{
function searcher($query)
{
$tmp=passthru("python serverscript1.py $query");
ob_start();
$out=ob_get_contents();
echo print_r($out,true);
}
}
but i dont get any output on the browser. i tried returning it to a controller class and printing the output but it just wont work.any help wud be appreciated. is it an issue with cakephp? because the same application works fine in normal php.

Try moving ob_start() above $tmp=passthru("python serverscript1.py $query");. It appears nothing is being output after the output buffer is started.
<?php
class SearchCategorizationService
{
function searcher($query)
{
ob_start();
$tmp=passthru("python serverscript1.py $query");
$out=ob_get_contents();
echo print_r($out,true);
}
}
?>

Related

Can't create an instance of my class

i'm sorry if this is a noob question, but i can't figure it out.
I have a .php file containing a class:
<?php
class Visitors
{
public function greetVisitor()
{
echo "Hello<br />";
}
function sayGoodbye()
{
echo "Goodbye<br />";
}
}
?>
In another php file containing mostly HTML, i try to create an instance of this class and call the function greetVisitor :
<div class="map col-md-4">
<?php
$test = new Visitors();
$test->sayGoodbye();
?>
</div>
For some reason this isn't displaying when i look in my browser. Any ideas ?
tried doing a var_dump, but nothing is showing
thanks
Before you create an object of the class Visitors you need to include/require the php file where that class is defined, like this:
By the way, do not use the parenthesis since you are not sending any values
and yes you are a newbie!

return method response after it executes to the parent method

I am using xmlprc server in codeignter for web services . the flow of my application is that i need to pass parameters to the xmlrpc server method which then should invoke another controller class method which would set the parameters in a js function and that js method is invoked concurrently .
The problem i am facing is in calling the controller class method from the xmlrpc server method and getting the response to the server parent method which could then be fetched using xmlhttprequest.
my xmlrpc server method is:
function update_p($request) {
$parameters = $request->output_parameters();
$this->session->set_userdata(array("portfolio" =>$parameters['0']["portfolio"]));
$this->session->set_userdata(array("filter" =>$parameters['0']["filter"]));
$url = base_url("ControllerClass/update_p?".$parameters['0']["portfolio"].'&'.$parameters['0']["filter"]);
header("Location: $url");
$xml_rpc_rows=array("portfolio"=>$parameters['0']["portfolio"],"filter"=>$parameters['0']["filter"]);
$response = array(
$xml_rpc_rows,
'struct');
$this->xmlrpc->send_response($response);
}
Controller Class method:
public function update_p() {
$loginid = $this->session->userdata('loginid');
if(!isset($loginid)){
die;
}
error_reporting(E_ERROR);
if (time()>$this->session->userdata('expire')) { redirect("/dashboard/logout?expired=Y","location",401); die; }
$out='';
$request="USER ".$loginid.($this->session->userdata('isMobile')?"#mobile":"")."\n";
if(isset($_GET["portfolio"])) {
$portfolio=trim($_GET["portfolio"]);
$request.='ECHO "LISTP":'."\nLISTP0 #".$portfolio;
if(isset($_GET["filter"])) {
$filter=trim($_GET["filter"]);
$request.=" -".$filter;
}
if(isset($_GET["sort"])) {
$sort=trim($_GET["sort"]);
if ($sort>=1024) $request.=" -s".($sort&1023);
else $request.=" -S".$sort;
}
$ph = isset($_GET["first"]);
if ($ph) {
$this->load->model('Model');
$resultArray = $this->Model->getData($this->session->userdata('loginid'),$this->session->userdata('isMobile')?'mobile':'default','listp');
$request.=" ".$resultArray[0]['listp'];
}
$request.="\nECHO ,\n";
if(isset($_GET["watch"])) {
$portfolio=trim($_GET["watch"]);
if ($ph)
$resultArray = $this->Model->getData($this->session->userdata('loginid'),$this->session->userdata('isMobile')?'mobile':'default','watch');
$request.='ECHO "watchl":'."\nLISTP1 #".$portfolio." -WL ".($ph?$resultArray[0]['watch']:"")."\n";
$request.='ECHO ,"watchs":'."\nLISTP1 #".$portfolio." -WS\nECHO ,\n";
}
}
$request.="RISk\nECHO ,\nPnL\n";
if ($result=$this->getData($request."BYE\n")) {
if (result!='') $out=$result."\n";
}
ob_start('ob_gzhandler');
echo "{".$out."}";
ob_end_flush();
}
I can not figure out how to get the controller method result in the server method anyone who can shed some light on this would be much appreciated .
Thankyou.
Your controller method is expecting to output the result as an echo statement, which goes to the browser, rather than to return it in a variable. This means your server function is having to try to capture the output of that controller method. That setup is much more awkward and prone to error.
Unless you also need to access your update_p method directly from a browser you should change your Controller to simply return the output which really means this controller is more of a library and should probably go in the libraries folder. You will need to change your controller code a bit so that instead of grabbing the parameters from $_GET you are getting them as arguments, which in CodeIgniter is what you should be doing anyway.
So from the end of update_p just do this instead of your echo:
return "{".$out."}";
Then in your xmlrpc server do this:
$controller = new ControllerClass();
$result = $controller->update_p($parameters['0']["portfolio"], $parameters['0']["filter"]);
Then do whatever you want with your $result.

How do I get the ob_start() callback to fire when getting the contents of the buffer?

I've got a script that runs a custom email obfuscation class's Obfuscate() function on the content before displaying it, as follows:
ob_start(array($obfuscator, "Obfuscate"));
include('header.php');
print($html);
include('footer.php');
ob_end_flush();
That all works great. However, I've completely rewritten my view architecture, so I need to run the email obfuscation from within a class function and return that string (which then gets echoed). I initially rewrote the above as:
ob_start(array($this->obfuscator, "Obfuscate"));
include('header.php');
echo($this->content);
include('footer.php');
$wrappedContent = ob_get_contents();
ob_end_clean();
Unfortunately, the $this->obfuscator->Obfuscate() callback is not being fired. I have since learned that ob_get_contents() does not fire the callback, but have tried ob_get_clean() & ob_get_flush() to no avail as well.
So, how can I get the contents of the buffer after the callback has been fired?
Of course, I was overlooking the fact that the only reason to use the callback on ob_start() was because I wanted to run Obfuscate() on the content before it was flushed, but if I'm getting that content back I don't need to run a callback! So, not using a callback and just running ob_get_clean()'s results through Obfuscate() does what I wanted. Doh!
ob_start();
include('header.php');
echo($this->content);
include('footer.php');
return $this->obfuscator->Obfuscate(ob_get_clean());
Change
ob_end_clean();
with
ob_clean()
Will trigger .
This is the code eg I tried
<?php
class Obfuscate {
public function __construct()
{
}
public function getObfuscate()
{
return "obfuscate";
}
}
class Example
{
public function hello( $obfuscator )
{
ob_start(array( $obfuscator, 'getObfuscate' ));
include('header.php');
echo "Thi is a content ";
include('footer.php');
$wrappedContent = ob_get_contents();
ob_clean();
}
}
$obfuscator = new Obfuscate();
$example = new Example;
$example->hello($obfuscator);
ob_clean();

PHP include/require within a function

Is it possible to have return statements inside an included file that is inside a function in PHP?
I am looking to do this as I have lots of functions in separate files and they all have a large chunk of shared code at the top.
As in
function sync() {
include_once file.php;
echo "Test";
}
file.php:
...
return "Something";
At the moment the return something appears to break out of the include_once and not the sync function, is it possible for the included file's return to break out?
Sorry for the slightly odly worked question, hope I made it make sense.
Thanks,
You can return data from included file into calling file via return statement.
include.php
return array("code" => "007", "name => "James Bond");
file.php
$result = include_once "include.php";
var_dump("result);
But you cannot call return $something; and have it as return statement within calling script. return works only within current scope.
EDIT:
I am looking to do this as I have lots
of functions in separate files and
they all have a large chunk of shared
code at the top.
In this case why don't you put this "shared code" into separate functions instead -- that will do the job nicely as one of the purposes of having functions is to reuse your code in different places without writing it again.
return will not work, but you can use the output buffer if you are trying to echo some stuff in your include file and return it somewhere else;
function sync() {
ob_start();
include "file.php";
$output = ob_get_clean();
// now what ever you echoed in the file.php is inside the output variable
return $output;
}
I don't think it works like that. The include does not simply put the code in place, it also evaluates it. So the return means that your 'include' function call will return the value.
see also the part in the manual about this:
Handling Returns: It is possible to
execute a return() statement inside an
included file in order to terminate
processing in that file and return to
the script which called it.
The return statement returns the included file, and does not insert a "return" statement.
The manual has an example (example #5) that shows what 'return' does:
Simplified example:
return.php
<?php
$var = 'PHP';
return $var;
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
?>
I think you're expecting return to behave more like an exception than a return statement. Take the following code for example:
return.php:
return true;
?>
exception.php:
<?php
throw new exception();
?>
When you execute the following code:
<?php
function testReturn() {
echo 'Executing testReturn()...';
include_once('return.php');
echo 'testReturn() executed normally.';
}
function testException() {
echo 'Executing testException()...';
include_once('exception.php');
echo 'testException() executed normally.';
}
testReturn();
echo "\n\n";
try {
testException();
}
catch (exception $e) {}
?>
...you get the following output as a result:
Executing testReturn()...testReturn() executed normally.
Executing testException()...
If you do use the exception method, make sure to put your function call in a try...catch block - having exceptions flying all over the place is bad for business.
Rock'n'roll like this :
index.php
function foo() {
return (include 'bar.php');
}
print_r(foo());
bar.php
echo "I will call the police";
return array('WAWAWA', 'BABABA');
output
I will call the police
Array
(
[0] => WAWAWA
[1] => BABABA
)
just show me how
like this :
return (include 'bar.php');
Have a good day !

calling a class with ajax

I need some help with this please
I can't get a handle on it.
The problem is that I want to call a class method, in this case with static methods with an ajax call.
I have put the helper class in the same folder as the script that is called by ajax for easy referencing and try to include it.
Could it be that my refencing is wrong?
If I make a testclass in the file that is called by ajax I can get a response.
class test {
public function testit() {
return "testit";
}
}
$t=new test;
$check= $t->testit();
switch($action) {
case "someaction":
$data = array();
$file='input_helper.php';
include_once $file;
$check= input_helper::ip_address();
header('Content-type: application/json');
$output = array(
"check" => $check,
"user" => $data
);
echo json_encode($output);
exit(0); // Stop script.
break;
//...
EDIT FOR MORE CLARIFICATION
The action is set as a post variable in the ajax function
The ajax url points to a script that takes some action based on the posted variables
thanks, Richard
<?php
include_once 'your/class/path/helper_class.php';
.
.
at the top of your PHP page should do it. it really has nothing to do with AJAX. If your PHP file is in fact being hit on the callback, then that should work properly.
Optionally, to test that your path is correct, if you do:
<?php
require 'your/class/path/helper_class.php';
.
.
If the path is not correct PHP will throw a fatal E_ERROR level error.

Categories