how to include .pl (PERL) file in PHP - php

i have two pages one in php(index.php) and another one in Perl(dbcon.pl).
basically i want my php file to show only the UI and all the data operations would be done in Perl file.
i have tried
in index.pl
<?php include("dbcon.pl");?>
<html>
<br/>PHP</br>
</html>
and dbcon.pl has
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use CGI::Simple;
my $cgi = CGI::Simple->new;
my $dsn = sprintf('DBI:mysql:database=%s;host=%s','dbname','localhost');
my $dbh = DBI->connect($dsn,root =>'',{AutoCommit => 0,RaisError=> 0});
my $sql= "SELECT * FROM products";
my $sth =$dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (my #row = $sth->fetchrow_array){
print $cgi->header, <<html;
<div> #row[0] #row[1] #row[2] #row[3] #row[4]</div>
html
}
but when i run index.php in browser it prints all the code in dbcon.pl file instead of executing it
how to overcome this problem?
note: i am running this in windows environment
is there any other way to do this?

May I ask what the problem really is? I don't see anything "special" in the Perl code, so you either:
a) Don't know how to access your DB from PHP (i.e. you don't know PHP) or
b) Don't know what Perl is doing (i.e. you don't know Perl) or
c) possibly your environment is set up so that you can use Perl DBI but you can't do the same from PHP.
This link should give you pointers to do what you are doing in Perl directly from PHP. You will easily find dozens of examples for various PHP/DB combinations.
The only other way would be to do what another poster suggests: invoke the Perl script and parse the result (printed to standard out).
This is rubygoldbergsque, brittle and unacceptable as a solution unless you are absolutely desperate to use something that is available only as a Perl module (which is not the case from the example you posted).
In general if you want to have something done in a language and use it from some other language the best way would be to make the (in your case) Perl run as a sort of "server", i.e. a seperate process - and make it expose services using XML-RPC or some other lightweight protocol.
INVOKING PROGRAMS WITH exec() OR SIMILAR CONSTRUCTS IS EXTREMELY BAD PRACTICE.

What you are trying is not possible that easy. You will have to execute the perl script with PHP, capture the output and print it like:
<?php echo exec('perl dbcon.pl'); ?>
As mentioned that is not a good thing to do. For a good separation between backend and user interface you should have a look at existing PHP frameworks.

There is Perl PECL package to integrate Perl into PHP.
P.S. IMHO it is better to use templating system like Template Toolkit in Perl. You can even use Perl inside templates.

If you're using Catalyst you could us Catalyst::View::PHP I suspect it will give you more clues on how to use php as your templating system. It also mentions PHP::Interpreter

Related

Coldfusion and php, in the same file?

