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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • lawrence

    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()?
  • Andy Hassall

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

    On 8 Mar 2004 15:31:16 -0800, lkrubner@geocit ies.com (lawrence) wrote:
    [color=blue]
    >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()?[/color]

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

    --
    Andy Hassall <andy@andyh.co. uk> / Space: disk usage analysis tool
    <http://www.andyh.co.uk > / <http://www.andyhsoftwa re.co.uk/space>

    Comment

    • Pedro Graca

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

      Andy Hassall wrote:[color=blue]
      > On 8 Mar 2004 15:31:16 -0800, lkrubner@geocit ies.com (lawrence) wrote:[/color]
      [color=blue][color=green]
      >>Is there anything like checkPHP()?[/color]
      >
      > Pipe it through the command-line version of PHP with the -l flag?[/color]

      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 =--

      Comment

      • CountScubula

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

        "Pedro Graca" <hexkid@hotpop. com> wrote in message
        news:c2j318$1qi 6lv$1@ID-203069.news.uni-berlin.de...
        [color=blue]
        > ############### ############### ###
        > #### 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";
        > ?>
        >[/color]

        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


        Comment

        • Pedro Graca

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

          CountScubula wrote:[color=blue]
          > "Pedro Graca" <hexkid@hotpop. com> wrote in message
          > news:c2j318$1qi 6lv$1@ID-203069.news.uni-berlin.de...
          >[color=green]
          >> ############### ############### ###
          >> #### 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";
          >> ?>[/color][/color]
          [color=blue]
          > However, please feel free to try it at work :)[/color]

          Well ... I did try that at home.
          [color=blue]
          >
          > And if you do, I also have a bridge for sale if you are interested.[/color]

          I think I'm entitled to a discount for the Brooklyn bridge :)
          [color=blue]
          > --
          > Mike Bradley
          > http://www.gzentools.com -- free online php tools[/color]

          Hey Mike! Your sig is broken.
          --
          --= my mail box only accepts =--
          --= Content-Type: text/plain =--
          --= Size below 10001 bytes =--

          Comment

          • Robert Peake

            #6
            Re: before eval(), how can one test a string to see if it isvalid PHP code?

            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
            da7e68e8.040308 1531.652b0b36@p osting.google.c om, "lawrence"
            <lkrubner@geoci ties.com> wrote:
            [color=blue]
            > 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()?[/color]

            Comment

            • Chung Leong

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

              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 <hexkid@hotpop. com> wrote in message news:<c2j318$1q i6lv$1@ID-203069.news.uni-berlin.de>...[color=blue]
              > Andy Hassall wrote:[color=green]
              > > On 8 Mar 2004 15:31:16 -0800, lkrubner@geocit ies.com (lawrence) wrote:[/color]
              >[color=green][color=darkred]
              > >>Is there anything like checkPHP()?[/color]
              > >
              > > Pipe it through the command-line version of PHP with the -l flag?[/color]
              >
              > 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[/color]

              Comment

              • lawrence

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

                Pedro Graca <hexkid@hotpop. com> wrote in message news:<c2j318$1q i6lv$1@ID-203069.news.uni-berlin.de>...[color=blue]
                > Andy Hassall wrote:[color=green]
                > > On 8 Mar 2004 15:31:16 -0800, lkrubner@geocit ies.com (lawrence) wrote:[/color]
                >[color=green][color=darkred]
                > >>Is there anything like checkPHP()?[/color]
                > >
                > > Pipe it through the command-line version of PHP with the -l flag?[/color]
                >
                > 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));
                > }[/color]

                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:
                [color=blue]
                > $code = escapeshellarg( '<?php ' . $code . ' ?>');[/color]

                to this:

                [color=blue]
                > $code = escapeshellarg( ' $code ');[/color]

                Comment

                • Pedro Graca

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

                  lawrence wrote:[color=blue]
                  > Pedro Graca <hexkid@hotpop. com> wrote in message news:<c2j318$1q i6lv$1@ID-203069.news.uni-berlin.de>...[/color]
                  [color=blue]
                  > Would all be well if I change this line:
                  >[color=green]
                  >> $code = escapeshellarg( '<?php ' . $code . ' ?>');[/color]
                  >
                  > to this:
                  >
                  >[color=green]
                  >> $code = escapeshellarg( ' $code ');[/color][/color]

                  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 =--

                  Comment

                  • Robert Peake

                    #10
                    Re: before eval(), how can one test a string to see if it isvalid PHP code?

                    On 3/9/04 5:00 PM, in article
                    da7e68e8.040309 1700.3a15c23b@p osting.google.c om, "lawrence"
                    <lkrubner@geoci ties.com> wrote:
                    [color=blue]
                    > Pedro Graca <hexkid@hotpop. com> wrote in message
                    > news:<c2j318$1q i6lv$1@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.[/color]

                    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
                    Robert@PeakePro .com | http://www.peakepro.com/

                    Comment

                    • lawrence

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

                      Robert Peake <robert@peakepr o.com> wrote in message[color=blue]
                      > 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.[/color]

                      Thanks. They don't get to write arbitrary code. There are 500
                      functions they are allowed. The names of the functions are kept in an
                      array and a regex makes sure they only use the allowed functions.




                      [color=blue]
                      > 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:[/color]

                      Thanks much for the rewrite.






                      [color=blue]
                      >
                      > <?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";
                      > }
                      > }[/color]

                      Comment

                      • Robert Peake

                        #12
                        Re: before eval(), how can one test a string to see if it isvalid PHP code?

                        On 3/12/04 10:45 AM, in article
                        da7e68e8.040312 1045.14f44bde@p osting.google.c om, "lawrence"
                        <lkrubner@geoci ties.com> wrote:
                        [color=blue]
                        > Thanks. They don't get to write arbitrary code. There are 500
                        > functions they are allowed. The names of the functions are kept in an
                        > array and a regex makes sure they only use the allowed functions.[/color]

                        Interesting. I'm working on a project:

                        Compare the best free open source Site Management Software at SourceForge. Free, secure and fast Site Management Software downloads from the largest Open Source applications and software directory


                        To add a layer of abstraction to the Smarty template engine to make
                        customized skinning of sites very, very user friendly and system safe.
                        Sounds like there's a need for it.

                        Cheers,
                        Robert

                        --
                        Robert Peake | Peake Professional Consulting
                        Robert@PeakePro .com | http://www.peakepro.com/

                        Comment

                        • lawrence

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

                          Robert Peake <robert@peakepr o.com> wrote in message news:<BC78EF0B. 21BE%robert@pea kepro.com>...[color=blue]
                          > On 3/12/04 10:45 AM, in article
                          > da7e68e8.040312 1045.14f44bde@p osting.google.c om, "lawrence"
                          > <lkrubner@geoci ties.com> wrote:
                          >[color=green]
                          > > Thanks. They don't get to write arbitrary code. There are 500
                          > > functions they are allowed. The names of the functions are kept in an
                          > > array and a regex makes sure they only use the allowed functions.[/color]
                          >
                          > Interesting. I'm working on a project:
                          >
                          > http://sourceforge.net/projects/simpletags/
                          >
                          > To add a layer of abstraction to the Smarty template engine to make
                          > customized skinning of sites very, very user friendly and system safe.
                          > Sounds like there's a need for it.[/color]


                          Could you expand on this, in English, and then maybe give an example?
                          I don't know much smarty, but I'm curious.

                          Comment

                          Working...