Forum Moderators: coopster

Message Too Old, No Replies

php if/elseif day and time not working

         

mattb123

8:45 pm on Dec 31, 2015 (gmt 0)

10+ Year Member



Hi guys.
I put together a php to display a certain page based on whether or not we're open. test1.html is when we are open and test2.html is when we are closed. I saved the php as index.php.

When it executes, it only opens the else, which is the test2.html.

Can someone take a look at my code and see what's wrong with it?
Thanks!

<?php


$day = date('N') ;
$time = date('H:i') ;

if (($day <= '4') && ($time >= '7:00') && ($time <= '19:30'))
{
echo readfile ("test1.html");
}

elseif (($day == '5') && ($time >= '7:00') && ($time <= '18:30'))
{
echo readfile ("test1.html");
}

elseif (($day == '6') && ($time >= '7:00') && ($time <= '17:30'))
{
echo readfile ("test1.html");
}


else
{
echo readfile ("test2.html");
}

?>

lucy24

11:09 pm on Dec 31, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Can I assume you've already tested by having it echo "day" and "time" (that is, their current values) so you're sure the server time is what you think it is?

getcooking

2:05 am on Jan 1, 2016 (gmt 0)

10+ Year Member



You can't compare date-formatted time to "7:00" or other arbitrary string. You have to convert them first. Something like:

$time >= date("H:i", strtotime("7:00"))

whitespace

12:31 pm on Jan 1, 2016 (gmt 0)

10+ Year Member Top Contributors Of The Month



You can't compare date-formatted time to "7:00" or other arbitrary string.


"Oh yes you can!" ('tis the season ;)


($time >= '7:00')


When you compare two strings you are performing a lexicographical string comparison. If $time is "12:25" (24 hour clock) then ($time > '7:00') is false ("1" does not lexicographically follow "7"), but ($time > '07:00') is true ("1" lexicographically follows "0"). So, basically you are just missing the "0" prefix:


($time >= '07:00')

whitespace

5:27 pm on Jan 1, 2016 (gmt 0)

10+ Year Member Top Contributors Of The Month



$time = date('H:i') ;


Btw, the "H" format character returns an hour with leading zeros.

whitespace

12:34 pm on Jan 2, 2016 (gmt 0)

10+ Year Member Top Contributors Of The Month



$time >= date("H:i", strtotime("7:00"))


Incidentally, this is the same as simply writing:


$time >= '07:00'


So yes, that would have worked!