php variable with site wide scope - php

I'm using Kirby CMS and creating a little snippet which limits by posts by what number they are, and what date they are. A way to create a 'autopost' system basically.
$today = new DateTime("now"); //Declare today
$startdate = new DateTime("2013-09-12"); //Declare startdate
$interval = $startdate->diff($today); //Find the difference between startdate & today
$latest = $interval->format('%a'); //Declare $latest variable to be that interval, formatted as integer
So I have that little bit which creates my $latest variable which I can then use to control the posts that are displayed.
My problem is, I don't want to have to change my $startdate on every different kind of page template I have, so I want to make it site-wide somehow.
I tried putting it as a snippet with Kirby's snippet() function but that doesn't work. The snippets must be being brought into the page after the snippet has already been run I guess.
How can I make my snippet apply to my whole site?

PHP doesn't have site-wide variables. The best you can do is put the assignments in a script, e.g. site.php, and have all your pages begin with require 'site.php'; to initialize these variables.

Related

Can not redeclare function doing while loop

I'm new to functions and I'm probably not doing it as well as I could so could use some help with this. I'm pulling stock information from a web sites API. All the information being pulled is done with several .php pages and I have one file that includes all the necessary pages. So I have something like this:
pullBalanceSheet.php for all the balance sheet data
pullIncomeStatement.php for all the income sheet data
etc, there are 10 pages. All pages can run independently of each other and was created like this to make easy to test each API call.
I have a master page (pullData.php) that contains the necessary includes for each page so it effectively runs all the pages as a single page. I hope this makes sense.
Some of my pages contain a function and this is where I'm probably not doing it the best way, but the pages work to pull the correct data. These pages pull quarterly financial information for the last 5 years. The issue is that every company states quarterly financial dates differently. So let's say it's January 2019 and some company quarterly will state Quarter 2, 2019 even though it really isn't Quarter 2 2019 until March 2019. So my code basically needs to capture possible future dates, so my code looks like this:
$fiscal_year = date("Y");
$fiscalPeriod = 'Q1';
pulldataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey);
$fiscalPeriod = 'Q2';
pulldataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey);
$fiscalPeriod = 'Q3';
pulldataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey);
$fiscalPeriod = 'Q4';
pulldataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey);
//year 2
$fiscal_year = $fiscal_year-1;
$fiscalPeriod = 'Q1';
pulldataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey);
$fiscalPeriod = 'Q2';
pulldataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey);
$fiscalPeriod = 'Q3';
pulldataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey);
$fiscalPeriod = 'Q4';
pulldataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey);
..etc for 5 years. The API looks at the $fiscal_year and the $fiscal_period and returns data if it's available.
The function is this:
function pullDataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey) {
// function code here
}
All my code works when pulling one stock. I'm now working on pulling multiple stocks by using a while loop on my pullData.php master page and this is where I'm having the issue. Since the code is repeating itself for each new stock, I'm getting a fatal error cannot redeclare function. I understand why this is happening since the loop is being treated as a single page and when it hits the second stock, it errors. I'm trying to figure out how to get around this. I have used
if(!function_exists('pullDataBS')) {
function pullDataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey) {
//function code here
}
}
And I get a undefined function pulldataBS error when it hits the function call at the very first time (3rd line of code where it tries the first pulldataBS in this example). Here is my pulldata.php master page:
while($research = mysqli_fetch_array($queryResearch)) {
$_SESSION['ticker'] = $research['symbol'];
include('pullBalanceSheet.php');
include('pullIncomeStatement.php');
// etc
}
I'm assuming the !function_exists is not correct or I have some other critical issue with the way I coded my function. I hope this all makes sense. Let me know if you need any other code. Thanks in advance!!
First of all, you should not include pullBalanceSheet.php and pullIncomeStatement.php files in each iteration of while loop. Take below two lines outside of while loop.
include('pullBalanceSheet.php');
include('pullIncomeStatement.php');
Now comes to the problem, you must not declare your function(s) over and over again, just declare it once and call it (with appropriate arguments) multiple times as per your need. Having said that, you can use defined() along with define() functions to solve your function redelaration problem.
if(!defined('PULL_DATA_BS')){
define('PULL_DATA_BS', 'pullDataBS');
function pullDataBS($fiscal_year,$fiscalPeriod, $username,$password,$apiKey) {
//function code here
}
}
This way this function won't get declared more than once. Ideally, you are supposed to encapsulate the entire code of a file with below block.
xyz.php
<?php
if(!defined('XYZ_PHP')){
define('XYZ_PHP', 'xyz.php');
// file code
}
?>
This way, you will prevent yourself(and somebody else) from including this file code more than once.

