PHP session: two values are ALWAYS sent - php

I'm pretty new to PHP but trying to find my way which has worked quite well up till now.
Problem is the following: I have a website with 2 links. Both should redirect to the same second website but depending on the link clicked, some values should change. I was trying to use a PHP session for this.
Here is the code up to now:
Link 1:
<a href="<? echo $link ?>" class="helsinki" onclick="<? $_SESSION['clicked']= "helsinki"; ?>"^^Helsinki^^</a>
Link 2:
^^Seattle^^
Now if I try to read which link was clicked on the next side like this:
<? if(isset($_SESSION['clicked']))
echo "clicked ". $_SESSION['clicked'];
?>
I always see "Seattle", Helsinki never appears although (I thought) I input Seattle if the Seattle link is clicked. Apparently it's not like that... Can anyone help me here?

This is because PHP code is server side, and thus executed at the time of the page request. So $_SESSION['clicked'] is set to helsinki then reset to seattle at the time your first page loads. You may want to use $_GET variables instead of $_SESSION variables.

Wait wait wait a second: PHP is "server-side", javascript is "client-side". That means you will ALWAYS execute PHP before javascript.
What you are trying to achieve can be simply done with a GET variable:
^^Seattle^^
^^Helsinki^^
And than in the second site you can get the value of our parameter:
$city = $_GET['city'];

Not sure if this is useful, but you could create a "redirector". It takes the user to a server side page that will redirect them to the final page and at the same time change the session.
The page:
...
...
The code for redirector.php:
<?php
session_start();
// determine where to redirect user (could be done with database or array of options)
switch ($_GET['link']) {
case 'helsinki':
header('Location: /link/to/helsinki');
break;
case 'seattle':
header('Location: /link/to/seattle');
break;
default:
return;
}
$_SESSION['clicked'] = $_GET['link'];

You're mixing up Javascript and PHP.
PHP is server side, that means that all PHP code is parsed and executed on the server side, and then is sent to the client.
So if you write
line #1: ^^Helsinki^^
and then
line #2: ^^Seattle^^
the value of $_SESSION['clicked'] is always first "Helsinki" (line #1), but then immediately overwritten by "Seattle" (on line #2).
In order to achieve what you want the script to achieve, is, for example, as follows:
^^Helsinki^^
^^Seattle^^
and then catch the sent variables from the PHP variable $_GET:
if (isset($_GET['location'])) {
if ($_GET['location'] == "helsinki") {
// Whatever
}
elseif ($_GET['location'] == "seattle") {
// You want
}
}

"^^Helsinki^^
"^^Seattle^^
and use $_GET['location'] at the other page to check weather it is helsinki or seattle.
$link should be the same for both links.
Also you can't mix PHP (server-side) with Javascript (client-side). Look it up for why that is.

You cannot write PHP code in the onclick event. If you want to do it like that, you should use Javascript/AJAX. Even if you do it like that, you won't still get the result as you desire, since AJAX request will delay some seconds.
I think the right way to do this kind of thing is like below:
Helsinki"
and this is the change_city.php:
<?php
$_SESSION["clicked"] = $_GET["city"];
?>
if you want to still use the $link, then you just put this above code top of your PHP file.

Related

setInterval doesn't seem to re-execute php script

what i'm trying to do is get a variable to update every 5 seconds doing this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>",5000);
but what happens is the inner html is set but doesn't update every 5 seconds like it should.
my guess is that the php only executes once, but i have no idea if that's the case or not.
and i'm aware i should make a function to do the stuff inside setInterval... i'll clean up the code once i figure out how to make it work.
thanks in advance.
ok... ajax was 'the best' answer since no more than 2 people would be logged in at a time here so server requests isn't such a big deal.
here's how i got it to work:
function lCount(){
$.get("../includes/shoutcaststuff.php",{Count: "TRUE"}, function(data){
document.getElementById('listeners').innerHTML = data;
});
}
setInterval(lCount,5000);
and added this to the end of the php:
if(isset($_GET["Count"])){
echo $dnas_data['CURRENTLISTENERS'];
}
now it works fine.
thanks for the suggestions guys :)
<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>
This code only executes once when the page is built. For the rest of the times this javascript is called whatever is first echoed will be the value.
Instead of using a static value here, you are going to need to use an ajax request (or a websocket if you want to use html5). The request will then hit your server once every 5 seconds. Keep in mind that this can cause undue load on your server.
Ratchet is a commonly used PHP WebSocket implementation that allows for data to be sent to the client using push technology. This is probably more preferable than using your polling approach.
PHP code is run on the server generating the HTML/JS. Use ajax if you need to run php code once the page has loaded.
Take a look at this for example;
Using this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php echo "1";?>",5000);
Will output this to the browser:
setInterval(document.getElementById("listeners").innerHTML =
"1",5000);

