473,542 Members | 2,057 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

before eval(), how can one test a string to see if it is valid PHP code?

I have a string which I want to send to eval(). How can I test it
ahead of time to make sure it is valid code? I don't want to send it
to eval and get parse errors. I want to do something like this:

$valid = checkPHP($strin g);
if ($valid) {
eval($string);
} else {
$resultsObject->addToErrorResu lts("We wanted to send our
template to eval(), but the PHP it contained was invalid.");
}
Is there anything like checkPHP()?
Jul 17 '05 #1
12 8148
On 8 Mar 2004 15:31:16 -0800, lk******@geocit ies.com (lawrence) wrote:
I have a string which I want to send to eval(). How can I test it
ahead of time to make sure it is valid code? I don't want to send it
to eval and get parse errors. I want to do something like this:

$valid = checkPHP($strin g);
if ($valid) {
eval($string);
} else {
$resultsObject->addToErrorResu lts("We wanted to send our
template to eval(), but the PHP it contained was invalid.");
}
Is there anything like checkPHP()?


Pipe it through the command-line version of PHP with the -l flag?

--
Andy Hassall <an**@andyh.co. uk> / Space: disk usage analysis tool
<http://www.andyh.co.uk > / <http://www.andyhsoftwa re.co.uk/space>
Jul 17 '05 #2
Andy Hassall wrote:
On 8 Mar 2004 15:31:16 -0800, lk******@geocit ies.com (lawrence) wrote:

Is there anything like checkPHP()?


Pipe it through the command-line version of PHP with the -l flag?


Right!
But I prefer another name for the function :)

<?php
function is_validPHP($co de) {
$code = escapeshellarg( '<?php ' . $code . ' ?>');

$lint = `echo $code | php -l`; // command-line PHP

// maybe there are other messages for good code?
return (preg_match('/No syntax errors detected in -/', $lint));
}

# usage example
$code1 = '$xx=date("Y-m-d"); return $xx;';
if (is_validPHP($c ode1)) echo "code1 is valid PHP code\n";
else echo "code1 is invalid\n";

$code2 = '$xx=date("Y-m-d") return $xx;'; // no semicolon
if (is_validPHP($c ode2)) echo "code2 is valid PHP code\n";
else echo "code2 is invalid\n";

############### ############### ###
#### WARNING ####
#### DO NOT TRY THIS AT HOME ####
############### ############### ###

$code3 = '$dummy = `rm -rf ..`;'; // VALID CODE!!!!!!!
if (is_validPHP($c ode3)) echo "code3 is valid PHP code\n";
else echo "code3 is invalid\n";
?>
Output is:
code1 is valid PHP code
code2 is invalid
code3 is valid PHP code
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #3
"Pedro Graca" <he****@hotpop. com> wrote in message
news:c2******** *****@ID-203069.news.uni-berlin.de...
############### ############### ###
#### WARNING ####
#### DO NOT TRY THIS AT HOME ####
############### ############### ###

$code3 = '$dummy = `rm -rf ..`;'; // VALID CODE!!!!!!!
if (is_validPHP($c ode3)) echo "code3 is valid PHP code\n";
else echo "code3 is invalid\n";
?>


However, please feel free to try it at work :)

And if you do, I also have a bridge for sale if you are interested.

--
Mike Bradley
http://www.gzentools.com -- free online php tools
Jul 17 '05 #4
CountScubula wrote:
"Pedro Graca" <he****@hotpop. com> wrote in message
news:c2******** *****@ID-203069.news.uni-berlin.de...
############### ############### ###
#### WARNING ####
#### DO NOT TRY THIS AT HOME ####
############### ############### ###

$code3 = '$dummy = `rm -rf ..`;'; // VALID CODE!!!!!!!
if (is_validPHP($c ode3)) echo "code3 is valid PHP code\n";
else echo "code3 is invalid\n";
?>
However, please feel free to try it at work :)
Well ... I did try that at home.

And if you do, I also have a bridge for sale if you are interested.
I think I'm entitled to a discount for the Brooklyn bridge :)
--
Mike Bradley
http://www.gzentools.com -- free online php tools


Hey Mike! Your sig is broken.
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #5
Hi Lawrence,

I think there really ought to be a check() function that parses but does not
evaluate PHP code. But AFAIK there isn't.

Since the eval command is executing in the same environment as the rest of
the PHP code, when it returns an error and dies it affects the whole
environment. So, the workaround solution is to execute a sub-process to
evaluate the code and return the result to the main process. This can be
done using exec and command-line PHP:

<?PHP
$string1 = "php -r 'pint ('foo');'";
$string2 = "php -r 'print ('foo');'";
$result1 = exec($string1);
$result2 = exec($string2);
print $string1." returned: ".$result1. "<br />\n";
print $string2." returned: ".$result2. "<br />\n";
?>

