Question

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.

Was it helpful?

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

OTHER TIPS

You can forcefully downcase the file name before capitalizing the first letter. That is if all what you care about is capitalizing the first letter.

$fileName = ucfirst(strtolower($fileName));

On the docs for ucfirst it says (with my emphasis):

Returns a string with the first character of str capitalized, if that character is alphabetic.

Depending on where you execute this script SCRIPT_FILENAME will return different results. Could it be possible that you execute the script from a different path, thus giving SCRIPT_FILENAME a relative path?

To test this theory, I ran the script below from some of your possible execution paths and saw possible examples include the prefix "./" and "/" which would likely not be considered as having alphabetic first characters.

<?php
error_reporting(E_ALL);
echo $_SERVER["SCRIPT_FILENAME"]; 
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top