If statement syntax and logic issue - php

I am trying to switch our surf web cameras off at civilian twilight but having some difficulties with the if statement at the bottom of this code. I am pretty sure it's a syntax issue but can't see it.
//Sunrise
//Set Zenneth to 96 which is Civilian Twilight start. Normally set to 90 for "normal" sunrise
$sunrise = date_sunrise(time(), SUNFUNCS_RET_STRING, 51.575363, -4.037476, 96, 0);
$sunrise = (integer) str_replace(":", "", $sunrise);
// echo "Sunrise: ".$sunrise."</br>";
//Sunset
//Set Zenneth to 96 which is Civilian Twilight start. Normally set to 90 for "normal" sunrise
$sunset = date_sunset(time(), SUNFUNCS_RET_STRING, 51.575363, -4.037476, 96, 0);
$sunset = (integer) str_replace(":", "", $sunset);
// echo "Sunset: ".$sunset."</br>";
// get the current date using a 24 digit hour without leading zeros, as an int
$current_time = (Integer) date('Gi');
if ((($current_time >= 0000 && $current_time <= $sunrise) && ($current_time >= $sunset
&& $current_time <= 2359)) && ($_SERVER["REQUEST_URI"] == "/webcams/langland-webcam"
| $_SERVER["REQUEST_URI"] == "/webcams/caswell-webcam" || $_SERVER["REQUEST_URI"] ==
"/webcams/llangennith-webcam" || $_SERVER["REQUEST_URI"] == "/webcams/swansea-webcam"))
{
// Cameras are offline
return true;
}

