echo php variable between php scripts - php

I was given a script with different variables that are based on date and time on the top of XHTML Strict page.
<?php
date_default_timezone_set('America/Los_Angeles');
$time = new DateTime();
if($time < new DateTime('2011-10-31 18:00')){
$title="Before Halloween";
$cb1="2011,10,31,18,0";
}else if
...
?>
Halfway through the HTML code I have a second PHP script:
<?php
date_default_timezone_set('America/Los_Angeles');
countdown(2011,10,31,18,0);
function countdown($year, $month, $day, $hour, $minute)
{
...
?>
How can I echo $cb1 from the upper script into the second script so the third line looks something like countdown(echo $cb1); and updates automatically based on the upper script?

Since it is a string you will need to explode (take apart) at the comma, to create 5 variables. To do this you would use:
$cbarray = explode(",",$cb1);
countdown($cbarray[0],$cbarray[1],$cbarray[2],$cbarray[3],$cbarray[4]);
Or something simalar by putting each one in a named variable.

You could try to set $cb1 as a session variable instead so you can access it from anywhere in the file.
Maybe replace:
$cb1="2011,10,31,18,0";
with
$_SESSION['cb1']="2011,10,31,18,0";
And then your code in the second script would be: countdown($_SESSION['cb1']);

Related

A confusion about time() function in PHP

I cannot understand why the result of subtracting the current time from the variable of $_session['now'] that has included the previous time is zero.
I expected outputting the difference between the current time and the time when i have created the variable $student->now. Explain me please.
class Student
{
public function __set($key, $value)
{
$_SESSION[$key] = $value ;
}
public function __get($key)
{
return $_SESSION[$key];
}
}
session_start();
$student = new Student() ;
//__set function will be called ;
$student->now = time();
//__get function will be called ;
echo time() - $_SESSION["now"]; // output is zero ?!
The $_session['now'] variable is set in the line before the echo.
In the echo line the current time is compared to the time set in the line before.
Because both lines are executed directly after each other, both are executed within the same second. There will be a difference of milliseconds but time() function is measured in seconds, refer to: https://www.php.net/manual/en/function.time.php.
That's why both timestamps are the same and there is no difference between these when comparing them.
time() has a precision of ONE second, you are basically doing:
$now = time(); // e.g. 1627385278
echo time() - $now; // 1627385278 - 1627385278
This happens very fast, so the output is (almost always) zero.
The fact that your example code involves a "session" hints that you want to measure time between different HTTP requests. If that is the case, some logic is needed to ONLY set the stored value for the first time, but not thereafter.

Display name of the tools provided in the last X days using XPath in PHP

Back at it again with another XML/PHP problem. :)
On my webpage I want to display the names of the tools provided in the last X days. X is a number that will be entered by the user in a textbox, and after clicking the submit button, the names of the tools that have been provided in those last X days will appear.
This will be done by comparing the X value the user enters with the dates in my XML file, and to find the tools that match.
In my XML file, I have a "dateentered" node that stores a random date that I entered:
<tools>
<tool type="..." web-based="..." free="...">
<name>Facebook</name>
<description>...</description>
<url>...</url>
<subjects>...</subjects>
<creators>...</creators>
<category>...</category>
<price>...</price>
<dateentered>2020-12-01</dateentered>
</tool>
</tools>
Next, I created a function in PHP that basically converts the 'Y-M-D' format into days by subtracting the current date from whatever date you enter:
function time2string($timeline) {
$periods = array('day' => 86400);
$ret = '';
foreach($periods AS $name => $seconds){
$num = floor($timeline / $seconds);
$timeline -= ($num * $seconds);
$ret .= $num;
}
return trim($ret);
}
Then, I loaded my xml file using simpleXML:
$xml = simplexml_load_file('tools.xml');
So for example, using the XML code sample above and doing
$days = $xml->xpath("//tool/dateentered");
foreach ($days as $day) {
print (time2string(time()-strtotime($day)));
}
this converts '2020-12-02' to '1' and therefore outputs '1', meaning that the function works as it should.
With XPath, What I want to do is, I want to compare the value the user enters in the textbox with the converted 'dateentered' from my xml, and if they match, then I want to display the tool name.
So something like:
if(isset($_REQUEST["submit"])) {
// time2string function
$f_day = $_REQUEST["days"]; // getting the value the user enters in the textbox
$xml = simplexml_load_file('tools.xml');
// do something here
}
So let's say, using the xml sample I provided above, if the user enters 1 in the textbox, the output should be:
Facebook
How can I solve this?
I'm also open for different approaches besides having to create a function, this is just what I came up with.
Turns out, like #CBroe has said, I don't even need a function that converts date to days, instead, I can take advantage of PHP's date() and strtotime() functions as follows:
<?php
if(isset($_REQUEST["submit"])) {
$xml = simplexml_load_file('tools.xml');
$f_days = $_REQUEST["days"];
$days = date("Y-m-d", strtotime("-$f_days days"));
$xdays = $xml->xpath("//tool[dateentered = '$days']/name");
foreach ($xdays as $name) {
echo "<h1 align='center'>".$name."</h1><br>";
}
}
?>
And this will output:
Facebook

