php run javascript code - php

is it possible to run some javascript expression? for example echo eval("Math.sqrt('25')");

In normal situations :
PHP runs on the server
and, then, Javascript is run on the client, in the browser.
So, no, it's not quite possible to have PHP execute some Javascript code on the server.
But there is at least on PHP extension that embed (or wrap arround) a Javascript engine, and, as a consequence, allows one to execute Javascript on the server, from PHP.
The extension I'm thinking about is the spidermonkey one : installing and enabling it on your server will allow you to execute Javascript code, on the server, from PHP.
Of course, like any other PHP extension, you'll need to be admin of your server, in order to install it -- and this one is never installed by default, as it answers a very specific need.
About this extension, I have never seen it used in real situations, and there are not many people who tried it... here are two articles you might want to read :
Using JavaScript in PHP with PECL and SpiderMonkey
and SpiderMonkey : Exécuter du Javascript côté serveur, depuis PHP (this one is in french, and on my own blog)

Try this
echo "<script language='javascript'> Math.sqrt('25') </script>"

There is also the J4P5
I don't know if it's still maintained but you can always fork it, it's released under the GPL license.

put your php into a hidden div and than call it with javascript
html / php part
<div id="mybox" style="visibility:hidden;"> echo sqrt(25); </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield... like this
alert(myfield);

Since PHP is a server-side scripting language that runs on the server and Javascript is a client-side scripting language that runs in a browser you would have to have the PHP generate Javascript code (the same way it generates HTML) that gets executed after the page is loaded.

echo sqrt(25);
See:
http://php.net/manual/en/function.sqrt.php

Run JavaScript code from PHP
php v8js: https://github.com/phpv8/v8js
$v8 = new V8Js;
$v8->executeString("Math.sqrt('25')"); // 5
https://github.com/chenos/execjs
use Chenos\ExecJs\Context;
$cxt = new Context;
$cxt->eval("Math.sqrt('25')"); // 5

if you have node installed on your server then you can exec this command with php
node a.js
and then use the console.log as output.

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
);
?>

Post into a textarea and then get the result from another textarea

Let say I have this JS code:
function plus2(){
print (2+2);
};
So I want to post this code into textarea#input at http://dean.edwards.name/packer/ and then get the result back from textarea#output.
Can use PHP Curl, Shell Curl or JQuery to do the job?
P.S.: By the way, there is bug in PHP Packer port and that's whay I am not using it.
PHP implementation of JSMin works well for me. Also, if you have server-side JS interpreter you can use UglifyJS, it's fast and provides a good compression.
Not really, no. It would need to be passed to a JavaScript engine at some point, so PHP/cURL is not going to be enough.
I recommend using an alternative server-side implementation of packer, or perhaps even YUI Compressor.

Open a new window using PHP

Is there any way to open a new window or new tab using PHP without using JavaScript.
Nope, a window can only be opening by adding target="_blank" attribute (invalid in Strict (X)HTML, but valid in HTML5) or using JavaSript's window.open(url '_blank').
PHP runs server side - therefore it can generate the HTML or JavaScript, but it can't directly interact with the client.
Short answer: No.
PHP is a server side language (at least in the context of web development). It has absolutely no control over the client side, i.e. the browser.
No. PHP is a server-side language, meaning that it is completely done with its work before the browser has even started rendering the page. You need to use Javascript.
No, there is not.
No, PHP is server-side scripting
PHP is a server-side language, it's what produces all the code you see on a page when you choose View Source. PHP cannot affect the client on its own, it needs to do it through a language such as JavaScript.
PHP is server-side, as everyone states, however you can add a target="_blank" attribute to your form tag. This doesn't perform any work server side, but does let you submit the form to a new window to be processed on the server.
A neat trick, but 1) deprecated in HTML Strict and 2) rarely useful.
This answer is dedicated to the How to call a JavaScript function from PHP? thread; you can execute this block of code:
<?php
echo "<script> window.open(\"about:blank\"); </script>";
?>
Hopefully this helps!

PHP in HTML <Script>

I was viewing a Appcelerator Titanium Video Tutorial and I saw they used syntax like
<script type="text/php">
...
global $window, $document;
mysql_connect(...) or die $window->alert('...');
$document.getElementById('xxx');
...
</script>
so I have a few questions. Is it any difference if I use <?php ?>
without setting $window and $document - won't they be "unset" variables?
I guess I can use (basic, not jQuery for example) Javascript functions like alert and getElementById() in PHP too?
In this case, they can only be "undefined", not "unset". However, they have "global" prefix, so there is a chance they are defined in some other code, possibly even outside your file.
$window->alert(...) probably outputs HTML that reads as javascript alert or a similar function.
You cannot use javascript alert() in PHP, because it is not PHP function.
As far as PHP is concerned, there is no JavaScript — only text.
$window and $document are just variables defined elsewhere in the PHP. $window appears to be an object with some methods that output text (text that happens to include JS syntax) while $document appears to be a string.
They will be undefined if they haven't been defined already.
You can write any JS function you like as normal text. If you want to use an object to generate it, then you need to have an object that is aware of that function.
For a regular web app, the code you're showing makes no sense whatsoever, because PHP runs on the server and JavaScript runs on the client. PHP is used to build the HTML code which forms the DOM tree on which JavaScript functions like getElementById() operate, so it's completely impossible to use them meaningfully within PHP code.
However, a cursory investigation reveals that Appcelerator Titanium is a sort of runtime that is meant to run applications using web technology completely on the client. In such a runtime, it is possible that the PHP code is running in the context of an already complete HTML DOM and interacts with it via JavaScript-like bridge functions. But that's completely different from how PHP normally works.

Run PHP class from JavaScript

I need to fire a php class from a javascript function.
code:
<input type="button" name="Submit" value="Submit" class="opinionbox"
onclick="verifyControl('<?=$control_no?>')"/>
function verifyControl(rNo) {
Cont_no=document.getElementById("ContNo").value;
if(rNo==Cont_no) {
frames['frame1'].print();
showPage('payment');
}
else if(rNo!=Cont_no) {
alert("invalid control no");
}
}
i need to run the code
$data = $obj_com -> getSelectedData('tbl',
'control_no', $contno);
$control_no = $contno;
$obj_com -> recordPay('tbl',$contno);
inside the verifyControl() how can I do this?
You cannot "call" a PHP class from Javascript because Javascript is run on the client side (ie, the browser) while PHP is run on the server. What you can do, however, is call a PHP script asynchronously, get its output, and do fun stuff with javascript. This is known as AJAX. If you're going to go down this road, you are highly advised to use a library like jQuery and learn from there. Here are a few questions to get you started (check out the answers):
How to dynamically call a php function in javascript
Javascript and PHP functions
To call PHP code from Javascript, given that PHP is executing on the server and Javascript is executing on the client, you will need to set up some sort of interface at the server that can be accessed remotely.
You may also want to be aware of the security implications of doing so. In particular, if you want to ensure that only your users will be calling your server in this way - that is, if a malicious user calling this code could do damage, you will need some sort of authentication.
You will also need to decide on a protocol for communicating between the client and server.
Protocols such as SOAP and XML-RPC define everything you need to remotely call procedures on the server. Or you can roll your own, just by calling a certain URL and receiving a certain result, in a certain format (JSON can help) from the server.
you can use Brent Ashley jsrsClient.js or $.ajax of jQuery Javascript lib.

Categories