does a PHP page with includes get compiled and sent as one page?

I have a PHP page where the header and footer are PHP includes.
I want to know if there is any possibility of the includes loading asynchronously - or does PHP gather all the files required, compile them and send them as one file?
The reason I ask is that I've seen an interesting PHP app that seemed to keep the connection open and do things in sequence before closing the connection - I wondered if that's what happens with includes.
PHP version is 5.3.6
EDIT:
What I actually want is for the page to load all at once, to prevent my layout mashing as each bit loads. Sorry to any who misunderstood this
PHP does gather and compile them; everything goes to the browser as a single document. If you don't want this, you'll have to do something with XMLHTTPRequest on the frontend
Generally any output will be output as it is generated.
echo 'A';
sleep(1000);
echo 'B';
sleep(1000);
echo 'C';
This slowly outputs "ABC". Includes are included when they are encountered, the same way echo outputs anything at that specific point. It's all in order, never asynchronously.
A web server may buffer all output before sending any of it to the client. In the above example, you'd receive "ABC" all together after 2 seconds of nothing.
If your objective is to receive all the page at once you need to use ob_start() and ob_end_flush(). Do something like:
ob_start();
...
write all your outputs
...
ob_end_flush();
This will force the server to buffer the output until the whole page is prepared.
Good luck!
I use the following architecture when loading a page on my application:
index.php
<script src="path/to/js/lib/jslib.js" type="text/javascript"></script>
window.addEvent('load', function()
{
BuildPg(PgStatus); //PgStatus is a variable I use in a state machine to build different pages
});
<form>
<div id="DivPgTop"></div>
<div id="DivPgMiddle"></div>
<div id="DivPgBottom"></div>
</form>
This is the entire index.php
In my jslib.js I have functions like:
function BuildPg(Pg) {
BuildPgTop(Pg);
BuildPgMiddle(Pg);
BuildPgBottom(Pg);
}
function BuildPgTop(Pg) {
var Content="";
if (Pg == 1) {
Content = function_a(); // function_a builds the top of the page
else if (Pg == 2) {
Content = function_b();
etc...
}
document.getElementById("DivPgTop").innerHTML = Content; //here is where I load the top of the page
}
And I do the same for the other parts of the page Middle and Bottom.
Using this framework, if you changed my BuildPg() function to something like:
function BuildPg(Pg) {
BuildPgTop(Pg);
sleep(foo);
BuildPgMiddle(Pg);
sleep(bar);
BuildPgBottom(Pg);
}
Your user would experience the top of the page loading first, a delay, the middle of the page, another delay, and the bottom.
And if you change the order of the function calls you could even have the bottom of the page load first, then the middle and the top.
I hope this makes sense. Good luck!
PHP sends a single document. What you want to do is achieved with something called AJAX (http://en.wikipedia.org/wiki/Ajax_%28programming%29)
Basically you write some JavaScript code that uses XMLHTTPRequest object to connect to the server and download some extra info.

How to store search result?

I am working on my personal site, where I want to store my customers recent search result limited to that particular session.
I am using PHP platform and Javascripts.
Here is an example of what I am exactly looking at :
It stores your previously searched domain name for that particular session so that user can make decision by comparing those results.
Thanks.
EDIT- Well Thanks for all of your answers and suggestions.
But If you have noticed
above example
It looks like some kind of script loading a new content on the same page without refreshing it and keeping previous search content <div> as it is.
How to achieve this using javascripts or some sort of div layer ????
UPDATE START
This example uses page reload. If you want to do it without page reload, you can but you'll have to use AJAX to load new search results. But then, it's not a PHP question. I suggest looking at jquery library, as it makes it easy. Tutorials: http://docs.jquery.com/Tutorials and e.g. this one ( http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax ).
When loading data via AJAX, the page rendering result (in my example search.php) should return only HTML for results part, not whole HTML page. This is generally a first part of my tutorial (without session).
But I really think that AJAX in here is not really needed. Session is more reliable and allows access to your page from older / mobile browsers where not always JS works correctly.
UPDATE END
Ok then. Let's try the simple tutorial then. Sorry if too simple, but I don't know your exact level.
PHP has mechanism called sessions. In reality they are just bytes stored on server. Server knows which session is for each client by reading session cookie from client browser.
Not every page uses sessions (not every page needs it, and session uses server space, even if only temporarily), session is not enabled by default. To turn on session you use command
<?php session_start(); ?>
In most cases this is either run by PHP framework you use, or put near the top of your site. Session is definitely needed if you want to authenticate user somehow. Or in your case :)
To access session you can use superglobal $_SESSION variable (superglobal means that you can access it anywhere). It's an array, so session element will be e.g. $_SESSION['search'] etc.
As example, let's assume that your page looks like that
<html>
...
<form action="search.php" method="post">
Search: <input type="text" name="searchQuery" />
<input type="submit" value="Search" />
</form>
...
</html>
this very form will send user search to file named search.php. It can be the same file where the form resides - in simplest case when you put both your code and HTML in one file. Beginners often use this schema, although it's not advisable as result is a mess and hard to further change.
In search.php then, you'll use similar code:
<?php
if (!empty($_POST['searchQuery'])) //we have a new search
{
$result = do_search($_POST['searchQuery']);
}
?>
Then, somewhere below you'll display your search result ($result variable). do_search() function is your search mechanism, I guess you have it somewhere. You may have it not 'wrapped' in a function, then I advise to create it like that, it's much more useful.
function do_search($searchQuery)
{
...
return $result;
}
mind it, the above code doesn't use sessions yet. Let's add saving previous search results in session. The code may then look like that:
<?php
session_start(); //Starting session
//let's create session variable used to store results
if (!isset($_SESSION['searches']))
$_SESSION['searches'] = array();
if (!empty($_POST['searchQuery'])) //we have a new search
{
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value, delete previous result from sesion
{
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
$result = do_search($_POST['searchQuery']);
//Let's add new search on the begining of session array to make iterations easier.
$result = array($_POST['searchQuery'] => $result); //convert result to same format as session table
$_SESSION['searches'] = array_merge($result, $_SESSION['searches']);
}
?>
In display you'll now not iterate on $result variable as before, but instead you will do something like
foreach ($_SESSION['searches'] as $query => $result)
{
...//display of single result
}
I haven't tested following code and it's not a full program. Parts to display result and to do actual search are not described but I guess you have them already prepared. Also, this is only one possible approach of countless possibilities. But I hope this helps :)
Possible modification - now I always perform search, even if user already searched on this term. You may want to receive the result from cache without second search. Then the code will look like
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value
{
$result = $_SESSION['searches'][$_POST['searchQuery']];
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
else
{
$result = do_search($_POST['searchQuery']);
}
For more in-depth information about sessions and some other constructs used in my example I suggest PHP manual
http://pl.php.net/manual/en/book.session.php
and various tutorials over the network. Or you can add a comment here :)
Put this code near the beginning of your script(s):
if (!isset($_SESSION['previous_searches']) || !is_array($_SESSION['previous_searches'])) {
$_SESSION['previous_searches'] = array();
}
[edit]
This code snippet checks if if there is already an array with prevous searches and if not it will be created.
[/edit]
Then when the user hits the search page put this code in the receiving script of the search:
$_SESSION['previous_searches'][] = $_GET['what_ever_your_search_value_might_be'];
[edit]
This code snippet adds the current search value to the and of the array with previous search values
[/edit]
Now you have all previous search values in $_SESSION['previous_searches']
If your website is a web application where you never reload the page nor change the page, you can keep it JavaScript in a global store (declare at top level something like var StoredSearch = []; and use it). If not, then use $_SESSION to store this and AJAX to save/load searches from JavaScript to PHP.

PHP work with JS Jquery

How do i make PHP work with JS?
I mean more like, i want to check if the user is logged in or not,
and if he is then it will:
$("#message").fadeIn("slow"); ..
How should i do this?
I have an idea maybe have a file that checks it in php, and then it echo out 1 or 0.
And then a script that checks if its getting 1 then do the message fade in.. But im not as so experienced to script that in JS
You cannot directly pass variables from Javascript to PHP because the PHP run on the server before it's sent to the client. But you can 'pass' variables from PHP to Javascript.
For example:
echo('<script type="text/javascript'> var phpvar = '.$variablefromphp.';</script>');
However, you can manipulate what javascript your browser will print. You can first check if the user is logged in in PHP, and based on that, conditionally print the HTML and Javascript.
For example
if($user->logged_in())
{
echo('<script type="text/javascript">$("#message").fadeIn("slow");</script>');
}
else
{
//php function
generateLoginBox();
}
I only javascript to enhance user experience. You should make your application work even when javascript turned off.
With the javascript enabled, you can add an enhanced experience, such as animated page element, AJAX request, etc.
In case of login state, you should have a way to know it in PHP script. Then in the output, you can have a conditional block that only executed if the login state is true. You can put anything you want here.
Javascript can be working in a static HTML page. You can use this to create a simple test for the code that you wrote, to see if it working as you want. Read the documentation in http://www.jquery.com/, there are many links there to many examples.

javascript-php var post get

That code work:
startSlideshow(<?php echo json_encode(glob("photos-animaux/*.jpg"))?>);
that code dont :
$.post("",{'folder':'animaux'});
startSlideshow(<?php echo json_encode(glob("photos-".$_GET["folder"]."/*.jpg"))?>);
WHY ?, what i am doing wrong ?, help !
why the stupid php fonction just dont make the string right !! ahhhh!
---new infos----
that line work :
startSlideshow(<?php echo json_encode(glob("photos-".$_GET["folder"]."/*.jpg")) ?>);
because if i MANUALLY enter in the address bar ?folder=animaux...bam! work
so the problem shoul be there : $.get("photo-portfolio.php",{folder:"animaux"});
still dont know where !
If you're using $.post() from JQuery, you should use $_POST['folder'] to access your variable. If you use $.get(), then you use $_GET['folder'] in PHP. Try changing that $_GET to $_POST.
Change $_GET["folder"] to $_POST["folder"] ?
You can dump the $_POST to be sure you're getting the right info..
echo '<pre>', print_r( $_POST, 1), '</pre>';
I hope you're not literally writing these two lines together and hope they are interacting, are you?
$.post("",{'folder':'animaux'});
startSlideshow(<?php echo json_encode(glob("photos-".$_GET["folder"]."/*.jpg"))?>);
PHP runs on the server, Javascript in the browser. In the above two lines, if written like this, the PHP is already long done by the time $.post() is called.
PHP processes the code on the server and sends this to the browser:
$.post("",{'folder':'animaux'});
startSlideshow(['something.jpg', 'something2.jpg']);
The browser executes this code:
Post {'folder':animaux'} to "" (no effect whatsoever).
Start a slideshow with ['something.jpg', 'something2.jpg'] (which was already decided by the time the page loaded).
I hope you're aware of this two stage process.

Categories