Search code examples
phpfopenfwritefreadstrstr

Strstr return false instead of true


I want to open file, check if string deosn't exist in file write it.

Doing this:

$fp=fopen('categories.txt','a+');
$content=fread($fp,filesize('categories.txt'));

if(!strstr($content,$cat)){
    fwrite($fp,','.$cat);
}
fclose($fp);

But I got repeating values in categories.txt after writing. Only issue I can expect is encoding problem, but all files are utf-8 and in categories.txt I just have latin symbols and few symbols.

Any ideas where is the problem?


Solution

  • Ok, I think problem in fopen. I changed to this, and code starts to work:

    $content=file_get_contents('categories.dat');
    $type=(string) $type;
    $content=(string)$content;
    
    if(!strstr($content,$type)){
        file_put_contents('categories.dat',$content.','.$type);
    }
    

    Thanks for helps.