phpucfirst

ucfirst capitalizing the second letter when run at command line


I have a log method which saves to a file that is named the same as the script calling it, only with a capital first letter, which works sometimes, but other times capitalizes the second letter (I can't see any pattern as to when it does what but it's always consistent, meaning that file A will always either be initial capped or second letter capped, it's not arbitrary).

Here's my code...

function logData($str){
    $filePath = $_SERVER["SCRIPT_FILENAME"]; 

    $dir = substr($filePath, 0, strrpos($filePath, "/") + 1);   
    $fileName = substr($filePath,strrpos($filePath, "/")+1);
    $fileName = preg_replace('/\w+$/','log',$fileName);
    $fileName = ucfirst($fileName);  
    $fHandle = fopen( $dir.$fileName , "a");
    $contents = fwrite($fHandle, $str ."\n");
    fclose($fHandle);
}

Does anyone have any thoughts on what could be causing such an odd behavior *some of the time?

I know I can brute force it with a strtoupper on the first char and then append the rest of the string, but I'd really like to understand what (if anything) I'm doing wrong here.


Solution

  • This is probably a bug further up the code, where you calculate the $dir and $filename. If the path has a slash or not... a probably solution is .

    if (strpos('/', $filePath) === false) {
        $dir = '';    
        $fileName = $filePath;
    } else {
        $dir = substr($filePath, 0, strrpos($filePath, "/") + 1);    
        $fileName = substr($filePath,strrpos($filePath, "/")+1);
    }
    

    But echo those values out and concetrate there