PHP $_SESSION not available until the page is reloaded. Why? - php

I'm creating a graph that does some database queries then builds the graph using GD functions then also puts the info from the database into an array that is stored in $_SESSION['my_data']. This graph is displayed on the web page using img tags.
<img src="my_graph.php?time=$time">
<?
print_r($_SESSION['my_data']);
?>
The problem is when I print_r() the array from the session variable it doesn't print the current graphs data; it prints the data that was in the graph last time the page was loaded. It's acting like a cookie.
I have tried putting session_write_close() immediately after I store the array in the session because I thought $_SESSION might have been locked until my_graph.php finished loading the image. That did not work.
I also tried putting sleep(10) before I print the array and that did not work.
Why this would happen?

I suppose, when your web server executes PHP code, which draws our page, it already has $_SESSION array initialized. And this array is not updated in current script runtime. When browser finds image tag, it makes another request to web server, which executes image generation script, which updates $_SESSION array in another runtime.
You may:
either make all calculations in your web page generation code
or reload page after image generation script completes calculations and sets all necessary data in $_SESSION array

If you are setting $_SESSION['my_data'] in mygraph.php, you will never see your $_SESSIONchange until your browser requests mygraph.php. This will never occur until the output is flushed to the browser (which will be AFTER you've already print_r() the $_SESSION).
You may be able to try flush() and hope the browser requests the image before you are done executing, I've never tried that (not sure if it will work). Though, sometimes you have to pad output with whitespace until it is about 2k (if I'm not mistaken). I wouldn't recommend this, though.
Another solution would be to request the page you have your code in above in the src. So if your code above is in test.php you could put <img src="test.php?img=true&time=$time">. Then if you get $_GET['img'], display an image, otherwise execute some code. Does that make sense?

Sequence of events:
Browser requests the main web page.
PHP runs the main page and sends the contents to the browser.
Browser receives the page.
Browser looks at the page and sends requests to load the graphics, etc.
PHP runs graph.php and sends the graphic to the browser.
Browser inserts the graphic into the page.
The important thing to note is that the whole of point 2 occurs before any of point 5 happens. This means that anything that graph.php does with $_SESSION will not be visible to the code in the main page, leading to the effect you're seeing.
This is the nature of a web page: the graphic files are separate from the main PHP program.
You cannot get around this using a separate graphic file the way you're doing it.
There is one way I can think of achieving it, but it would be a complete rewrite (it's up to you to decide whether it's worth it!)
It is possible to create a graph using Javascript. If you generate the javascript code to do this in the main page, you could then set $_SESSION during the graph generation code, and it would be available later in the program.
If you do decide to do this, you should look into the gRaphael library to help you out.
Hope that helps.

Related

how is already loaded php script processed by server if there is another request from the same page

I real beginner and try to understand how things work more then to develop stuff, and now i can't move forward till someone gives me an accurate answer about a little detail of following issue.
Let's assume there's a page with php code http://example.com/blablabla and link on it like http://example.com/blablabla?file=number_1 which's used to modify some parts of this page
What i really don't know is what happens with the already loaded script from http://example.com/blablabla when there's a request from this page -http://example.com/blablabla?file=number_1
The questions actually are:
Is code from the already loaded page processed every time when requesting ?file=number_1?
For me it seems very strange, 'cause if with the first http://example.com/blablabla via php i selected for example a huge size of data from database and only want to modify small part of page with ?file=number_1 and why do i need server to process request to the database one more time.
My experience says me that server do process again already loaded code,
BUT according to this i have a very SLIGHT ASSUMPTION, that i'm not really sure about this, but it seems very logical:
The real trick is that the code in the first page has one VARIABLE and its value is changed
by the second request, so i assume that server see this change and modifies only that part of the code with this VARIABLE - for example the code in http://example.com/blablabla looks like this
<?
/* some code above */
if (empty($_GET['file'])) {
/* do smth */
} else {
/* do smth else */
}
/* some code below */
?>
with the request http://example.com/blablabla?file=number_1 the server processes only part of the original code only including changed $_GET['file'] variable.
Is it totally my imagination or it somehow make a point?
Would someone please explain it to me. Much appreciated.
HTML is a static language. There is php and other similar languages that allows you to have dynamic pages but because it still has to send everything over as html you still have to get a new page.
The ?file=number_1 just gives a get request to the page giving it more information but the page itself had to still be rerun in order to change the information and send the new static html page back.
The database query can be cached with more advanced programming in PHP or other similar languages so that the server doesnt have to requery the database but the page itself still had to be completely rerun
There are more advanced methods that allows client side manipulation of the data but from your example I believe the page is being rerun with a get request on the server side and a new page is being sent back.
i believe this is what your asking about.
Yeah, thanks you guys both. It certainly clarified the issue that every script (clean html or generated by php) runs every time with each request, and only external types of data like image files and, even as it follows from the previous answer, mysql results can be cached and be used via php to output necessary data.
The main point was that I mistakenly hoped that if the page is loaded and consequently cached in computer memory, the appended QUERY STRING to this URL will send, of course, new get request, but retrieved respond will affect this page partly without rerunning it completely.
Now i have to reconsider my building strategy – load as much data as it’s required from each requested URL.
If you are looking for a way to edit the page dynamically, use JavaScript.
If you need to run code server side, invisibly to the client, use PHP.
If you need to load content dynamically, use AJAX, an extension of JavaScript.
I hope that helps.