Highchart add three zeros in the loop

I have use library chart from this page link. Unfortunately, the data I download is not compatible, for example:
I get from JSON time:
time: 1346803200
this time is not displayed on the chart. I must add three zeros at the end (look like this: 1346803200000), then the chart displays correctly. So I have code:
for ($i=0; $i < count($chart['Data']) ; $i++) {
$time = $chart['Data'][$i]['time'];
}
I need add to variable $time numeric 000 (three zeros at the end). I can not add it this way:
$time = $chart['Data'][$i]['time']."000";
because variable $time change from int to string. I must have $time in integer type. Is there any way to add three zeros without changing the variable type inside the loop ?
Not sure why you are doing this or if there is a better way, but if type conversion is the only thing that worries you, you can explicitly cast it to int:
$time = (int)($chart['Data'][$i]['time']."000");
Also, not sure if this is your desired behavior, but just note that your $time variable will get overwritten with every iteration of the for loop.
And one more thing, you can achieve your desired output without the explicit conversion by just multiplying your result with 1000, like so:
$time = $chart['Data'][$i]['time'] * 1000;
This should be a better solution than concatenation when you are working with ints
Seriously?
$time = $chart['Data'][$i]['time'] * 1000;
You con multiply for 1000
$time = $chart['Data'][$i]['time']*1000;

PHP GET method in <a href>

