PHP Identical Variable Names - php

I'm really inexperienced when it comes to PHP and hoping someone can clarify something for me when it comes to how variables are handled in PHP.
I have a PHP Web App that I created and needed to make a quick duplicate of, so I simply copy and pasted this app into a new folder on the same server.
I am wondering are there any concerns if the apps, in 2 different folders, have the exact same variable names?
I'm thinking of an accidental overwrite situation. If "no", then can someone explain to me why there is no concern?

No, there will not be any collisions between application global variables as long as the two application directories are truly separate and don't include files from one another. When a PHP script runs, the HTTP request that initiated it can be thought of as an isolated incident. It is separated and isolated from all other requests to the same application (even concurrently) and from other applications.
Each script gets its own variable namespace when execution starts, and that environment is terminated and deleted from memory when the script completes.
Now, if you happen to be using $_SESSION and both applications use the same value for session_name() and run on the same domain name, there is the possibility that values persisting in $_SESSION can collide between your application instances. This is simply solved by changing the value for one of the applications from the default PHPSESSID:
// Application 1
session_name("APP1");
session_start();
// Application 2
session_name("APP2");
session_start();
You probably are already aware of this, but I'll say it to be complete. Wherever possible, it is advised to abstract out aspects of the code that can be shared between the two application instances and included by both of them. This is in keeping with the DRY principle, and will save you lots of headaches if you ever have to make modifications to the code both applications share.

In my opnion you may or may not use indenticle variables names in different folders. this depends on the functionality of your app. you need to do a little research on google 'scop of global and local variables in php'.
In short, yes, you can duplicate the app into new folder, you just need to update/reset the paths (for example the include files paths) and database connection strnigs (if your app use database to store data).

Related

Is PHP session still used nowadays?

Is there a more contemporary alternative to PHP session or is PHP session still the main choice to store information? I read this: https://pasztor.at/blog/stop-using-php-sessions. I'm still learning PHP and frankly, I'm quite clueless.
Your first assumption is incorrect. PHP Sessions are not where you store data. Databases, files, Document stores, etc. are where you store your data.
Session "data" is simply the variables included in the $_SESSION array in serialized form. You can run serialize() and unserialize() on variables to gain some insight into what these look like.
In your script, once you have started a session using session_start(), when you add change or delete variables in $_SESSION, php serializes this and stores it for you.
Once a session exists, and a user makes another request that is identified as being the same user (having the same session id) which has typically passed to the client via a cookie, then upon issuing session_start(), PHP reads the serialized data in the session file, and unserializes it, and stores it back into $_SESSION.
By default, PHP will store the individual session data as files on the filesystem. For a small or medium size application, this is highly performant.
So to be clear, what people store in PHP sessions is basically variables read out of whatever other persistent storage you might have, so that you can avoid doing things like re-querying a database to get the name and user_id for a user who has already logged into your application.
It is not the master version of that data, nor the place through which you will update that data should it change. That will be the original database or mongodb collection.
The article you posted has a number of stated and unstated assumptions including:
Devops/Sysadmins just decide to reconfigure PHP applications to change the session handlers (misleading/false)
The deployment involves a load balancer (possibly)
The load balancer doesn't support or use sticky sessions
He then goes on into some detail as to several alternatives that allow for shared session handlers to solve the race conditions he describes
As you stated, you aren't clear yet what sessions actually are, or how they work or what they do for you. The important thing to know about PHP scripts is that they are tied to a single request and sessions are a way of not repeating expensive database reads. It's essentially variable cache for PHP to use (or not) when it suits your design.
At the point you have a cluster, as pointed out in the article people often store data into shared resources which can be a relational database, or any of many other backends which each have different properties that match their goals.
Again, in order to change the session handlers, there is typically code changes being made to implement the session handler functions required, and there are ways to code things that mitigate the issues brought up in the article you posted, for just about every persistence product that people use.
Last but not least, the problems described exist to whatever degree with pretty much any clustered serverside process and are not unique to PHP or its session mechanism.
Usually, that will depends on the use case and other requirements of your application and most of the time people will use PHP frameworks to handle sessions.
Take for example, for Yii 2 framework, the framework provides different session classes for implementing the different types of session storage. Take a look at here https://www.yiiframework.com/doc/guide/2.0/en/runtime-sessions-cookies.
Learning the different types of sessions available out there, allows you to be able to make decisions by weighing the pros and cons. You can also read here for more understanding https://www.phparch.com/2018/01/php-sessions-in-depth/

Static object that is accessible to all users like Application.cfc

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.

How long will an instance of a PHP class last?

How long does the instance of a class, object, in PHP last. Is it confined to the running script or will it last for a session? If it does last for a session is this regardless of whether the PHP script has start ed the session?
A simple question but this makes a big difference to me because it will mean user data will survive as an on the server and won't need storing in the session variable. Hence affecting some fundamentals of my design.
Thanks
Colin
the question doesn't really belong to OOP but to PHP behavior in general
All PHP data is going nowhere as well as PHP script itself.
PHP scripts execution is atomic. It's not like a desktop application constantly running in your browser, and not even a daemon with persistent connection to your desktop application. It's more like a command line utility - doing it's job and exits.
That's why using external storage, like file or database is required. But of course you can save only strings there, not instances of variables or anything of the kind. Strings only.
It depends on the way PHP is configured. If PHP is configured as CGI, instances would be lost on each invocation. PHP would be invoked for each http request.
If PHP is configured as a module, then there would be multiple processes handling PHP requests. So, the instance would survive in "that particular" process. But subsequent requests might be handled by a different process.
If you need class instance to survive, you will need to serialize it and store it in DB or file.
If this information is transient (or stored somewhere else) you can store (seralize) it in session. One such example is user's full name which might be required for each http request, so it can be read from DB once and then stored in session.
Example of storing class instances in session : http://www.talkphp.com/advanced-php-programming/3407-storing-class-instance-into-session.html
It's nicely explained here :
How long does an instance variable persist? In Rails? In Java? In PHP?

Reading and writing global variables across scripts in PHP

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

Multiple PHP Sessions

I am to build a PHP application for a website that already has another PHP application running on the same domain/server.
My app will of course be using sessions, and I don't want my sessions to interfere with the existing app.
For example if I want to use $_SESSION['username'], maybe the other app also uses $_SESSION['username'], which could be a problem.
I'm not looking for an extra layer of security, I trust the application I'm sharing the host with. I just want to avoid bugs.
One way would be to do something like $_SESSION['MY_APP_NAME']['username'], but I want to know if there is an easier way.
I see on the PHP documentation that there is a function called 'session_module_name'. The name sounds good, but the docs don't really explain what it is for.
Any advice?
There is an easier way: session_name.
Prior to calling session_start(); call session_name("something"); (where you change something to whatever you want it to be called).
Another thing that may help you in keeping apps separate is move the session storage to another place either setting session.save_path in php.ini to a folder of your choice or calling session_save_path() before session_start().

Categories