How Ajax enables a Javascript string to be passed to php

I've been learning Ajax and now I'm wondering how it allows a string from Javascript to be passed to php.
It was said before that the problem with passing Javascript to PHP is that the PHP code gets run first, and then the Javascript gets run. So when Javascript generates a string it's already too late.
Does this mean that Ajax allows PHP code to be run after Javascript?
I think this is what they're getting at:
Before Ajax -- specifically, before XMLHttpRequest came along -- a single web page was served as a single page load. If it was a PHP-generated page incorporating Javascript, the browser would request the page, PHP would generate the page (including Javascript code, includes, fragments of script on the page, etc.), would send the page to the browser, and the browser would display it. So, the PHP happened up-front. Until the next page load -- when the entire page was refreshed from scratch -- PHP wasn't involved again.
After the advent of XMLHttpRequest, which helped put the "X" in "AJAX", as it was back then, you had another option. Once the page was loaded, your Javascript could make requests "behind the scenes" of the page, to request more information from the server, without reloading the page. In effect, the loaded page could cause more PHP to be run on the server, and display the results.
So, if you're considering a single page load from a PHP-based website, that is (sort of) what Ajax means; without it, you get a single PHP page-build that's delivered and then your Javascript has to run on that result alone. With Ajax, you can make further requests to your server and throw the results out onto the existing page without a full page load.
The php interpreter sitting on the server is basically interprets whatever php script into (usually) HTML page.
That's why you can never "pass" javascript variable into php as to the interpreter, your javascript is just yet another string, without any special meaning. Your javascript is run by your browser and doesn't even aware that it was being produced by PHP.
I believe that's what it means by "too late".
You should know, that Javascript is always (except Node.js) Client-Side.
PHP is a Server-Side language.
You can't pass Javascript variables to PHP - at least not at the Pageload.
What you can do is doing a AJAX-Request after the Page is laoded to send something to PHP.
With the Response of that call you can replace some other things on the current requested Page.
No it does not mean that "Ajax allows PHP code to be run after Javascript". AJAX is a new request to the server and it allows you to manipulate with the server's response. You can observe this by coping the url to which AJAX request is being made and pasting it into the browser.
So basically when you open a web site with the browser, you send a request and any AJAX call is also a request, but done in a background, so you cannot see it directly. You can use for example firebug or other developer's tool to see what happens behind the scenes. It has nothing to do with the scripts executions orders.

How can I prevent content from unauthorized views (php/js)

