Do variables transfer over from one seperate script to another via PHP? - php

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.

Related

PHP session variable not persisting between pages

I have a variable that I want to persist between pages. I've tried setting it using POST, and when that didn't work, I used SESSION. Yet in either case, the variable is lost when I go to the new page.
Here is the code when the variable is set:
$_SESSION['filename'] = $boardName;
$debug->alert_code_info($_SESSION['filename']);
And just as a debugging test, I used this line to check if it persisted:
$debug->alert_code_info($_SESSION['filename']);
You can substitute POST for SESSION in the above lines - I've tried that as well, and it doesn't work either.
Why are these variables not persisting from page to page?
Make sure you have session_start(); on both the pages on the top.
Yes, $_POST would work. In that case, please go through this article. Post data in PHP
$_POST is an array that stores data received from an HTTP POST request to a particular page. It is not like $_SESSION variable which persists across the pages.
PHP has "page scope". What that means, is that when a script is run, all variables are created, and when the script completes, all variables are disposed of. It has no persistence. Without output buffering (a whole subject unto itself) for all intents and purposes, as soon as the page is accessed and output generated, the script will be complete. This model is very close to the way HTTP is designed.
As noted, you need some other form of persistence to carry variables between pages. Sessions, databases & datastores, cache, cookies and shared memory are all routinely used in php applications.
Which one is appropriate requires some further understanding of why you need the persistence.
You can also pass variables from one page/script to another using the standard web mechanics of url parameters (automatically placed in the $_GET superglobal), POST variables (automatically placed in the $_POST superglobal) or cookies (automatically placed in the $_COOKIE superglobal).
Some of these are connected, in that php sessions by default utilize a cookie used by the server to identify a returning client.
In regards to your specific question about POST variables, so long as a form is POSTed targetting your script, the POST variables will be available in the $_POST. A much used technique is to either utilize hidden form fields or to set the value of form fields when there is a multi form process, or in the case of error handling.
To be clear, again PHP has no persistence, which is different from some other languages which run under application servers (such as Java with a J2EE server). In J2EE Objects can be created and will live inside the Application server across any number of page requests. PHP in some implementations has some minor persistence capabilities as in the case of database pooling, but nothing intrinsic to the language.
Once you are clear about page scope, and that essentially nothing lives beyond one HTTP request/response, your persistence options should be clearer.

passing variable between pages