Yikes. That is one huge if statement. I've broken it up a bit:
if (
(
($current_time >= 0000 && $current_time <= $sunrise)
&& ($current_time >= $sunset && $current_time <= 2359)
// ^^ Should be `||`
) && (
$_SERVER["REQUEST_URI"] == "/webcams/langland-webcam"
| $_SERVER["REQUEST_URI"] == "/webcams/caswell-webcam"
// ^ Should be `||`
|| $_SERVER["REQUEST_URI"] == "/webcams/llangennith-webcam"
|| $_SERVER["REQUEST_URI"] == "/webcams/swansea-webcam"
)
) {
As commented, first thing I notice: You should be using || on the first comparison. Additionally, you later use a single pipe | instead of a ||.
Overall, I would recommend that you refactor this code a bit. Perhaps move the allowed URIs into an array, then use in_array() to check it. Cumbersome ifs like this can cause problems--as you just discovered. Something like this:
$validUris = array("/webcams/langland-webcam", "/webcams/caswell-webcam", "/webcams/llangennith-webcam", "/webcams/swansea-webcam");
if (in_array($_SERVER["REQUEST_URI"], $validUris)) {
if (($current_time >= 0000 && $current_time <= $sunrise) || ($current_time >= $sunset && $current_time <= 2359)) {
// Cameras
return true;
}
}

Related

Running code between certain times

I have php code that is suppose to run between 04:00am and 05:00am but it does not run, i cant see the problem with this?
$begin = new DateTime('04:30');
$end = new DateTime('05:00');
while (!connection_aborted() || PHP_SAPI == "cli") {
$now = new DateTime();
if(date("Hi") <= $begin && date("Hi") >= $end){
//run code
}
}
Your problem lies here:
if(date("Hi") <= $begin && date("Hi") >= $end){
You are trying to do "greater than" and "less than" comparisons on strings. You should use the integer values (epoch time) then you can do this.
if(time() >= strtotime('14:00') && time() <= strtotime('15:00')) {
echo 'In Range2';
} else {
echo 'out of range2';
}
Note: This is for between 2:00pm and 3:00pm just to show it works (it currently is 2:00pm where I am located).
Demo: https://3v4l.org/NhnfM

Pulling in data around/after midnight

Ok.. so I've created myself a messy problem.
So I have a jquery slider that shows 5 slides of content
1) -2 hours ago
2) -1 hour ago
3) (0) present
4) +1 hours
5) +2 hours
The content for each slide is decided by what time of day it is. However when it comes to trying to go back/forwards 1 to 2 hours during the run up to midnight and after midnight the whole script breaks, and kills the site.
<?php
$h = date('G', strtotime ("-2 hour")); //set variable $h to the hour of the day.
$m = date('i', strtotime ("-2 hour")); //set variable $m to the min of the hour.
$d = date('w', strtotime ("-2 hour")); //set variable $d to the day of the week.
// SATURDAY SCHEDULE
if ($d == 6 && $h >= 0 && $h < 07) $file ='earlyhours.php';
else if ($d == 6 && $h >= 07 && $h < 09) $file ='breakfast.php';
else if ($d == 6 && $h >= 09 && $h < 12) $file ='throughthemorning.php';
else if ($d == 6 && $h >= 12 && $h < 13) $file ='rewind.php';
else if ($d == 6 && $h >= 13 && $h < 17 && $m <= 30) $file ='nonstop.php';
else if ($d == 6 && $h >= 17 && $m >= 30 && $h <21) $file ='livetrend.php';
else if ($d == 6 && $h >= 17 && $m >= 35 && $h < 21) $file ='nonstop.php';
else if ($d == 6 && $h >= 21 && $h < 18) $file ='gennation.php';
else if ($d == 6 && $h >= 23) $file ='earlyhours.php';
else if ($d == 7 && $h >= 0) $file ='earlyhours.php';
require $_SERVER['DOCUMENT_ROOT'] . '/collection/profiles/' . $file . '';
?>
As you can see it figures the time and then drops the correct file in - there's five of these for everyday of the week (-2.php, -1.php, 0.php, 1.php, 2.php).
Does anybody have a solution? Ideally I need to stop the break, but I don't want my visitors to be scrolling +1 / 2 or -1 / 2 hours on for the same days rotation when it nears, and steps over midnight.
For example, right now the code is broken on -2.php until at least 2am (my timezone) so that it back track.
I've totally burnt myself out trying to figure this one out.
The problems arising from the change of day can become intractable. I'd tackle this a different way. Start by calculating the day and hour for the five periods your interested in and use DateTime to do the heavy lifting. Then, use a function to provide the schedule item for a particular day/time combination.
Here's a skeleton
<?php
date_default_timezone_set('Pacific/Auckland');
$now = new DateTime();
$oneHour = new DateInterval('PT1H');
$minusOne = (clone $now);
$minusOne->sub($oneHour);
$minusTwo = (clone $minusOne);
$minusTwo->sub($oneHour);
$plusOne = (clone $now);
$plusOne->add($oneHour);
$plusTwo = (clone $plusOne);
$plusTwo->add($oneHour);
echo returnFile($minusTwo);
echo returnFile($minusOne);
echo returnFile($now);
echo returnFile($plusOne);
echo returnFile($plusTwo);
function returnFile(DateTime $t) {
$day = $t->format('D');
$hour = $t->format('G');
// echo "Day:$day, Hour: $hour;<br>";
switch ($day) {
case 'Mon':
if ($hour<7) {
// Small hours Monday...
$filename = "smallMonday.html";
break;
}
if ($hour<12) {
// Monday morning
$filename = "morningMonday.html";
break;
}
break;
case 'Tue':
if ($hour >=23) {
// Late Tuesday
$filename = "lateTuesday.html";
}
default:
$filename = "Some other time";
}
return $filename;
}
?>
I haven't put in a complete schedule - you can work that out.
If you're using PHP 5.5 or later you can use DateTimeImmutable instead of DateTime which does away with all the cloning.
There's a fiddle here
Get rid of the leading zeros in your comparisons. Those are octal numbers and not decimals. You won't get the results you expect.
// 09 is not a valid octal number. It gets converted to zero in decimal.
else if ($d == 6 && $h >= 07 && $h < 09)
..
else if ($d == 6 && $h >= 09 && $h < 12) $file ='throughthemorning.php';

PHP on getting time before 6:30PM

This is my code below to get. but this code will invalidate the hour before 6PM which minute is above 30, how do I do it that
if today is "3" and today hour is still before 6:30PM , the if condition will works
My current code:
if( ($today=="3") && ($today_hour < "18") && ($today_min < "30") )
{
}
You should only check the minutes if the hour is actually 6. Change your condition to:
if ($today == 3 && ($today_hour < 18 || ($today_hour == 18 && $today_min < 30))) {
// Do stuff
}
Or easier to read:
$beforeTime = $today_hour < 18 || ($today_hour == 18 && $today_min < 30);
if ($today == 3 && $beforeTime) {
// Do stuff
}
Make sure to work with numbers as well, because doing string comparison on them will lead to unexpected results when the amount of digits is different.
Try this it will help you :
if ((date('d') == "03") && (date('H') < "18:30")) {
$condition = true;
}
H = 24-hour format of an hour (00 to 23)

How do I stop my IF statements from conflicting and how do I choose which one has priority?

