PHP - Global, Update-Able Variable Available to All Clients - php

GOAL: To have a global variable that any php on my website can access. The variable would be a bool.
What I am stuck on is how I can store such a variable that is available to all php scripts, but can also be updated via php.
The variable is a bool that determines whether or not the site loads advertisements based off if a certain criteria was met that day. So, every day I will have a cron job that runs to reset this variable, thus meaning the variable needs to be update-able via php.
The only way I can think of to store it is either via a db table, which seems like overkill just for one little bool, or a json file that I store outside of the public_html directory.
With the json file, I would just perform a get on load with file_get_contents via my "class lib" file that is present on all pages of the site. Then do something similar to update it with the cron job.
NOTE: I do have a php file that is present on ALL of my pages, so including a file on every page is not a problem.
Is there a better way? It would be nice if there was a way I could just set a PHP superglobal or something, but I'm unsure if settings something like $_SERVER['custom-variable'] sticks or if it's just for that session.
Apologies if this is a simple mis-understanding of how PHP superglobals/constants work.
I appreciate any help.

A couple of options:
Just store it in the database. This is a perfectly reasonable solution.
Store it in a file, in whatever format you want. JSON is handy if you want to store anything more complex than a single string or number.
Store it in a PHP file which returns a value, e.g.
<?php return array("ads_enabled" => true);
then require() that file -- the require() call will return that value. If your server has a PHP opcode cache enabled, this will be faster than loading a normal file, as the contents of the file will be cached.
Note that the file cannot return false, as that's indistinguishable from the include() failing.
The following are not viable options:
Storing it in a session. Sessions are per-user, and start out empty.
Storing it in an in-memory cache, like APCu or Memcache. Caches are not persistent storage; the value may be evicted from the cache.
Storing it in an environment variable. Environment variables are awkward to update in most server environments.

SetEnv APPLICATION_ENV "development"
Use that in your Apache vhost definition if you are using Apache and have access to modify it. I think you can do something similar in .htaccess files.
You can use a .env file and a library for reading that file.
If you are using a front controller where all requests pass through a single index.php file then you can set a global variable or constant in there.

Related

How can I create a persistent array var in PHP?

I'm writing a web application in PHP and I want to declare an array, in which i want to save the host and how often this host has opened my web application. I want to add the variable to something like the application scope in JSP. I've tried to add this array to $_SERVER, but this hasn't worked. If I try to acess the variable in another file with $_SERVER[$_GET["id"]] the variable is always NULL. Can someone please help me?
Here my code:
if(empty($_SERVER[$_GET["id"]])){
$_SERVER[$_GET["id"]]=array($country, 1);
}else{
$_SERVER[$_GET["id"]][$country]+=1;
}
several things:
$_SERVER is for SERVER do not use it to play global array.
$_SESSION is returning null because you probably didn't declare any
session_start at the beginning of your file. If you don't do that, the session cookies (variables) are not shared and this is why its null.
this is the basic of vanilla php.
From here, you could explore a micro framework that has this built in...
UPDATE
due to your misconception of "session", what you want to do is to persist data. If you want to "share" this array of yours among different users (aka data sharing among session), I would recommend to persist via data storage:
sqlite/memory or sqlite/file
redis (value/key and its quick)
mysql or any sql/no-sql
least favorable IMO: write to a simple file and retrieve. The only issue with this, is that you will have "lock" condition but then again so will the other ones

Symfony 2 asset, check if file exists performance

on symfony 2, using Twig you can use the asset() function to link an image in the way
{{ asset('path_to_the_image') }}, now if the file does not exists then the src of the file keeps the same,
Thinking about that, I was tempted to create another Twig function on my TwigExtensions, in order to check the file existence, in order to do the following, If the file exists then I will use the given url and if does not exists then I will change the result of the function to a default image that I will use as a not_image image.
The motivation for this function is to always show an image to the user.
Now, my question.
I can't figure out the performance issues with this approach because I will check the file twice, the first time to check if exists and the other time is the request that asks for the file. And the usual thing to do is to put the asset address and in case the file does not exists replace it with some default file using javascript.
I will use php's file_exists function, and on the manual I have read that is very inexpensive and that in case that the file indeed exists the result is cached to avoid performance issues.
Thanks in advance...
file_exists triggers a read access to your file system (or, even just the FS metadata). This is very inexpensive indeed. Keep in mind that, when running a Symfony application, you’re usually accessing hundreds of PHP files alone.
The result of file_exists is cached indeed, but only while during the execution of a script. So, if you call file_exists several times within one script execution (and don’t call clearstatcache in between), the result is cached. If you call the script again later, PHP will look for the file again.
However, if you really worry about performance, you shouldn’t check for the files’ existence “on the fly”, but instead create a Symfony command that checks if all linked assets are valid during building or deployment.
This command would basically render all pages, and your custom asset function would, instead of returning a dummy image, throw an exception. This way, you only need to check once, during deployment, if all assets are valid.

