Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protecting one class from the bad programming of another?

Is there a way in PHP to try to include a file, but if the file contains errors that stop it from compiling to just skip that file from inclusion?

like image 552
Mark Tomlin Avatar asked Jun 06 '10 00:06

Mark Tomlin


2 Answers

You can call php -l on the file in question. This will shell out and slow though. it doesn't handle runtime errors like die() though.

test.php:

<?php
function check_code_file($filename)
{
    $filename = escapeshellcmd($filename);
    system("php -l $filename 2>/dev/null 1>/dev/null", $status);
    if ($status) return false;
    return true;
}
if (check_code_file('test-good.php'))
{
    include('test-good.php');
}
if (check_code_file('test-bad.php'))
{
    include('test-bad.php');
}
print "finished\n";

test-good.php:

<?php
print "here\n";

test-bad.php:

<?php
die(

$ php test.php

here
finished
like image 64
Gavin Mogan Avatar answered Sep 18 '22 00:09

Gavin Mogan


A less than ideal solution I thought I'd mention here for posterity. The original idea is here.

You can capture the E_PARSE error you would receive on a bad 'require' and hand it off to a shutdown function. The idea is to suppress the parsing error...

register_shutdown_function('post_plugin_include'); 
@require 'bad_include.php';

Then do your primary execution after the fact.

function post_plugin_include() {
    if(is_null($e = error_get_last()) === false) {
        // do something else
    }
}

Like I said, less than ideal but interesting nonetheless.

like image 30
allnightgrocery Avatar answered Sep 22 '22 00:09

allnightgrocery