I have a WordPress page that is build out of different PHP files. In one the files there is a PHP Script that calculates the deadline when the application closes. I would like to echo this at the bottom of my page, but that's part of a different file.
What am i doing wrong?
File 1:
<?php $deadline = {
$now = time();
$dueDate = get_field('due_date');
$dueDate = strtotime($dueDate);
$datediff = $dueDate - $now;
$daysLeft = floor($datediff/(60*60*24))+1;
$daysLeft = intval($daysLeft);
?>
<?php if($daysLeft == 0) {
echo 'Last day';
} elseif($daysLeft < 0) {
echo 'Deadline passed';
} elseif($daysLeft == 1) {
echo $daysLeft.' days left';
} else {
echo $daysLeft.' days left';
}
}?>
File 2:
<?php
include('/../content-challenge.php');
echo $deadline;
?>
Note: as you see the file where file 2 points at is in a dir above the file it needs to be echoed in.
File 1.
<?php
function deadline() {
$now = time();
$dueDate = get_field( 'due_date' );
$dueDate = strtotime( $dueDate );
$datediff = $dueDate - $now;
$daysLeft = floor( $datediff / ( 60*60*24 ) )+1;
$daysLeft = intval( $daysLeft );
if( $daysLeft == 0 ) {
echo 'Last day';
}elseif( $daysLeft < 0 ) {
echo 'Deadline passed';
}elseif( $daysLeft == 1 ) {
echo $daysLeft.' days left';
}else {
echo $daysLeft.' days left';
}
}
?>
File 2.
If the function is defined in functions.php
<?php deadline(); ?>
or if is defined in any other file then you must include this file like you did (be sure that path is good)
<?php
include('/../content-challenge.php');
deadline();
?>
Related
I have a php script here to create login at our datacenter for myself, but this script is doing the login for next week if i run it after 12:00 on monday, and a lot of times I'm not there the whole week, so I want to improve this script by asking for user input and pass the dates that I will be there so the script only picks up on those dates. I know i have to do this with stdin and I do have a part that works, but i have no idea on how to integrate this into the current script and how to make sure i can give multiple dates
My stdin part that does ask my for a date, but no idea on how to combine it:
<?php
function promptDateFromUser(string $prompt, string $dateFormat): DateTimeInterface
{
echo "{$prompt} [$dateFormat]: ";
$stdin = fopen('php://stdin', 'r');
$line = trim(fgets(STDIN));
fclose($stdin);
$dateTime = DateTimeImmutable::createFromFormat('Y-m-d', $line);
if (! $dateTime instanceof DateTimeInterface) {
throw new UnexpectedValueException('Invalid datetime format');
}
}
$dateTime = promptDateFromUser("Please insert date:", 'Y-m-d');
?>
My login script as of now:
<?php
require 'shared.php';
restore_exception_handler();
restore_error_handler();
$md = new RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$date = new DateTime();
$hour = (int)$date->format('H');
$dow = (int)$date->format('w');
if (($dow === 1 && $hour > 12) || ($dow > 1 && $dow < 6)) {
$add = 'P' . (8 - $dow) . 'D';
$date->add(new DateInterval($add));
}
if (($dow === 1 && $hour <= 12) || $dow === 0 || $dow === 6) {
if ($dow === 6) {
$date->add(new DateInterval('P2D'));
} elseif ($dow === 0 ) {
$date->add(new DateInterval('P1D'));
}
}
$tomorrow = $date->format('Y-m-d');
$duration = 720;
$customerId = 30;
$purpose = 'DCG visit';
$phoneNumber = '';
$name = 'SOME NAME, REMOVED FOR PUBLICATION';
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
for ($x = 0; $x < 5; $x++) {
$start = $tomorrow." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested for: ", $tomorrow, PHP_EOL;
$date->add(new DateInterval('P1D'));
$tomorrow = $date->format('Y-m-d');
}
?>
I'm a big php noob, so some explanation is greatly appreciated!
after some help from a friend, i managed to solve this:
#!/usr/bin/env php
<?php
include('shared.php');
restore_exception_handler();
restore_error_handler();
// Constants
$timeout = 45;
$md = new \RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$duration = "720";
$customerId = "30";
$purpose = "DCG visit";
$phoneNumber = "";
$name="SOME NAME, REMOVED FOR PUBLICATION";
// Functions
function requestInput($msg) {
global $timeout;
echo "$msg\n\nThe timeout for this selection is $timeout seconds.\n\n> ";
$fd = fopen('php://stdin', 'r');
$read = array($fd);
$write = $except = array(); // we don't care about this
if(stream_select($read, $write, $except, $timeout)) {
$choice = trim(fgets($fd));
}
echo "\nYou typed: $choice\n\n";
return $choice;
}
// Start of program
$date = new DateTime();
$weekchoice = (int)requestInput("Which week would you like to request access for?\n1) Current week\n2) Next week\n3) Specific week number");
if ($weekchoice == 3) {
$weeknumber = (int)requestInput("Please enter a numeric week number");
} else {
$weeknumber = (int)$date->format("W");
if ($weekchoice == 2) {
$weeknumber += 1;
}
}
// We override $date with the start of the chosen week
$date->setISODate($date->format("Y"), $weeknumber);
echo "Thanks, you chose week $weeknumber which starts with " . $date->format("l d F, Y") . " \n\n";
$dayschoice = requestInput("Please enter the days you want access, as a space separated list:\n1) Monday\n2) Tuesday\n3) Wednesday\n4) Thursday\n5) Friday\n\nExample: 1 3 5");
$daylist = explode(' ', $dayschoice);
$processedDays = [];
foreach ($daylist as $eachday) {
$iday = (int)$eachday;
if ($iday == 0 || $iday % 7 == 0) { // No Sundays, also (int)"" -> 0, which is terrible
continue;
}
$add_days = $iday - 1; // Sums 0 if Monday, 1 if Tuesday and so on...
$newdate = new DateTime($date->format("Y-m-d"));
$newdate->modify("+$add_days days");
$processedDays[] = $newdate;
$formatted = $newdate->format("l d F Y");
echo "Processing day $iday, which is $formatted\n";
}
$hour = $date->format('H');
$tomorrow = $date->format('Y-m-d');
$confirm = requestInput("\nRequest access for these days? Yes/No");
if ($confirm != "Yes") {
echo 'Good bye!';
exit(0);
}
foreach ($processedDays as $reqDay) {
echo "Submitting " . $reqDay->format("l d F Y") . "\n";
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
}
foreach ($processedDays as $reqDay) {
$start = $reqDay->format('Y-m-d')." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested: ", $reqDay->format('l d F Y'), PHP_EOL;
$tomorrow = $date->format('Y-m-d');
}
?>
I have following code where inside image tag I open php tag and decide different images based on ifelse() condition. I want to add different titles for the images selected but could not come up with a solution. The code is as follows:
<img title = "Last assessment for this child was submitted <?php if ($time == 0){echo $time;}else{echo $time - 1;}?> Month(s) ago."
src="<?php
if ($record->$period == 0) { echo base_url()."img/warning.png";}
else{
date("M d, Y", strtotime($record->$period));
$vtime = new DateTime($record->$period); ///////////////////////
$today = new DateTime(); // for testing purposes ///Calculate Time period//
$diff = $today->diff($vtime); ///
$time = $diff -> m;
if($time <= 4)
{echo base_url()."img/green.png";}
elseif( $time > 4 && $time <= 6)
{echo base_url()."img/yellow.png";}
elseif($time >= 6)
{echo base_url()."img/red.png";}
}
"
/>
I want different title for the first condition. i.e. If the first condition is true and the image shown is "warning.png". Then the image title should be "Check record" instead of title "last assessment submitted was ...."
Any help is much appreciated.
You can simply use the following. Just nest current if...else condition in another if...else condition on title tag also.
<img title = "
<?php if($record->period==0)
echo "Check record";
else { ?>
Last assessment for this child was submitted <?php if ($time == 0){echo $time;}else{echo $time - 1;}?> Month(s) ago.
<?php } ?>"
src="<?php
if ($record->$period == 0) { echo base_url()."img/warning.png";}
else{
date("M d, Y", strtotime($record->$period));
$vtime = new DateTime($record->$period); ///////////////////////
$today = new DateTime(); // for testing purposes ///Calculate Time period//
$diff = $today->diff($vtime); ///
$time = $diff -> m;
if($time <= 4)
{echo base_url()."img/green.png";}
elseif( $time > 4 && $time <= 6)
{echo base_url()."img/yellow.png";}
elseif($time >= 6)
{echo base_url()."img/red.png";}
}
"
/>
Just like I've said in the comments, you could just separate the logic, make your calculations here and there. After you are done with it, set the variables and then echo it out in the presentation:
<?php
// initialization
$title = '';
$src = '';
// logic
$time = ($time == 0) ? $time : $time - 1;
$title = "Last assessment for this child was submitted %s Month(s) ago."; // initial
if ($record->$period == 0) {
$src = base_url() . "img/warning.png";
// override $title
$title = 'Check record';
} else {
$vtime = new DateTime($record->$period);
$today = new DateTime();
$diff = $today->diff($vtime);
$time = $diff->m;
if($time <= 4) {echo ;
$src = base_url()."img/green.png";
} elseif( $time > 4 && $time <= 6) {
$src = base_url()."img/yellow.png";
} elseif($time >= 6) {
$src = base_url()."img/red.png";
} else {
// whatever you need to do
}
}
$title = sprintf($title, $time);
?>
<!-- HTML MARKUP -->
<img title="<?php echo $title; ?>" src="<?php echo $src; ?>" />
You should avoid putting so much PHP code inline in the HTML to keep your code readable.
if ($record->period === 0) {
echo '<img src="img/warning.png" title="Warning title" />';
} else {
// Are you sure this does what you want?
// You probably need $record->period. (no $)
$vtime = new DateTime($record->$period);
$today = new DateTime();
$diff = $today->diff($vtime);
$time = $diff->m;
$title = 'Last assessment for this child was submitted ' .
($time === 0 ? 0 : $time-1) .
' month(s) ago.';
if ($time <= 4) {
echo '<img src="img/green.png" title="'. $title . '" />';
} else if ($time <= 6) {
// Don't need to check if it's bigger than 4, you've already checked this
// in the initial "if" and if that was succesful, we wouldn't be here.
echo '<img src="img/yellow.png" title="'. $title . '" />';
} else {
echo '<img src="img/red.png" title="' . $title . '" />';
}
}
PHP is easily embed with the HTML. So use it.
$imageURL = "";
if ($record->$period == 0) {
$imageURL = base_url() . "img/warning.png";
} else {
// date("M d, Y", strtotime($record->$period)); // This is not usable remove this statement
$vtime = new DateTime($record->$period); ///////////////////////
$today = new DateTime(); // for testing purposes ///Calculate Time period//
$diff = $today->diff($vtime); ///
$month = $diff->m;
if ($month <= 4) {
$imageURL = base_url() . "img/green.png";
} elseif ($month > 4 && $month <= 6) {
$imageURL = base_url() . "img/yellow.png";
} else {
$imageURL = base_url() . "img/red.png";
}
}
Rewrite your image tag as follow:
<img title = "Last assessment for this child was submitted <?php echo ($time)? $time - 1: $time; ?> Month(s) ago."
src="<?php echo $imageURL; ?>" />
There are some mistakes with your code.Kindly check the below points for further developments.
date("M d, Y", strtotime($record->$period)) : Why this statement is there as you have not saved the result saved by the date function.
$vtime : What is vtime ? Variable should I short and meaningful name.
$diff->m : This will return the month number so to be more specific instead of $time use $month as variable name to store the month value.
Regarding the if condition
First If : checking for $month is <= 4 : correct
Second If: checking for $month > 4 or <=6
Third elseif : in your old code. Why we need this because if it is not
satisfied by above two conditions then that means it is compulsory >= 6
then put this in else part directly.
I have this code, and it's not returning the images correctly, at a certain time of day I need an image to change. However, the code isn't putting the right image in, the cover works, have I done the date and time wrong?
<?php
// H = hour
// i = minute
// n = day of the week
$dj = 'cover';
if(date("Hin", time()) == '06001'){ $dj = 'test1'; }
elseif(date("Hin", time()) == '06002'){ $dj = 'test1'; }
elseif(date("Hin", time()) == '14006'){ $dj = 'test3'; }
// 06001 = Monday at 06:00
// 06002 = Tuesday at 06:00
// 14006 = Saturday at 13:00
?>
<img class="cover" src="img/djs/<?php echo $dj; ?>.png" alt="DJ <?php echo $dj; ?>" />
n is not day of the week. it's a numeric representation of a month, without leading zeros (1 to 12)
I think this is your problem.
If you want day of the week, you have to use capital N.
So your code would be like:
<?php
// H = hour
// i = minute
// N = day of the week
$dj = 'cover';
if(date("HiN", time()) == '06001'){ $dj = 'test1'; }
elseif(date("HiN", time()) == '06002'){ $dj = 'test1'; }
elseif(date("HiN", time()) == '14006'){ $dj = 'test3'; }
// 06001 = Monday at 06:00
// 06002 = Tuesday at 06:00
// 14006 = Saturday at 13:00
?>
<img class="cover" src="img/djs/<?php echo $dj; ?>.png" alt="DJ <?php echo $dj; ?>" />
I believe what you are trying to do is show the image for the duration between those times. If this is the case, then try the following:
<?php
$dj = 'cover';
$day = date("N", time());
$time = (date("H") * 60) + date("i"); // current time in minutes
switch($day) {
case 1: // Monday
if($time >= 360) {
$dj = 'test1';
}
break;
case 2: // Tuesday
if($time >= 360) {
$dj = 'test1';
}
break;
case 6: // Saturday
if($time >= 840) {
$dj = 'test3';
}
break;
}
echo sprintf('<img class="cover" src="img/djs/%s.png" alt="DJ %s" />', $dj, $dj);
In this example, the image will be displayed as 'cover' after every day at midnight, but will display 'test1' etc, after the proposed periods. The condition $time > 360, etc, are based on the minutes from the start of the day, so 360 is 6 AM.
Since (in the example you supplied), you wish to show 'test' on both Monday and Tuesday starting at 6 am, you can simplify the code by allowing the case to fall through and run the same code for both scenarios as follows :
<?php
$dj = 'cover';
$day = date("N", time());
$time = (date("H") * 60) + date("i"); // current time in minutes
switch($day) {
case 1: // Monday
case 2: // Tuesday
if($time >= 360) {
$dj = 'test1';
}
break;
case 6: // Saturday
if($time >= 840) {
$dj = 'test3';
}
break;
}
echo sprintf('<img class="cover" src="img/djs/%s.png" alt="DJ %s" />', $dj, $dj);
<?php
$time = date('Hi');
if ($time > 0030) {
echo "closed";
} elseif ($time >= 0800) {
echo "open";
}
?>
This is the code i'm using for a client's website. In short it's a code that'll show if the client's business is open or not.
My client's working hours are between 8am to 12:30am.
I was wondering if there's an easier way of doing this or am I doing this right?
Try this:
<?php
date_default_timezone_set('Asia/Calcutta'); # set timezone according to your requirement
$now = new DateTime();
$start = new DateTime('today 08:00:00');
$end = new DateTime('tomorrow 00:30:00');
if ($start <= $now && $now < $end) {
echo "open";
}
else{
echo "close";
}
?>
I have an event calendar that starts on Sunday. I must change it to start on Monday.
Part of my code:
<html>
<body>
<?php
$dagteller=$firstDayArray["wday"];
$mDay=$firstDayArray["mday"];
define("ADAY", (60*60*24));
$mydate=getdate(date("U"));
define("ADAY", (60*60*24));
for ($count=0; $count < (6*7); $count++) {
$dayArray = getdate($start);
if (($count % 7) == 0) {
if ($dayArray["mon"] != $month) {
break;
} else {
echo ("</tr ><tr>\n");
}
}
if ((!isset($_POST['month'])) || (!isset($_POST['year']))) {
$nowArray = getdate();
$month = $nowArray['mon'];
$year = $nowArray['year'];
$day = $nowArray['day'];
} else {
$month = $_POST['month'];
$year = $_POST['year'];
}
// on my table
echo ("<td bgcolor=\"#DDDDDD\"><center>".$dayArray["mday"]."</center></td>\n");
$start += ADAY;
?>
</body>
</html>
Read the PHP date manual for yourself:
http://www.php.net/manual/en/function.date.php
The 'W' identifier will help you