Search code examples
phpsubstrstrpos

edit to substr and strpos causes Error 500


I'm trying to make some edits to a piece of code but I get an error 500 when I do. For this example, lets say that

basename(__FILE__)

is my_filename.php

The code is:

$HTTP_GET_VARS['feed_file'] = $_GET['feed_file'] 
= substr(
            basename(__FILE__),
            3,
            strpos( basename(__FILE__), '.php') -3
        );

$HTTP_GET_VARS['feed_file'] would echo as "filename"

Now, if

basename(__FILE__) 

is aaa_filename.php the original code would give $HTTP_GET_VARS['feed_file'] as "_filename"

I changed the code to

$HTTP_GET_VARS['export_feed'] = $_GET['export_feed'] 
= substr(
            basename(__FILE__),
            4,
            strpos( basename(__FILE__), '.php') -3
        );

$HTTP_GET_VARS['export_feed']now echos as "filename."

Ok, so I need to lose one more character from the end of the string. I change the -3 to -4 so that I have

$HTTP_GET_VARS['export_feed'] = $_GET['export_feed'] 
= substr(
            basename(__FILE__),
            4,
            strpos( basename(__FILE__), '.php') -4
        );

Only now the Error 500 is thrown. Confusing the hell out of me as I thought it was going to be a simple change. Any suggestions on why I'm having problems simply changing the number of chars to drop from the beginning and end of a string?


Solution

  • I would use preg_match to dynamically get "filename":

    $basename = 'ab_filename.php';
    
    if(preg_match('/_(.+)\.php$/',$basename,$matches)):
        $name = $matches[1]; // 'filename'
    endif;
    

    Now $name is just "filename"

    Live demo

    That aside, the code snippet you shared by itself would not cause a 500 server error. There is probably a domino effect and the error gets triggered elsewhere. Learn how to look up error logs for details.

    Finally, if you'll keep using your current approach, don't hardcode the offset (your -3 or -4). Rather compute it dynamically like so:

    $basename = 'abcd_filename.php';
    
    $pos_ = strpos($basename,'_') + 1;
    $len  = strpos( $basename, '.php') - $pos_;
    $name = substr($basename, $pos_, $len);
    

    Now $name is "filename"