Does PHP have global variables that can be modified by one running script and read by another?
No, by design PHP is a "share nothing" architecture, which means nothing is shared between processes running at the same time or between requests running one after another. There are ways to share data, but you have to do it explicitly.
If you just want to share between 2 requests from the same user, sessions or cookies might be the way to go.
If you want to share between multiple users, you probably want some sort of shared persistence, either short term in a cache (eg. memcached) or more robust like a database.
Either way, the data is actually being retrieved and reconstructed on each request. It's just handled automatically for you in the case of sessions.
You can actually do this using shared memory, or APC (which is using shared memory itself).
You can use $_SESSION, i.e.:
script1.php
<?php
session_start();
$_SESSION['myVar'] = "something";
?>
script2.php
<?php
session_start();
echo $_SESSION['myVar'];
//something
?>
The only one which could be accessed between scripts is the superglobal $_SESSION array. This is because whatever you store in the array is sent to a cookie, which can then be picked up by the next PHP script.
Global variables simply mean that they can be accessed in the script regardless of the scope; that doesn't mean they can be sent between scripts.
So either you have to transfer the variables using the $_SESSION array (this stores a cookie on the client computer, so don't sent any sensitive information through that array) or you can either POST or GET between the scripts to send the variables.
Each request is handled by a php instance of its own. Global variables in php are only accessible from within the same php instance. However you can use something like the memchached module to share data between different instances (which should usually be faster than writing the data to the filesystem).
Not as such, but you can use cookies or sessions to maintain data for duration of a user's browsing experience, or you can write to a database or file on-disk if the information needs to persist beyond that.
Another common substitution for global variables in PHP is the shared use of a database like MySQL (albeit not a perfect one)
Global variables are bad in most programming. They're especially bad in multithreaded/multiuser systems like webapps. Avoid. If you must use global variables (rather than global constants) put them in a database with transactions guarding updates.
Since you talk about different scripts though, it sounds like what you really want is a web application framework in a more application oriented language --- something like Django (python) or Rails (ruby). These let you think of your code much more like a cohesive PROGRAM, rather than a lot of loosely connected scripts that process web requests.
I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx
It has functions to write, read, modify, check and delete data.
It implements serialization, and therefore supports all data types.
Here's how you can use it:
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
Related
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
I've done a fair bit of PHP over the years but I'm currently learning ColdFusion and have come across the Application.cfc file.
Basically this is a class that's created once (has an expire date). The class handles incoming users and can set session variables and static memory objects, such as queries. For example I can load site wide statistical data for one user in another thread from the Application.cfc. Something that would usually take a few seconds for each page would make the whole site quick and responsive.
Another example (just for clarification).
If I put an incremental variable that's set to 0 in OnApplicationStart this variable can be incremented with each user request (multiple users) or in OnSessionStart without the need to contact the SQL database since it's constantly in the server's memory under this application.
I was wondering if PHP has a similar file or object? Something that can be created once and used to store temporary variables?
The PHP runtime itself initializes the environment from scratch on every HTTP request, so it has no built-in mechanism to do this. Of course you can serialize anything into common storage and then read it back and deserialize on each request, but this is not the same as keeping it in-memory.
This type of functionality in PHP is achieved by outsourcing to other programs; memcached and APC are two of the most commonly used programs that offer such services, and both come with PHP extensions that simplify working with them.
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
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.
I have a script that has PHP on it, and a link that goes to a new script that alters that PHP. When writing the query and containing variables on the second script, do I need to use the same variables or are the new ones I create completely seperate? or can will the variables from the first script carry over to the second script if used?
If by "link" you mean you use require or include, then any variables that are defined in the same scope as the "link" will already be defined within that file's "global" scope (under most conditions).
If you are linking to another page via a typical HTML anchor tag, then the answer is no. You can, however, pass along information using HTTP GET method or create sessions through manipulations of $_SESSION in php or by setting cookies in the browser. All of the various ways of maintaining informaion across multiple links really depend on your needs. In the case where you would want to use HTTP GET, you could setup the link in script A to link to script B like this:
Click here
Then in script B you would access that data like this:
<?php
$data1 = $_GET['var1'];
$data2 = $_GET['var2'];
And use it however you need. Of course, be sure to perform sanity checks against the data before accepting it as reliable.
You can try and use sessions
As mentioned by everyone else, HTTP is stateless and nothing is shared unless you explicitly store it. Most of the time you will want to store these in the $_SESSION[] super global, but you could also store them in files, cookies, or the database, although the file system and database introduce larger overhead and cookies can easily be manipulated.
PHP is basically "nothing shared". So, when you build your link, you control the state of the $_REQUEST variable using the query parameters (GET or POST) and the hidden parameters (cookies).
The session ($_SESSION) is a convenient cookie/file storage to migrate common data between pages, but it is typically best to keep session lean and free of non-critical state details.