How can I prevent (unauthorized) people from reading a message on a website (e.g. by looking in the browser cache for the text/images)?**
It's a PUBLIC (!) site (means: no logins here!)
But:
the (secret) message is only shown for a certain time.
the message might be shown only if a passwort is given.
Problems:
In Opera for example page(=page contents/text) could be indexed by the browser and searched.
One idea was to create an image with the message ... but: Also images - even when a header "no cache" is send could be retrieved from FireFox's cache.
Also: Recreating the message from single characters as image does not work (at least I think so at the moment). I tried this method, but it makes output quite slow (writing this: I notice that I do not need to create the images at runtime, but could create images (of single letters) in advance and display/refer to them not by real, but pseudo random names in the HTML )
I also had the idea to output a encoded message (ROT13) (in HTML) but use JS .onload to decode the message immediately. Problem: If this code is in the HTML it could be recovered from the cache later on. At least if someone searches through the (Opera) cache the person would probably not think of entering search terms encoded.
Programming language is PHP.
You can't. What if someone takes a screenshot of this?
You could add the secret code to the page with javascript, after the page is loaded. You'd want to retrieve the secret code via AJAX, then write it to the page - that way, the code isn't cached in the HTML part of the source, and it isn't sitting in the javascript within the page's source code.
Content piped in with AJAX is pretty ephemeral, it won't be cached or otherwise recorded.
Since I don't know anything about your HTML or what (if any) javascript framework you might be using, I can't give you a code sample, but you should be able to work with the concept.
Realistically if it is sent to the client and displayed on screen then you can not prevent the message from being saved or stored on the client machine. Whatever you do to prevent that save could still be bypassed by a simple screenshot.
If you are not concerned about the person the message is targeted at saving said message then I think your best course of action would be to use Flash with Flash doing a call to the server to retrieve the message and display it. Another option may be to use javascript to perform some form of call (AJAX) to the server which then sends back the message and you alter the DOM to display the message. I don't think that would be cached but unless you use SSL it could be stored by intermediate proxies.

AJAX vs PHP Directly into JS

I have a little bit of a conundrum. Basically I'm developing a WYSIWYG Editor plugin for jQuery specifically for my web application. One of the features will be inserting an inline image tooltip based on the images a user has uploaded. For example:
Hello there my name is [i="profile_pic.png"]A. Username[/i]
The part that I'm having an issue with is, when defining which images are available to a user, whether I should insert the PHP array directly into the Javascript like so:
var available_images = "<?=json_encode($User->Profile->images)?>";
or to go for an Ajax GET that returns an encoded array of the image sources? I think the inline php makes more sense since it removes the need for an unnecessary ajax call but I didn't think that inserting inline php into javascript is terribly good form?
Any suggestions?
There's nothing wrong with inserting data collected by PHP into JS, how else would JS get the data? The only reason you should consider the AJAX call would be, if users could upload new images while they are editing. This would mean the information needs to be updated, which would make the AJAX call more appealing than the static JSON on page load.
Unless the array changes in any way over the life time of the page, then I'd spit out the array exactly as you suggest in your code snippet. There isn't any real benefit to having an extra ajax call because the size of the array I'm guessing won't be so huge as to impact the initial page load time.
If you look around the Stack Overflow pages and do view-source, they do this sort of thing all the time.
If the amount of data is huge and maybe adds a seven or more seconds to the page load time then I'd consider an ajax call. At least the page is rendered and the user has something to look at, meanwhile you can have a throbber image with a status message saying loading or whatever.
I'd also say that I see a lot of unnecessary ajax goings on just for the sake of it. It's like premature optimisation, people adding complexity to solve a problem they don't have. Start off simple as you're doing, if you're having response time issues down the road with the said page, then consider what benefits ajax will bring to the table.
Do you always get the array of images, or only sometimes (e.g. in response to a user's action)? If the former, I'd say do it inline. Otherwise do it as AJAX. i.e. only do it by AJAX if it'll reduce your traffic etc. But if you have to always do it, I don't see any advantage. I don't see any problem with mixing inline php and javascript, other than it means you have to do your javascript inline too instead of in external .js files that can be cached (or at least the part where you populate your array).

Send a Variable to an IFrame's Parent in PHP?

How can I transfer an array from an IFrame running a php script, to the parent PHP of the IFrame?
I have an Array of strings in PHP that need to be transferred to the main window so that when the iframe changes pages, the array is still stored.
I could use a cookie for this, though I'm not sure that would be the best idea.
Thanks.
you can't do that in php. iframe is like a new browser window, so they are separate requests. separate requests can not transfer data between each other in a server side language.
if you give some detail as to what you're trying to accomplish, there may be another way around the issue that someone can suggest.
Like Tim Hoolihan said, PHP is a server side language that is only responsible for generating the HTML before it is sent to the browser. Meaning once the page shows up in your browser window, PHP has done it's part.
However, with that said, if you control both the "parent" page and the page being iframed, you can json_encode the array in the page being iframed and set it to Javascript variable, then on load pass it to a Javascript function on the parent page (assuming not violating any browser/domain sandbox constraints). At that point you can do whatever you want with it.
Take a look at jQuery for your core Javascript/Ajax needs.
if you control the iframe, you can save the array in a session variable and make the parent do an asynchronous call to retrieve the array from session.
however Jordan S. Jones solution with only javascript works as well

Categories