On this server, I can use both .cfm and .php files. Both types will be parsed, as expected.
However, I want .cfm files to be parsed for php, as well. For example,
//test.cfm:
<cfoutput>hello from cf</cfoutput>
<?php echo 'hello from php'; ?>
// outputs the php, verbatim, without processing :(
I know that I can change the php config, to parse .cfm. I dont know what order the parsing will take place or any other pros and cons, tricks and tips.
The goal here is that I want to wrap php (which i know well) into a cfm file (much less experience). The cfm file will be in an admin section, which automatically checks the user auth, and includes other cf files.
So, it seems to me that if coldfusion parses the file (checking the user-auth and all that), then hands it over to php, that would be the process that I am looking for.
This has been done:
See: http://www.barneyb.com/barneyblog/projects/cfgroovy2/
Most of the documentation has mixing ColdFusion and Groovy, but other languages can be mixed in too.
Example code:
<cfimport prefix="g" taglib="engine" />
...
<h2>Run some PHP (via Quercus)</h2>
<cftry>
<g:script lang="php">
<?php
$variables["myArray"][] = "Pretty Happy People wrote PHP.";
echo "<pre>";
var_dump($variables["myArray"]);
echo "</pre>";
?>
</g:script>
<cfcatch type="CFGroovy.UnknownLanguageException">
<p>Quercus needs to be added to your classpath for the PHP example to work</p>
</cfcatch>
<cfcatch type="any">
<p>Error running PHP code: #cfcatch.message#</p>
<p>#cfcatch.detail#</p>
</cfcatch>
</cftry>
Source: https://ssl.barneyb.com/svn/barneyb/cfgroovy2/trunk/demo/index.cfm
It will depend on the ColdFusion Application Server, what it supports and what level of interoperability you want. Generally if you want to be able to mix variables across statements, then you need to share the ColdFusion pageContext and make sure that php variables are written and updated. I don't believe that the example above does this, but I am happy to stand corrected. The other alternative is to called ColdFusion from PHP, again using Quercus. These 2 articles will help you do this. The first shows how to call Java from PHP, the second how to call ColdFusion from Java.
http://quercus.caucho.com/quercus-3.1/doc/quercus.xtp#Instantiatingobjectsbyclassname
http://help.adobe.com/en_US/ColdFusion/10.0/Developing/WSe61e35da8d318518-106e125d1353e804331-7ffb.html
Firstly create a ColdFusion component that can render ColdFusion dynamically
<cfcomponent displayname="ColdFusion renderer" output="false">
<cffunction name="render" returntype="'String' or 'Any'">
<!---
Do something with the coldfusion code here e.g:
write to a file using <CFFILE> and then <CFMODULE> or <CFINCLUDE>,<CFSAVECONTENT> it
or if the ColdFusion is all script, use the evaluate() function
--->
</cffunction>
</cfcomponent>
the invoke the component in PHP, via Java, using the CFCProxy
<?php
function cfml($code)
{
$cfc = new Java("coldfusion.cfc.CFCProxy", "path/to/cfc/above");
$cfc.render($code);
}
echo 'hello from php';
cfml(<<<EOT
<cfoutput>Hello from CF</cfoutput>
EOT
);
?>

Need to run a php program inside a rails produced page

I plan to use Spree for a shopping site but at some point need to sign some data with a PHP program provided by a bank. The only alternative I can think of is to link to somePage.php that runs PHP program and come back to Spree. Is there any easier way like a sending to some PHP shell inside Ruby? or changing for the view to have php extension?
Any help would be appreciated.
Well, first I would check for a native Ruby way of signing your data in Ruby. Have a look at Spree documentation first, or at your bank specs (they usually are very bad, take how bankers write contracts, they can't be any good at writing software specs).
As a second alternative, if you have the PHP program you should try and translate it in Ruby.
If that is not an option for you then you can play with open4 like this:
status = Open4::popen4("/path/to/php bank_code.php #{data_to_sign}") do |pid, stdin, stdout, stderr|
out_msg = stdout.read
err_msg = stderr.read
logger.error "out_msg #{out_msg}"
logger.error "err_msg #{err_msg}"
end
handle_error_case if status.existatus != 0
Cheers,

read a password-protected page

I'm trying to read specific div-elements of a website with a script either written in php or perl.
Unfortunately, the page requests a login before those specific site can be read. As I can see, it's ssl-protected. I'm not looking for a complete solution, I just need a hint regarding the best way to tell the script the informations needed for logging in (user+password), before reading parts of the sourcecode of the page that comes afterwards.
I'm not quite sure if it's better to do this with PERL or PHP, so i have tagged this question with both of these languages.
Mojo::UserAgent (see cookbook) has a built-in cookie jar and can do SSL if you have IO::Socket::SSL installed. It has a DOM parser which can easily use CSS3 selectors to traverse the returned result. And if that wasn't good enough, the whole thing can be used non-blocking (if that's something you need).
Mojo::UserAgent and the other tools listed above are parts of the Mojolicious suite of tools. It's a Perl library, and I would certainly recommend Perl for this task since it is a more general purpose language than PHP is.
Here is a very simplistic example to get the text from all the links that are inside a div with a class myclass
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
$ua->post( 'http://mysite.com/login' => form => { ... } );
my #link_text =
$ua->get( 'http://mysite.com/protected/page' )
->res
->dom('div.myclass a')
->text
->each;
In fact, running this shell command may be enough to get you started (depending on permissions)
curl -L cpanmin.us | perl - -n Mojolicious IO::Socket::SSL