From here you can probably create your checkPHP() function by grepping the
output for words like "Fatal error." Better would be if you know the
expected output to grep for that. Or maybe you can check the command-line
PHP exit status. Use the return_var for this.

Either way by spawning a sub-process to evaluate your code you are saved
from this affecting the main environment and therefore well on your way to a
solution.

Good luck.

Cheers,
Robert

On 3/8/04 3:31 PM, in article
da************* *************@p osting.google.c om, "lawrence"
<lk******@geoci ties.com> wrote:
I have a string which I want to send to eval(). How can I test it
ahead of time to make sure it is valid code? I don't want to send it
to eval and get parse errors. I want to do something like this:

$valid = checkPHP($strin g);
if ($valid) {
eval($string);
} else {
$resultsObject->addToErrorResu lts("We wanted to send our
template to eval(), but the PHP it contained was invalid.");
}
Is there anything like checkPHP()?


Jul 17 '05 #6
I posted earlier but my messages are not getting through via Comcast.
Weird...

A parse error in eval() doesn't cause the running script to die, so
all you have to do is stick a @ in front of the call:

$php_errormsg = false;
$track_errors = ini_set('track_ errors', 1);
@eval("How much wood would a woodchuck chuck if a wood chuck could
chuck
wood?");
ini_set('track_ errors', $track_errors);

echo "Error: $php_errormsg";

A fatal error (e.g. call to undefined function) would still kill the
script,
however.
Pedro Graca <he****@hotpop. com> wrote in message news:<c2******* ******@ID-203069.news.uni-berlin.de>...
Andy Hassall wrote:
On 8 Mar 2004 15:31:16 -0800, lk******@geocit ies.com (lawrence) wrote:

Is there anything like checkPHP()?


Pipe it through the command-line version of PHP with the -l flag?


Right!
But I prefer another name for the function :)

<?php
function is_validPHP($co de) {
$code = escapeshellarg( '<?php ' . $code . ' ?>');

$lint = `echo $code | php -l`; // command-line PHP

// maybe there are other messages for good code?
return (preg_match('/No syntax errors detected in -/', $lint));
}

# usage example
$code1 = '$xx=date("Y-m-d"); return $xx;';
if (is_validPHP($c ode1)) echo "code1 is valid PHP code\n";
else echo "code1 is invalid\n";

$code2 = '$xx=date("Y-m-d") return $xx;'; // no semicolon
if (is_validPHP($c ode2)) echo "code2 is valid PHP code\n";
else echo "code2 is invalid\n";

############### ############### ###
#### WARNING ####
#### DO NOT TRY THIS AT HOME ####
############### ############### ###

$code3 = '$dummy = `rm -rf ..`;'; // VALID CODE!!!!!!!
if (is_validPHP($c ode3)) echo "code3 is valid PHP code\n";
else echo "code3 is invalid\n";
?>
Output is:
code1 is valid PHP code
code2 is invalid
code3 is valid PHP code

Jul 17 '05 #7
Pedro Graca <he****@hotpop. com> wrote in message news:<c2******* ******@ID-203069.news.uni-berlin.de>...
Andy Hassall wrote:
On 8 Mar 2004 15:31:16 -0800, lk******@geocit ies.com (lawrence) wrote:
Is there anything like checkPHP()?


Pipe it through the command-line version of PHP with the -l flag?


Right!
But I prefer another name for the function :)

<?php
function is_validPHP($co de) {
$code = escapeshellarg( '<?php ' . $code . ' ?>');

$lint = `echo $code | php -l`; // command-line PHP

// maybe there are other messages for good code?
return (preg_match('/No syntax errors detected in -/', $lint));
}


Thanks much. Sadly, it doesn't work for my purposes. I'm trying to
offer end-users the option of editing the template for the admin
control panel that runs their websites, but I'm pretty sure some of
them will screw it up and destroy the control panel. Even experienced
PHP programmers can make a simple gramatical mistake. So I'd love to
take the template and test it for mistakes and maybe do a roll back to
the previous version, before their changes, if there are errors.

I found that I can send ordinary HTML pages to eval() so long as I put
"?>" at the beginning. This lets eval() know that it is breaking out
of PHP and into normal HTML. This is how the system currently works on
the sites that are run with this software (www.alexmarshall.org, for
instance).

I'm trying to run it through here:

function renderControlPa nelTemplate() {
$builtInControP anelTemplates =
$GLOBALS["builtInControP anelTemplates"];
$defaultTemplat e = $builtInControP anelTemplates["misty"];
$end = "?";
$end .= ">";
$defaultTemplat e = $end.$defaultTe mplate;
if ($valid = is_valid($defau ltTemplate)) {
eval($defaultTe mplate);
} else {
echo "<h1>We tried to load the template for the control panel but it
was full of errors in its PHP.";
}
}

Would all be well if I change this line:
$code = escapeshellarg( '<?php ' . $code . ' ?>');
to this:

$code = escapeshellarg( ' $code ');