I am creating a calendar function in php. Along with the function I need a "previous" and "next" link that show the previous or next month using the GET method. The links don't work the way I expect them to. From what I've found through debugging it doesn't look like it's actually adding or subtracting 1 from month.
This is currently what I have:
$month=$_GET["month"];//should initially set them to null?
$year=$_GET["year"];
//previous and next links
echo "<a href='calendar.php?month=<?php echo ($month-1)?>'>Previous</a>";
echo "<a href='calendar.php?month=<?php echo ($month+1)?>'>Next</a>";
//Calls calendar method that returns the calendar in a string
$calDisplay=calendar($month,$year);
echo $calDisplay;
PHP doesn't do calculations inside strings and doesn't parse PHP tags inside strings. You are already in 'PHP mode', and opening another PHP tag inside the string just outputs that tag as you may have noticed when you inspected the link in your browser.
Instead, try closing the string, concatenating the next/previous month (using the dot operator), and concatenating the last part of the link:
//previous and next links
echo "<a href='calendar.php?month=" . ($month-1) . "'>Previous</a>";
echo "<a href='calendar.php?month=" . ($month+1) . "'>Next</a>";
You can also calculate the values into variables first, because simple variables can be used inside double-quoted strings:
//previous and next links
$previousMonth = $month-1;
$nextMonth = $month+1;
echo "<a href='calendar.php?month=$previousMonth'>Previous</a>";
echo "<a href='calendar.php?month=$nextMonth'>Next</a>";
On the first request, you may not have a month at all, so you may want to check for that too, for instance using isset.
$month = 1;
if (isset($_GET['month'])) {
$month = (int)$_GET['month'];
}
As you can see, I already did an (int) typecast there too. Combining this with the variables version, allows you to make the code a little more solid by performing some checks on the input, and only output the previous/next links if they make sense.
$month = 1;
if (isset($_GET['month'])) {
$month = (int)$_GET['month'];
}
if ($month < 1 || $month > 12) {
// Invalid month. You can choose to throw an exception, or just
// ignore it and use a default, like this;
$month = 1;
}
//previous and next links, if necessary.
$previousMonth = $month-1;
$nextMonth = $month+1;
if ($previousMonth >= 0) {
echo "<a href='calendar.php?month=$previousMonth'>Previous</a>";
}
if ($nextMonth <= 12) {
echo "<a href='calendar.php?month=$nextMonth'>Next</a>";
}
Oh, and a minor detail. Personally I don't like to put 'big' chunks of HTML inside a string, so I'd rather use some template, or at least write it like this. As you can see, you can close and open PHP tags (just not inside strings), so you can output plain HTML from within your PHP code. The <?= $x ?> notation is a shorthand for <? echo $x; ?>.
//previous and next links, if necessary.
$previousMonth = $month-1;
$nextMonth = $month+1;
if ($previousMonth >= 0) {?>
<a href='calendar.php?month=<?=$previousMonth?>'>Previous</a>
<?php}
if ($nextMonth <= 12) {?>
<a href='calendar.php?month=<?=$nextMonth?>'>Next</a>
<?}
Try doing something like the following:
echo sprintf('Previous', http_build_query(array('month' => $month - 1)));
echo sprintf('Next', http_build_query(array('month' => $month + 1)));
While it seems more convoluted, it serves two purposes.
Its cleaner and less messing around with string concatination
You get to learn about sprintf and http_build_query functions which can be very useful in certain situations. sprintf is a string formatting function which basically takes a string as its first parameter and substitutes certain tokens with the next n parameters. In this example, %s is a token which means replace it with a string, which is passed as the second function. http_build_query takes an associative array and builds a http query from it. So in the code above, the http_build_query function will return month=11 (assuming the month was 12) for the Previous link. You can also add multiple array parameters and it will build the query string with the ampersands.
While the other answers do what you need, its always wise to look at and understand other PHP functions.
The $_SERVER REQUEST METHOD when you click on a link is 'GET'.
use the parse_str function and place your $_GET keys and variables into an array.
parse_str($_SERVER['QUERY_STRING'],$output);
print_r($output);
Maybe you can test for that. Is this what you are looking for?
Since everything you send via request is considered a String, try this casting integer.
HTML
<!-- previous and next links -->
<a href='calendar.php?month=<?php echo ((int)$month - 1)?>'>Previous</a>
<a href='calendar.php?month=<?php echo ((int)$month + 1)?>'>Next</a>

PHP Convert Minutes+Seconds to Seconds

Currently, I have the following time format like the following:
0m12.345s
2m34.567s
I put them in variable $time. How do I convert the variable to seconds only in PHP, like 12.345 for the first one, and 154.567 for the second one?
You can do it like this,
//Exploding time string on 'm' this way we have an array
//with minutes at the 0 index and seconds at the 1 index
//substr function is used to remove the last s from your initial time string
$time_array=explode('m', substr($time, 0, -1));
//Calculating
$time=($time_array[0]*60)+$time_array[1];
<?php
$time="2m34.567s";
$split=explode('m',$time);
// print_r($split[0]);
$split2=explode('s',$split[1]);
$sec= seconds_from_time($split[0])+$split2[0];
echo $sec;
function seconds_from_time($time) {
return $time*60;
}
?>
Demo here http://phpfiddle.org/main/code/gdf-3tj

Categories