I'm quite new to PHP and I've been asked to write a script that displays an image based on time. I've deducted that I need to use PHP's native 'date' function for this and up until I was asked to implement bank holidays and Christmas into it, all went well.
I tried to add the Christmas and bank holidays in as a separate if statement but that was when disaster struck and I haven't been able to figure out why it's come to a halt. I've tried using an online PHP validator to no avail.
Please don't be afraid to throw details and jargon at me as I really wish to expand my knowledge of PHP and rely less on the support of web forums in the future!
Here is the code:
<?php
// Date-time (day of month, month)
$d = date('j'); // Day of month: Numeric without leading zeroes
$m = date('n'); // Month: As above
$D = date('w'); // Day of week
$H = date('G'); // Hour of day
// REGULAR OPENING TIMES
// Closed before 9am on weekdays
if ($H < 9 && $D <= 5) :
$showroom_img = '/media/gbu0/pagehead/showroom_closed.jpg';
// Open before 5pm (but after 9, as first if statement overrides this) on weekdays
elseif ($H < 17 && $D <= 5) :
$showroom_img = = '/media/gbu0/pagehead/showroom_open.jpg';
// Closed before 10am on Saturdays
elseif ($H < 10 && $D == 6) :
$showroom_img = = '/media/gbu0/pagehead/showroom_closed.jpg';
// Open between 10am and 2pm on Saturdays
elseif ($H < 14 && $H > 10 && $D == 6) :
$showroom_img = = '/media/gbu0/pagehead/showroom_open.jpg';
// Any other time, display closed image :)
else :
$showroom_img = = '/media/gbu0/pagehead/showroom_closed.jpg';
endif;
// Holidays 2014
$xmas_starts = ($d == 23 && $m == 12 && $d > 17);
$xmas_ends = ($d == 26 && $m == 12);
$nyd = ($d == 1 && $m = 1);
// Easter Friday: April 18
// Easter Monday: April 21
// Early Spring B/H: May 5
// Late Spring B/H: May 26
// Summer B/H: August 25
// All bank holidays: 10am - 2pm
if( date >= $xmas_starts && $day <= $xmas_ends ) :
$xmas = true;
elseif( date = $nyd ) :
$nyd = true;
else :
$bankhol = false;
endif;
if( $xmas = true ) :
$showroom_img = "/media/gbu0/pagehead/showroom_xmas.jpg";
elseif( $bankhol = true && date('F', 'j') = strpos('April 18' || 'April 21' || 'May 5' || 'May 26' || 'August 25') || date('w') = 6 ) :
$showroom_img = "/media/gbu0/pagehead/showroom_bhol.jpg";
elseif( date('w') = 7 ) :
$showroom_img = "/media/gbu0/pagehead/showroom_closed.jpg";
else :
$showroom_img = "/media/gbu0/pagehead/showroom_open.jpg";
endif;
?>
First of all. I noticed a couple of bugs :
elseif( date = $nyd ) :
$nyd = true;
and
if( $xmas = true ) :
$showroom_img = "/media/gbu0/pagehead/showroom_xmas.jpg";
In PHP, '=' is the assignment operator, used to assign value to a variable. What you need here is the comparison operator, '=='. For example :
if( $xmas == true ) :
Or you could also do (it's pointed out in a comment already) :
if( $xmas ) :
Rgarding priority, the if statements are going to be checked in the order you write them in your code. TO ensure that a condition gets the highest priority, that has to be checked first.
Have you considered using the switch case function instead of elseif?
Switch case method:
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
Read more here: http://www.php.net/manual/en/control-structures.switch.php
if statements cannot conflict, and have no concept of priority. Each one is evaluated and executed in the order it appears, unless it gets skipped by code branching (e.g. an elseif would get skipped if a previous if or elseif in the same chain evaluated to true).
The cause of your problems is most likely your confusion of assignment and equality operators (= and ==).
In all situations, x = y is an assignment; i.e. it assigns the value of y to the variable x. This is the case even if you put it in an if statement, so it's usually something you want to avoid (although there are situations where it's useful).
In all situations, x == y is an equality comparison; i.e. it checks if the value of x is (or can be converted to) the same as the value of y. This is the one you usually want in an if condition.
To put it another way, you want to change this:
if( $xmas = true )
To this:
if( $xmas == true )
You'll need to do the same thing in a couple of other places as well.

Need specific time each week in PHP

I have a DIV on a page that I wanted to show only on Thursdays between 7pm and 8pm (local time) on a site. I made a post a while back and found my answer for that. Previous Post Here.
I was using this code to do so:
if( date('l') == "Thursday" && date('G') >= 19 && date('G') < 20 )
However now I need to show the div from 6:59:30 to 8:01pm (server time) and I'm not quite sure how I would format the statement above for that?
This would need to run weekly for an indefinite time until I remove the code.
if( date('l') == "Thursday" && date('Gis') >= 185930 && date('Gis') < 200100) {...
You should check out the php date manual for clarification: http://php.net/manual/en/function.date.php
if (date('l') == 'Thursday' && time() >= strtotime('18:59:30')
&& time() <= strtotime('20:01:00'))
if (date('l') == "Thursday" && date('His') >= '185930' && date('His') <= '200100')

Categories