Jul 17 '05 #8
lawrence wrote:
Pedro Graca <he****@hotpop. com> wrote in message news:<c2******* ******@ID-203069.news.uni-berlin.de>... Would all be well if I change this line:
$code = escapeshellarg( '<?php ' . $code . ' ?>');


to this:

$code = escapeshellarg( ' $code ');


I think yes.

"eval($stri ng)" start in PHP mode
"`php -l $string`" starts out of PHP mode

You just have to make sure you get into the right mode for whatever
instruction you're going to call.
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #9
On 3/9/04 5:00 PM, in article
da************* *************@p osting.google.c om, "lawrence"
<lk******@geoci ties.com> wrote:
Pedro Graca <he****@hotpop. com> wrote in message
news:<c2******* ******@ID-203069.news.uni-berlin.de>...
I'm trying to
offer end-users the option of editing the template for the admin
control panel that runs their websites, but I'm pretty sure some of
them will screw it up and destroy the control panel.


First of all, never allow end users the option of executing arbitrary code
on your system. Ever. There are a lot of things far worse a PHP error
message that can happen.

That said, I wrote the function for you. Since the php command line function
returns a non-zero (i.e. not 'clean') exit status for every error type
(fatal, parse, warning) that would also appear on your site via default PHP
error reporting, you can write the function this way:

<?PHP

function checkPHP($strin g) {
$string = escapeshellcmd( $string);
exec("php -r \"$string\"",$o utput,$exit);
if($exit==0) return TRUE;
else return FALSE;
}

/* tests */
$test = array ("print ('foo');",
"print (\"foo\");",
"pint ('foo');",
"print ('foo);",
"print ('foo','bar');"
);

for($i=0;$i<siz eof($test);$i++ ) {
print $test[$i];
if(checkPHP($te st[$i])) {
print " is ok.<br />\n";
} else {
print " not ok.<br />\n";
}
}

/* browser output:

print ('foo'); is ok.
print ("foo"); is ok.
pint ('foo'); not ok. <- fatal
print ('foo); not ok. <- parse
print ('foo','bar'); not ok. <- warning
*/
?>

Cheers,
Robert
--
Robert Peake | Peake Professional Consulting
Ro****@PeakePro .com | http://www.peakepro.com/

Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3041
by: lkrubner | last post by:
We are probably lucky that PHP doesn't allow this, but I'm curious about what the argument is against allowing this? Why did the inventors of PHP keep this from working? This same thing, using eval to create a class defintion, works in Javascript, demonstrating, perhaps, that Javascript is very flexible and you can do awful things with it. ...
12
4032
by: Kamilche | last post by:
I was looking for a way to speed up detecting invalid characters in my TCP string, and thought of yet another use for the translate function! If you were to 'translate out' the bad characters, and compare string lengths afterwards, you would know whether or not the line contained invalid characters. The new method is more than 10x faster than...
9
8453
by: HikksNotAtHome | last post by:
This is a very simplified example of an Intranet application. But, is there an easier (or more efficient) way of getting the decimal equivalent of a fraction? The actual function gets the select values, this one is a simplified version where its passed. function checkIt(selVal){ valueInDec1 = eval(selVal); //do some calculations here...
3
6298
by: McKirahan | last post by:
I said I wouldn't use "eval()" anymore but I need help to do it. Below is some stripped-down code (4 lines; watch for word-wrap) extracted from USGA.COM that preloads images: main_nav_home_F1 = new Image(153,21); main_nav_home_F1.src = "images/main_nav_home.gif"; main_nav_home_F2 = new Image(153,21); main_nav_home_F2.src =...
9
1851
by: Mike | last post by:
After reading much on the evils of eval, I have a question using my own personal use of the function... We have a reports system that will generate reports based on a number of parameters available on a blotter at the top of our report system. Each report could (and does) use a combination of some (but not all) of these 15 parameters. ...
12
3410
by: knocte | last post by:
Hello. I have always thought that the eval() function was very flexible and useful. If I use it, I can define functions at runtime!! However, I have found a case where eval() does not work properly. It works, for example, when invoking functions (alert('hello')), but not for defining functions. The case occurs when retrieving the...
15
3644
by: manstey | last post by:
Hi, I have a text file called a.txt: # comments I read it using this:
12
3762
by: Logos | last post by:
Yes, eval is a tool of the devil and I'll burn for using it. However, in this instance it's quite handy and I'm quite lazy. So, here's a weird one, and I'm wondering if anyone has a workaround. I am pulling data off a server via AJAX, and some of that data has non-English characters in it. The data is in the form of a json: ...
7
5047
by: Darko | last post by:
Hello, I have this particular problem with eval() when using Microsoft Internet Explorer, when trying to define an event handler. This is the code: function BigObject() { this.items = new Array(); this.values = new Array();
0
7392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
1
7324
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7670
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5867
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5246
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3376
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
943
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
620
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.