简体   繁体   中英

preg_match for <?php, <?, and/or ?>

I'm not very familiar with regEx's and I'm trying to find a preg_match regex for searching for any of the following strings within a file and if found it will halt it. I already have the fopen and fgets and fclose setup I just need to use a regex inside of a preg_match for the following php tags:

<?php <? ?>

so if preg_match returns 1 than this will skip this file and not upload it. I am using the $_FILES array to upload it via post, so I'm hoping I can use the $_FILES['file']['tmp_name'] variable for this to read through the file.

Thanks for your help with this :)

EDIT

if (in_array('application/x-httpd-php', $files[$filid]['mimetypes']) && ($_FILES[$value]['type'][$n] == 'application/octet-stream' || $_FILES[$value]['type'][$n] == 'application/octetstream'))
{
    $file_extension = strtolower(substr(strrchr($_FILES[$value]['name'][$n], '.'), 1));

    if ($file_extension == 'php')
    {
        // Reading the current php file to make sure it's a PHP File.
        $fo = fopen($_FILES[$value]['tmp_name'][$n], 'rb');
        while (!feof($fo))
        {
            $fo_output = fgets($fo, 16384);

            // look for a match
            if (preg_match([REG EX HERE], $fo_output) == 1)
            {
                $php = true;
                break;
            }
        }
        fclose($fo);
    }
}

OK, I apologize, but actually, what I am doing is I need to find a PREG MATCH. Because if it is a PHP FILE, I need to set the MIME TYPE to: application/x-httpd-php within the database. BECAUSE I'm also allowing PHP Files to be uploaded as well in certain instances. So hopefully the code I posted above makes more sense to you all now.

Can someone please help me with a preg_match regex for this please?

/(?:<\?(?!xml)|\?>)/

(15个字符)

If you want to parse the file, try the following instead:

function containsPhp($file) {
    if(!$content = file_get_contents($file)) {
        trigger_error('Not a file');
        return false;
    }
    foreach(token_get_all($content) as $token) {
        if(is_array($token) && in_array(current($token), array(T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO))) {
            return true;                
        }
    }
    return false;
}

... besides checking for a php extension (php, php5, phtml, inc etc).

\?>|<\?((?=php)|(?!\w))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM