PHP Server-local Variable? - php

Short and sweet, I need to have a variable NOT be unset after a page has finished loading. I've used a file to store the value, and I've used a MySQL table with 1 record, and updated/read from that, but I want something cleaner and simpler. Any ideas?
Some people misunderstood the question, so here's an example. At the top of my page, I would have some code such as:
$_PERMANENT['hits']+=1;
print 'Hits: '.$_PERMANENT['hits'];
Note that this works across multiple clients, so it's not $_SESSION.

I finally found the answer: apc_store et al

Use the $_SESSION, that's exactly what it's for. This either requires the user's browser has cookies on, or that you format links to maintain the session id.
At the start of your pages, use session_start() - only do this once, and it must be before content is written as it needs access to the header area.
session_register() is deprecated, so just do a $_SESSION['key'] = $value; and the next page load within that session will have access to the value via: $value = $_SESSION['key'];

Related

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.

session id value changes

I am writing a PHP website. I have a $_SESSION['id'] that hold the username id of a user, which I will use this value later on in my scripting. However, I notice that the ID changes as I surf the site.
Is id reserved in any way? Or, should I change id to something else?
This problem is happening whenever I click on a button several times. I am 100% sure that I'm not altering $_SESSION['id'] beyond the initial login.
Could someone please help me understand what is happening, and how it can be fixed.
I am going to assume you already use session_start, if not see the other comments :P
If you have register globals on, you may be seeing behavior like that if you use the variable $id in your code. As a test, try:
<?php
session_start();
$_SESSION['testing'] = 'Foo';
$testing = 'bar';
die($_SESSION['testing']);
?>
Reload the page a couple times. If bar prints out rather than Foo, that may be your problem. You'll probably want to make the session variable name something that is less likely to get used elsewhere, or (more correct) turn off register globals.
make sure you start the session - look at session_start();
Make sure you are calling session_start() at the very top of the page(aka before ANYTHING else).
This may be causing the screw up.
A very quick rundown as to why you need to do this:
Most of the time a session id(different from $_SESSION['id'], don't worry) is stored via cookie. The cookie values are sent via the response headers, which needs to be the first thing that is sent back to the client. So if you are outputting ANYTHING before calling session_start(), you are actually forcing php to send the response headers. This will cause the response headers to NOT contain the cookie session value, thus not being able to properly use the session.

can session variables survive from php -> html -> php?

the question is really simple, but i searched it many different ways and the results were not related to my question.
so if i have a session variable in a php file if i open an html page after that and then a php file again, will i be able to retrieve the data ? or do they all have to be adjacent?
I tried php->html->php but i couldn't get the variables on the other side. maybe Im doing something wrong.
Thanks in advance
Not 100% sure what you mean, but if by "open" you mean in the browser, the calls do not need to be adjacent. You just need to do a session_start() in every PHP script in which you want to use session data.
Adjacency is not something that is really relevant for this question.
in PHP way of things, sessions are essentially files that contain serialized data on the server. The browser that called a script containing session_start() call receives a special token that identifies the session on the server, and it is normally (though not necessarily) stored as a cookie.
This effectively means that any php script that uses session_start() and receives a session id (via cookie or otherwise) will read and could use session data, unless it was removed from the server file system between the calls, or the session has expired (frankly, I'm not sure whether PHP removes the expired sessions on the server side).
Accessing anything outside of this model with the browser (html page, or even other sites) will not affect it in any way, unless these actions change or remove session id.
yes...session variable can survive php->html->php.
But on every php page ...very first line should be session_start()
This easy way (I guess): Set a cookie storing the session ID on the first php page. This way, every other php page can access the session ID and use it to restore the stored data, not matter how many (even foreign) pages were in between.

Return a result in the original page

When the user submit his data, I take him to a different page where plenty of calculations are made, then I redirect him to the original page with a simple :
<?php header("Location:http://mysite.com/index.php");
The problem is I need all the variables and results to be show in this page, but they are obviously stored in the other one, so I need your help please :) !
Thank you for reading this !
PHP sessions.
session_start(); as the first thing on both (and all of your pages where you want to access this data).
set the variables you want to access as such:
$_SESSION["somekey"] = "somevalue";
then you can recall them on any of the other pages.
this functionality is reliant on session cookies, of course.
You can accomplish this through the use of sessions.
Don't forget you could use a database.
Sessions would be your best choice. See the other answer for the link to the php manual.
You could append them to the URI, but depending on field length and field counts that could be very messy (or not even possible, if too long).
If neither of these are options (too long, can't use cookies), you could can pass the session key along in the GET param. You can then use sessions normally.

how do php share data without access a DB

I have two pages and I want to pass data to each other.
How can I do this without accessing a DB?
Sessions? Cookies? someother magical way?
If you know how, can you please post sample code?
Thanks
Session variables is one way:
$_SESSION["variable"] = "value";
This variable can then be read/modified by another page.
Also note, that you need to start the session by calling start_session(); at the beginning of your script.
And Cookies are another way... You can also try writing in and out of a file instead of a DB
How does a user get between these two pages? I assume a Form based solution is out of the question...
Amongst the possibilities, here are some that I think about :
You could $_SESSION (see Session Handling) -- if both pages are accessed by the same user, without too much time between the two accesses, so the session doesn't expire.
You could store your data to a file ; that'll work fine if :
The amount of data is big
You want it to persist for a long time
But you'll have to do some cleaning-up by yourself
Another idea would be some external daemon, like memcached
But, as it's a caching engine, it's not necessarily good for storing data : the data that is cache can be removed from the cache even if it has not expired yet (i.e. if there is no place left in cache, memcached will remove some least used data)
Of course, if the data is small and you don't mind it going back and forth through the network, and both pages are accessed by the same user using the same browser, you could use cookies
Only a couple of possibilities, though ; my preferences would probably be :
$_SESSION
or files
Depending on your situation.

Categories