Search code examples
phpsyntaxstrtotimefgets

PHP strtotime() function


I have a file with the following lines. I want to identify lines which have timestamps less than a week from now(starting from aug 22 for this example).

log3.txt
28-08-2011 10:29:25 A string
29-08-2011 14:29:25 A new string
20-08-2011 14:29:25 Don’t include

php file

if($file = fopen("/opt/apache2/htdocs/log3.txt", "r"))
{
    while(!feof($file))
    {
        $contents = fgets($file, 23); // This is supposed to be 22.
        echo $contents; // With 22 it only returns 08-29-2011 14:29:25 P
        if(strtotime($contents) > strtotime("last Monday"))
        {
            $string1 = fgets($file);
            echo "In if $string1";
            // Do something
        }
        else
        {
            $string1 = fgets($file);
            echo "In else $string1"; //Always goes to else statement.
        }
    }
}

The timestamps are created with date('m-d-Y H:i:s').

Why does fgets need 23 characters when it's actually 22.

What am I doing wrong here with strtotime?

What is the best way to parse lines with timestamps less than a week ago.

EDIT: Got it to work

$date = DateTime::createFromFormat('d-m-Y H:i:s', $contents);

if(strtotime($date->format('d-m-Y H:i:s')) > strtotime("last Monday"))

Use DateTime function with d-m-Y format or m/d/Y.

Thanks for all the help guys.


Solution

  • Use DateTime::createFromFormat instead. strtotime() may have problems to detect the used format of your date.

    $date = DateTime::createFromFormat('d-m-Y H:i:s A', $contents);