Store old folder size in session php

I calculation a size of a folder using php and then store it in session, than i delete some files with other function and than calculate size of folder,
i want difference of both state old and new
But session stores every time new data and difference becomes 0
How do i maitain old size in session and prevent it from overwriting?
here is some part of code
$this->size_session = $currentsize;
$_SESSION['oldsize']=$this->size_session;
i calculate new size after submit button
if($_REQUEST['file_delete']):
$this->size_now = $currentsize;
$_SESSION['oldsize']- $this->size_now;
endif;
You should read the $_SESSION['oldsize'] to another variable BEFORE changing its value:
$old_size = $_SESSION['oldsize'];
if ($_REQUEST ... ):
(...)
endif;
$difference = $old_size - $_SESSION['oldsize'];
Only that $_SESSION['oldsize'] is not a very good name, shouldn't it be 'actualsize', since you use it to store the actual size? ;)
Not sure if you typed this example manually or copy/paste, but:
$_SESSION['oldsize']- $this->size_now;
Should probably look like this:
$difference = $_SESSION['oldsize'] - $this->size_now;

PHP Timezone adjust as per user

Im creating a UI where users get to choose their timezone. My backend is PHP and I know you can do it a few ways but I had questions about all of them and which way is the best:
http://ca2.php.net/date_default_timezone_set
//where America/Los_Angeles will be changed based on user
date_default_timezone_set('America/Los_Angeles');
Does this change the server timezone for ever user or just what is being exported? is there any performance issues with this?
What if it was a function like this...?
date_default_timezone_set('America/Los_Angeles'); -08:00 set in php.ini
$date = "2014-01-01 12:00:00";
$new_time_zone = "America/New_York" // -05:00 = +3 hours difference
function adjust_time_zone($string, $zone){
$datetime = new DateTime($string);
$new_zone = new DateTimeZone($zone);
$datetime->setTimezone($new_zone);
return ($datetime->format('Y-m-d H:i:s'));
}
adjust_time_zone($date, $new_time_zone);
Results(i tested this):
2014-01-01 15:00:00 //3 hours ahead.
in this format everything stamped in the system would be on LA time and exported would be the change...
I know there is allot of these Timezone threads but there seems to be allot of "i do it like this" and not any solid "this way blows my socks off="
Thanks for any help you can give!
I store everything in the db as a datetime and UTC timezone.
I store the user's timezone in the db ($timezone).
So when a time ($time) is taken from the db, I run it through the following function:
function changetimefromUTC($time, $timezone) {
$changetime = new DateTime($time, new DateTimeZone('UTC'));
$changetime->setTimezone(new DateTimeZone($timezone));
return $changetime->format('m/d/y h:i a');
}
This returns the time in the user's timezone, formatted.
edit: you can see the db table of timezones in this thread:
Generating a drop down list of timezones with PHP
Well it looks like what you have should work for you. This is an alternate method, although not necessarily better. You can just use PHP's mktime and pass the hour offset to it.
<?php
print "<br>Date: ".date("Y-m-d H:i:s");
// DEFINE AN OFFSET
$offset = -5; // TIMEZONE OFFSET: '-5' FOR NEW YORK
// ADD THE OFFSET TO THE CURRENT TIME
print "<br>Date Offset: ".$date_offset = date("Y-m-d H:i:s", mktime(date("H") + $offset, date("i"), date("s"), date("m"), date("d"), date("Y")));
I found a great solution to the problem - and to adapt the date and time settings on my page according to the users settings.
Ready build js code
Some developers that had the exact same problem build a javascript solution to the code. You don't need to know javascript as long as you follow these instructions.
Go to https://bitbucket.org/pellepim/jstimezonedetect/src/default/
Read through the readme file if you want to
Either download the script as an NPM package or download it manually by pressing "downloads" in the left menu.
If you pressed downloads to manually download the script press "Download repository" to get the files.
Create a js folder - named "js" in your project. (optional)
Unzip the jstimezonedetect files into the js folder. I chose to name the unziped file "jstimezonedetect".
To reach the files above my current directory is /js/jstimezonedetect/.
In your header code (important it is in header since the time-zone will affect the full code on the rest of your page unless you run a function.
Enter the following code to your php file:
echo '
<script src="js/jstimezonedetect/dist/jstz.min.js"></script>
<script>
document.cookie = "usertimezone="+jstz.determine().name();
</script>
';
$settimezone = $_COOKIE['usertimezone'];
date_default_timezone_set($settimezone);
The first line of script will import the jstz.min.js file from the importat jstimezonedetect project.
Second line will create a cookie (you can later delete the cookie if you want to).
In the third line I get the cookie into the php script and then I use PHP date_default_timezone_set();
(https://www.php.net/manual/en/function.date-default-timezone-set.php)
to set the timezone.
Worked perfectly for me. :) Ask if something is unclear.

change global variable on given date

I guess, this is a very simple question. I want my wordpress theme to automatically change some global variables on a given date.
My Theme changes color and some other things every two months. From now on, I want to type in the needed variables before that date and let Wordpress do the changes. I could do that from within the loop, so that the first person who enters the site on that date initiates the change. But that would mean extra code, everytime the loop is called. Is it possible to perform that task automatically?
I haven't used WP in ages, but I think this will work, change time_to_change_theme to the forward date you want. I have no idea where to put this, I am sure you will work it out though.
<?php
$time_to_change_theme = strtotime("2012-12-31 12:12:12"); // the time in the future you want to change the theme
$time_now = strtotime(now);
if($time_to_change_theme > $time_now)
{
echo "Use current theme";
}else{
echo "Change theme";
update_option('current_theme', '[theme name]'); // this should update the current theme
}
?>
Uses code from this post by harmen

Display content based on date with PHP

I'm putting together a contest site built on Wordpress. Legally, the contest has to start at midnight. To avoid being up at midnight to set up the content, i'd like to build some PHP logic to show everything after the start date, and before then display some basic HTML for a splash page. I'm a TOTAL programming newb, but i'm trying to work the problem out, here's what I have so far:
<?php
// The current date
$date = date('Y, j, m');
// Static contest start date
$contestStart = ('2012, 02, 03');
// If current date is after contest start
if ($date > $contestStart) {
//contest content?
}
else {
// splash content?
}
?>
I feel like there is smarter ways to do this. My site is fairly large... wrapping the whole thing in an if statement seems ridiculous. Maybe a redirect to a different page altogether based on the date?
Any help is appreciated.
You will want to modify your WordPress theme so that the changes can be site-wide.
Log in to your WordPress installation.
Navigate to Appearance > Editor
In the Templates section, go to header.php
At the very beginning of header.php, insert your code :
<?php
$date = time();
$contestStart = strtotime('2012-02-03 00:00:00');
if ($date < $contestStart) {
?>
<html>
Insert your whole splash page here.
</html>
<?php
exit;
}
?>
//The normal template code should be below here.
Don't forget to click the "Update File" button on WordPress when you're done; and like the others said, make sure that your specified time is synced with whatever timezone the server is in.
I suppose technically your code's logic would work but yes, there are much better ways of doing this. However, for your purpose we will go simple.
You should be comparing against a timestamp and not a string. Try this:
<?php
// The current date
$date = time();
// Static contest start date
$contestStart = strtotime('2012-02-03 00:00:00');
// If current date is after contest start
if ($date > $contestStart) {
//contest content?
}
else {
// splash content?
}
?>
You can put the splash and content components in separate .php files, and simply include() then within the conditionals.
if ($date > $contestStart) {
include("SECRETDIR/contest.php");
}
else {
include("SECRETDIR/splash.php");
}
You'll want to set up an .htaccess so that people cannot point their browsers towards secretdir and directly access contest.php
You don't have to wrap the content, you can have something like:
<?php
if ( time() < strtotime('2012-02-03 00:00:00') ) {
echo "not yet!";
exit;
}
//code here wont be executed
Be careful of timezones! Your server might be in a different timezone than your content.
// setup the start date (in a nice legible form) using any
// of the formats found on the following page:
// http://www.php.net/manual/en/datetime.formats.date.php
$contestStart = "February 1, 2012";
// check if current time is before the specified date
if (time() < strftime($contestStart)){
// Display splash screen
}
// date has already passed
else {
// Display page
}

Categories