Welcome to WebmasterWorld Guest from 3.227.233.78

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

php if/elseif day and time not working

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

New User

joined:Dec 29, 2015
posts: 4
votes: 0


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");
}

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

Senior Member from US 

WebmasterWorld Senior Member lucy24 is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

joined:Apr 9, 2011
posts:15889
votes: 876


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?
2:05 am on Jan 1, 2016 (gmt 0)

Full Member

10+ Year Member

joined:June 4, 2008
posts: 202
votes: 0


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"))
12:31 pm on Jan 1, 2016 (gmt 0)

Full Member

Top Contributors Of The Month

joined:Apr 11, 2015
posts: 328
votes: 24


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')
5:27 pm on Jan 1, 2016 (gmt 0)

Full Member

Top Contributors Of The Month

joined:Apr 11, 2015
posts: 328
votes: 24


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


Btw, the "H" format character returns an hour with leading zeros.
12:34 pm on Jan 2, 2016 (gmt 0)

Full Member

Top Contributors Of The Month

joined:Apr 11, 2015
posts: 328
votes: 24


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


Incidentally, this is the same as simply writing:


$time >= '07:00'


So yes, that would have worked!