Search code examples
phprubyiosyntax-checkingphplint

Using php -l to verify syntax - behavior w/ opening tags


I can't seem to find anything on this, and I'm wondering if anyone else has encountered this issue or knows the reason why.

I have some PHP code that I'm trying to verify the syntax of before I save it into a database.

I'm in Ruby, but that doesn't matter. I'm using php -l to check the syntax and either clear it for saving or output any syntactical errors that occur.

This is a newer server install, so I'm guessing the issue is with something that needs installing or a setting in the php.ini that needs tweaking.

If the php content has a blatant error in it and starts with <?, the PHP lint function doesn't catch the error.

If the php content has the same blatant error and starts with <?php, the PHP link function catches the error.

The ruby code -- taking the content, putting it into a tempfile, then running php -l on the tempfile:

module PhpValidator
  def validate_php
    output = IO.popen("php -l", "r+") do |f|
      f.puts self.content
      f.close_write
      f.read
    end
    if $? != 0
      output.sub!("Errors parsing -", "")
      errors.add(:content, "contains invalid PHP: #{output}")
    end
  end
end

Then in the model where the content / php is being saved:

before_save :validate_php

Example PHP that returns invalid with

<?
echo "test";
dsfaks;fjaskl;fkas0f9qiroawlsfkasdfa;'
?>

Solution

  • Turns out it was a simple issue. I was looking at the wrong php.ini file.

    From the command line, I did:

    php -i | grep php.ini to figure out which php.ini file was active.

    Then, looking in there, I noticed that:

    short_open_tag the preference was set to Off and it needs to be On.

    Secondly, I was getting a simple Errors parsing - response when there was a syntax error, which meant I also needed to turn on display_errors in the php.ini file.

    Simple issue, took me 5 minutes after I thought it through, but I'll leave this here for the next person.