Scala Lift - Run PHP file from within scala runtime

I'm not entirely sure the wording for the title is correct, but what I'm attempting to do is run and execute PHP files from within the Lift framework.
I'm not after any url queries to a PHP file residing on a server, more interested in somehow getting the PHP runtime working through my Scala/Lift app.
Use case: I have my app packaged into a .war file, I host this via a cloud provider. I upload code snippets to said app which then runs the php file and does whatever necessary.
I've seen various posts regarding Bianca but am hoping to keep this setup light and require only the PHP binary itself and a little code to get it flying.
Thanks in advance, please let me know if you need me to elaborate :)
“Never say never, because limits, like fears, are often just an
illusion.”
― Michael Jordan
What you really need is an open source (GPL), embeddable, full PHP 5 implementation, written entirely in Java!
Caucho's Quercus PHP Java runtime is just that, and it will let you run PHP within a Java app without external libraries or native code.
Below is a Quercus-PHP-in-Java code sample I found in this answer
import javax.script.ScriptEngine;
import com.caucho.quercus.script.QuercusScriptEngineFactory;
QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
String phpCode = "<?php $foo = strlen('abc'); print $foo; return 'yikes'; ?>"; //PHP Code as String
Object o = engine.eval(phpCode);
System.out.println(o);
It should be little effort to convert this code to idiomatic Scala. Obviously, the 'phpCode' variable could be constructed from external PHP file contents etc.
Let us know how you get on ;-)
That's a bit of an odd requirement, but if it's what you need to do, you can use a ProcessBuilder to execute and interact with your PHP script from the command line.

How could one use Node.js to run JS from PHP and return a value back?

This isn't for anything serious, more so to just play around and experiment. Just not sure where I would start. Also not bound to Node.js, just figured it's the most popular server-side JS tool around.
Though if there are some major technical reasons why one shouldn't do something like this on a real site, feel free to throw them out there.
What I'm asking about is something like…
$input = $js_string_built_via_php;
if ($run_on_server)
$output = node.js($input);
else
$output = '<script type="text/javascript">'.$input.'</script>';
echo $output;
There are several alternatives to using node here.
Have you seen the V8js PHP extension, which integrates the V8 engine with PHP? I don't have any experience with using it myself, though.
Alternatively, similar to using node, you could install Rhino (available in the Ubuntu repos, at least from 12.04). Or another command line javascript interpreter. Then you can execute javascript from the shell:
rhino -e '<javascript code>';
So you should be able to do something like the following. You would have to use print to output data and then parse the output back in php somehow:
<?php
function execute_js($script) {
return shell_exec('rhino -e '.escapeshellarg($script));
}
$javascript = "
function add(a,b) {
return a+b;
}
print(add(5,6));
";
$result = execute_js($javascript);
print $result;
I doubt this would be a good idea in a production application and seems like it might be quite vulnerable with a much greater attack surface. With clients being able to inject javascript code that actually gets executed on the server. It's probably very slow at load also.
A better solution 3 years later?
dnode-php would a better solution for what you want today.
There is a cool introduction here. As mentioned by the author Henri Bergius:
DNode is a remote method invocation protocol originally written for
Node.js, as the name probably tells. But as the protocol itself is
quite simple, just sending newline-terminated JSON packets over TCP
connections, implementations have started popping up in other
languages. You can talk DNode in Ruby, Perl, Python, Java, and now
PHP.

Categories