Is it good way to pass variable between pages using $_GET method with url:
<a href="input_obj.php?id='$id'&method=plain
and take it in file input_obj.php with such code:
$id = $_GET['id'];
$method = $_GET['method'];
OR
using session - has someone idea how?
It depends on your needs, really, If you are passing search arguments between pages, for example, and the variables should be both persistent and be available to the end user (via bookmarking, for example), then pass them in the URL (but don't usually use quotes like you have around $id in "input_obj.php?id='$id'&method=plain)
If you are truly passing internal variables between scripts, this is better done via $_SESSION variables. Remember that end users can easily modify variables passed through URLs. Unless they are intended for use by the end user, that may be a real problem. By using $_SESSION, you insulate your script's variables from tampering by the end user when it's necessary to insulate them. (unless, of course, the variables are produced by other user input via GET/POST/COOKIE)
//page1.php
session_start();
$_SESSION['id'] = $id;
//page2.php
session_start();
echo $_SESSION['id'];
GET variables are a much better way to go. When you start dropping variables into the session, it can have side effects like copy/pasting a URL from browser to browser or trying to bookmark can bring up different pages (which consequently is a nightmare for SEO). Also, it can have complications if you ever start clustering your servers b/c you'll need to deal with session failover.
IMHO, the best solution is to use mod_rewrite to implement path-based variables...you get pretty URLs with all the benefits of GET vars.
GET is a reasonable way to pass variables to another page.
$_SESSION and cookies is another way, but it won't allow a user to bookmark a page.
POST is another way, but it requires form submission which would either need user intervention or javascript.
It depends on the what the data is for, its type and its length. Usually, passing variables in the query string is fine.
Be aware that when accepting mutable parameters, you need to verify they are what you expect them to be. For example, I could change ?id=5 to ?id=hello and possibly break your application. To remedy this, we could typecast the ID to an integer: $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
You could also use cookies. These are sent like this:
setcookie(name, value, expire, path, domain);
you can ommit the path and domain variables. This has to be declared before the tag. The name is just the name with which you will get it. The value is what wil be returned and expire is the time at which the cookie expires (it is writen in the form of time() + $timeTillExpire where timetillexpire is a variable or constant value you set). This of course has the limitation of if the person has cookies of it will not work.
You get a cookie with:
$_COOKIE["name"];
and returns value
the way you did works fine.
If you're just using variables in your PHP script, you don't really need to 'pass' them. You can create a variable globally and access it from another page.

persistent data in php question

OK Ive written this neat javascript 'thing' using jquery and ajax. Its all based on the idea that a div has an attribute that lets you write inside the div. (contenteditable=true). I thought it would be cool to make a chatroom type thing out of it, and holy cow its doing some cool stuff(*), but I have an issue.
Using ajax I post to a php page that takes the posted data (x,y, text, id) and stuffs it into a JSON-like object. Without writing to a database (overkill I think), how can I make this data persist? See the problem? : The variables in a php page are essentially vapor after the page has ran, so my javascript ajax call to retrieveNewJSON() would find nothing.
*using jquery effects and setting colors I have variably placed text that scrolls and evaporates, matrix style, for example. Also, a cursor is placed in the div where the user clicks.
You have to store the data somewhere. If you don't want to use a full blown database you can store them in flat files (ie: txt) and use PHP's file functions to handle the files.
Of course this is not very scalable, and I'd strongly recommend using a database if you are going to be using this a lot.
You could use cookies (client-side) or session variables (server-side), or you could write to a file for longer-term storage.
You could use a the $_SESSION variable to persist data.
// Call at start of PHP script
session_start()
//....
// Store object
$_SESSION['obj'] = json_encode(obj);
in your pull script:
// Call at start of PHP script
session_start()
// Retrieve object
echo $_SESSION['obj'];
Note that when using sessions you have to make sure that you call session_start() at the top of every php script that uses the session.
I would not recommend trying to store this in a file unless you are supporting a very low number of users and have taken proper data sanitation steps to physically write files to the server. If you need this to persist past the length of a session you should be using a database.
It is worth noting that you can't update a users session without some other form of centralized storage. Unless you have some sort of long-polling / comet type setup you will have to have some sort of central storage place. Something I would take a look at would be memcache.
If you want to avoid using a database engine (which would have a lot of overhead for a multiple-read, multiple-write app like a chat room anyway), you might look at a simple object store like memcache, couch, or mongo. Files are also a valid option, provided you store them outside of the Web root with proper permissions. Bottom line is, you'll have to use some sort of storage engine on the back end in order to make the data shareable across multiple user sessions.
If this is simply a tech demo or a proof of concept, I wouldn't worry too much about overhead right away.

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

What is the "?" symbol in URL used for in php?

I am new to PHP. In the path of learning PHP language, I notice that, some website would this kind of URL:
www.website.com/profile.php?user=roa3&...
My questions:
What is the "?" symbol used for?
If I were develop a php website, must I use it in my URL? For example, after a user(roa3) successful logged in, I will redirect to "www.website.com/profile.php?user=roa3" instead of "www.website.com/profile.php"
What are the advantages and disadvantages of using it?
Good questions, briefly,
"?" stands for the start of querying
string which contains the data to be
passed to the server. in this case
you are passing user=roa3 to
profile.php page. You can get the
data by using $_GET['user'] within
profile.php. querystring is one of the methods to send data to the server from client agent. The other one places the data in HTTP body and POST to the server, you don't see the HTTP POST data directly from browser.
querystring can be edited by user
and it is visible to the public. If
www.website.com/profile.php?user=roa3
is intended to be public then it is
fine, otherwise you may want to use
session to get current user's
context.
it is a flexible way to pass data to
the server, but it is visible and
editable to the users, for some
sensitive data, at least produce
some kind of hash before attaching
it to the querystring, this prevents
users to edit it or understanding
the meaning of it. However this
doesn't prevent a decent hacker to
do something wrong about your
website. Different browsers support different max length of URL, the lengthy URL is made up by those querystring parameters. If you want to send large amount of data, place the data in the HTTP body and POST to the server.
Most of the answers I've seen so far have been in terms of PHP, when in reality this isn't language specific. The answers given so far have been from the view of PHP and the methods you would use to access the information differ from one language to the next, but the format in which the data is in the URL (known as the Query String) will remain the same (Ex: page.ext?key1=value&key2=value&...).
I don't know your technical background or knowledge, so please forgive me...
There are two different methods for a web page to provide data back to the web server. These are known as the POST or GET methods. There also also a bunch of others, but none of those should be used in any sort of web design when dealing with a normal user. The POST method is sent invisibly to the server and is meant for 'uploading' data, while the GET method is visible to the user as the Query String in the URL and is only meant to literally 'get' information.
Not all sites follow this rule of thumb, but there can be reasons as to why. For example, a site could use POST exclusively to get around caching by proxy servers or your browser, or because they use double byte languages and can cause issues when trying to perform a GET because of the encoding conversion.
Some resources about the two methods and when to use them...
http://www.cs.tut.fi/~jkorpela/forms/methods.html
http://weblogs.asp.net/mschwarz/archive/2006/12/04/post-vs-get.aspx
http://en.wikipedia.org/wiki/Query_string
Now from a strictly PHP position, there are now 3 different arrays you can use to get the information a webpage has sent back to the server. You have to your disposal...
$_POST['keyname'], to grab only the information from a POST method
$_GET['keyname'], to grab only the information from a GET method
$_REQUEST['keyname'], to allow you to grab the POST, GET, and any COOKIE information that might have been submitted. Sort of a catchall, especially in cases where you don't know which method a page might be using to submit data.
Don't get sloppy by going directly with the $_REQUEST method. Unless you have a case like I mentioned above for the $_REQUEST variable, then don't use it. You want to try and use a 'deny all, and only allow x,y,z' approach when it comes to security. Only look for the data that you know your own site will be sending, only look for the combinations that you'll be expecting, and cleanse all of the information before you use it. For example..
Never do an eval() on anything passed via the above methods. I've never seen this done, but it doesn't mean people haven't tried or do.
Never use the information directly with databases without cleaning them (research into SQL injection attacks if you're not familiar with them)
This is by far not the end-all, be-all to PHP security, but we're not here for that. If you want to know more along line, well then thats another question for SO.
Hope this helps and feel free to ask any questions.
1) If a user logs in to your site, you would use Sessions to store there username instead of passing it in the url e.g profile.php?username=roa3
2) Using a ? symbol in the urls is generally considered bad for Search Engine Optimization. Also, the urls look a bit ugly. Using mod_rewrite you can do the same thing as profile.php?user=roa3 or products.php?id=123&category=toys with: site.com/profile/roa3 or products/toys/123.
Using the CodeIgniter framework will give you friendly URLs by default and eliminate the need for ?s in your urls. See this page for an example.
3) The ? symbol is also used inside the code of a php page. For example, an if else block such as:
if ($x==1)
$y=2;
else
$y=3;
can also be written as:
$y=($x==1) ? 2 : 3;
The "?" signifies that some GET variables are to follow. You example uses a variable called "user", and assigns a variable called "roa3".
Advantages of using GET variables:
they can be bookmarked as part of the URL
Disadvantages
they are public.. Anyone can intercept and see this information. These url requests are even cached by servers along the journey. So anyone can impersonate your roa3 user just by typing that information in by hand... also they could change the roa3 to a different user and impersonate them..
You can also use a "&" symbol to separate many variables e.g.:
www.website.com/profile.php?user=roa3&fav_colour=blue
Other options:
POST variables
You can send your variables via the POST variables. These variables are passed in the header of the request, not the url of the request. they are not immediately obvious, and are not cached by servers along teh journey, but they can still be read. unless you have a HTTPS conection established.
variables in a form can be sent by POST or GET methods.. You specify this in the "method" of the form. <form action="index.php" method='post'/>
SESSION variables
Session variables are stored on the server. A session id is passed to the user, and this session id is passed back to the server every time the user makes another request. This session id can then be used to get the session variables that were stored. So you could store a user's favorite colour, their name, and ip address etc.. but you could store it on teh server rather than the user's home PC.
Session ids can be impersonated, so it is good to check against the user's IP, and or to wrap them in a secure conection. eg https.
session variables can't be changed by someone who intercepted the request.
COOKIE variable:
Similar to the session variables, except that they are stored on the user's PC, not the server. They are stored against a domain, and when they go to that domain, they resubmit the variables in the header of the request to the server.. this means that the user could change and hack the variables, or someone else could.
To access these variables in php you can use:
$x = $_GET['user'] for a get variable
$x = $_POST['user]
$x = $_REQUEST['user'] - the combination of get, post and cookie variables
$x = $_COOKIE['user'] - cookie variables
$x = $_SESSION['user'] to access the session variables
(user could be replaced with the name of the variable you are using)
Simple enough stuff, but important to know what they actually do.
? is part of the HTTP standard and not part of PHP. Thought I should point that out so when you move on to another language and see it again you are not confused thinking there is PHP involved.
Otherwise there are some excellent answers above.
From the server's point of view, the ? is just another character. PHP provides easy methods for parts of the URL after the ? character, e.g. for "/profile.php?user=roa3", PHP will set $_GET['user'] = 'roa3'.
The reason ? is useful in URLs is that browsers can construct dynamic URLs using forms -- in the case above, I would expect that the URL was built by an HTTP form with a field "user", into which the human user has typed "roa3".
"?" is used to separate the URL and the parameters. For e.g, it is like http://www.url.com/resourcepath?a=b&c=d. In this case a=b is like request_parameter=request_value.
Ya, Its not advisable to use much of the parameters because the total url size is limited and it is like GET request, where all the parameters are shown on the url and the user can modify it. In your example, say what if a user modify the url to "user=techmaddy'.
Advantage is it can be used for the GET kind of requests. Disadvantage is low security, limitation in size.

Categories