PHP - How to share configuration data among sessions

I have a cluster of PHP hosts serving a small PHP script. The script retrieves an array of key/value pairs from the database at the beginning of the script, that are configuration values.
I would like to avoid the retrieving of these configuration data from the database for every request, in order to optimize.
My idea was that the script loads the data from the database only for the first request and it stores these variables into some kind of shared memory that is persistent among all sessions.
I've tried to use PHP global variables but they are all destroyed at the end of the script...
Also, I would like to avoid using a config file because as I said I have more than one host serving the script and I'd like to store the data centralized.
When I need to store small bits of data across scripts, I usually use apc
apc_add('config', array('a' => 'b'));
$config = apc_fetch('config');
...among sessions
rather implies that you are already using sessions - so why not just use a custom session handler?
You load the session data using the session id, and overload the config. Optionally you could set it up so you can call the read method and only return the config data without searching for conventional session data.
Probably the most efficient way to do this would be to run a daemon - that way you can keep the config data in PHP variables. There's a nice single threaded server implementation here.
You can keep this as:-
$_SESSION['_config_data']['index_1'] = 'value_1';
$_SESSION['_config_data']['index_2'] = 'value_2';
$_SESSION['_config_data']['index_3'] = 'value_3';
...
In this way, you will get all the configuration data stored in the session variable "$_SESSION['_config_data']".
But you need to check at the starting of the setting method, whether the session variable "$_SESSION['_config_data']" exists with some pre-filled data or not. If it is, then you don't need to set the configuration data for each page request.
Hope it helps.
Answer is memcached: http://memcached.org/
Its a sort thing that was meant to for this kind of scenarios and there are alot of good tutorials but official php documentation is a good starting point: http://php.net/manual/en/book.memcache.php

How can I store data in RAM memory using PHP?

Is there a way to store small data in RAM memory using PHP so that I can have access to the data between different session instead of regenerating it. Something similar to memcached (I don't have access to memcahced). My current solution is just to save the data in file.
APC?
It works differents from memcached; in memcached you can access the data from various languages (c, python, etc..) while APC works only for PHP.
EDIT are you sure that APC is installed correctly?
Did you add extension=apc.so in your php.ini? And to restart apache (im assuming youre on a lamp server with apache2)? What does you phpinfo(); say about APC?
This is a simply test that work perfectly for me:
<?php
/*
* page.php
* Store the variable for 30 seconds,
* see http://it.php.net/manual/en/function.apc-add.php
* */
if(apc_add('foo', 'bar', 30)){
header('Location: page2.php');
}else{
die("Cant add foo to apc!");
}
<?php
/*
* page2.php
* */
echo 'foo is been set as: ' . apc_fetch('foo');
p.s: i prefer to use apc_add over apc_store, but the only difference between them is that apc_add doesnt overwrite the variable but will fail if called twice with the same key:
Store the variable using this name. keys are cache-unique, so attempting to use apc_add() to store data with a key that already exists will not overwrite the existing data, and will instead return FALSE. (This is the only difference between apc_add() and apc_store().)
It's a matter of taste/task of the script, but the example above works with apc_store too.
You could always use an in-memory DB to save the data. Possibly overkill, though.
I am assuming you are on a shared server of some sort.
memcached or another caching solution is indeed the only way to do this.
Sessions, the most prominent method of persisting data across PHP pages, work based on files. You can change the session handler to be database based instead, but that's not RAM based, either.
As far as I can see, without changing your system on root level (e.g. to install memcached, or store session files on a RAM disk), this is not possible.
Create a file in /dev/shm and it will be kept in memory until the machine is rebooted. This may or may not be faster than using any old file, depending on your usage pattern.

Is there a variable scope that is accessible anywhere in PHP?

I'd like to create something like a very basic chat application. I don't want to use a database, since it'd cause a heavy load on an already strained db. I also don't want to use a flat file, because it have a feeling that it'd become a mess or that it'll have lots of read/writes...
So, I'm wondering if there is a way to have a variable that is accessible in any file and at any time.
Well if you don't want a file, you're left with shared memory.
You could try PHP's shared memory functions, or use an extension like memcache or APC.
You can't share variable values among separate requests - think of each request like the entire program is starting and finishing each time, even if there are several requests happening at once.
You could look into storing data in a cache layer (for example, memcached) however it sounds like you need to cache your database if it's under heavy load. I'd recommend caching your database (again memcached or file-based storage; serialize() data first) and then when that problem is solved store the chat data in the database (which is in turn cached). You need to store it persistently somewhere.
There isn't such thing. Try creating a basic file that saves serialized/json'd version of the variable you want, use php's flock to manage access to that file, cycle the file every hour/day. Since it's no big traffic simple app, I think this will be okay.

Categories