Search code examples
phpfile-iofwrite

PHP not writing into file. Just appending a 0 (zero)


When I use the following code to append a string to a file it does nothing but to append a zero.

I can assure that the cookie is set properly as I used an if condition to check and then I do this to write the fule:

$file = 'leaderboard.txt';
$txt = "" + $_COOKIE["user"] + "\n";
file_put_contents($file, $txt, FILE_APPEND | LOCK_EX);

I tried this also :

$myfile2 = fopen("leaderboard.txt", "a") or die("Unable to open file!");
$txt = "" + $_COOKIE["user"] + "\n";
fwrite($myfile2, $txt);

None of the methods anything but to append a 0 to the file.


Solution

  • In order to understand the 0 output, you have to realize that PHP does implicit type casting which can lead to weird unexpected behavior. Since you were using a math operator, namely +, instead of the string concatenation operator ., the the strings were all cast into a number, which in your case always was zero instead of throwing an error.

    But just for the fun of it try

    echo 5 + "3 beers"
    

    It will result in 8, as the string is cast to the integer three.