Jump to content

Help With Session And If Else ..


spacepoet

Recommended Posts

Hello:

 

I do not quite understand how SESSIONS work, so now is a good time to seek some answers ..

 

I am trying to make a SESSION that will set a default location (if the session is blank) or display a SESSION requested from another link on that page, or a different page.

 

Not fairing as well as I had hoped ..

 

So ..

 

Page.php:

<?php

session_start();

$_SESSION['showCity'];

$showCity = $_GET['showCity'];

if($_SESSION['showCity'] == "") {
echo "Philadelphia PA, 19128";
}

else
{
echo $showCity;
}

<html>
<? echo $showCity; ?>
</html>

 

I am trying to define the SESSION at the top of the page, and then display it one or more times on the page. Not working ...

 

Also, how would I change it if the SESSION variable is different on another page:

<a href="Page.php?showCity='Lancaster PA, 14567">Lancaster PA, 14567</a>

 

Can someone clear up my confusion .. ??

Link to comment
Share on other sites

Sessions works in a two-stage manner:

  1. PHP first generates and ID to identify the session, then it creates a text-file on the server, where it stores all the data associated with the session. Using the session ID as the name of said file. Once this is done, the session ID is sent to the client via a cookie (which is stored in a text file on the user's computer).
  2. Then, on every subsequent page load, for as long as the cookie exists on the client, the client sends the session ID back to the server in the HTTP request. The server then uses this ID to find and read the session file from disk, re-populating the $_SESSION array with all of the data that was saved inside this file.

If any of the data in the $_SESSION array is changed, then the session file is automatically updated on the server whenever the PHP script finishes parsing.

 

Note that you have to start the session (using session_start ()) on every page that is meant to use the session variables, in order to get it to read the data from disk. Otherwise the server will just ignore the session cookie.

 

Hopefully that helped to clear up the confusion?

Link to comment
Share on other sites

Hello there:

 

Thanks for posting this well-written explanation.

 

Yes, this does clear-up some of my questions! :)

 

But I cannot get my script to work:

<?php

session_start();

$_SESSION['showCity'];

$showCity = $_GET['showCity'];

if($_SESSION['showCity'] == "") {
$_SESSION['showCity'] == "Philadelphia PA, 19128";
}

else
{
$_SESSION['showCity'] == $showCity;
}

<html>
<? echo $showCity; ?>
</html>

 

Is it possible to do this is PHP?

 

I am asking because I use to do something very similar in Classic ASP using a SERVER.TRANSFER method.

But PHP does not have SERVER.TRANSFER.

 

Any ideas how to get my script working properly?

 

Thanks!

Edited by spacepoet
Link to comment
Share on other sites

you never assign any value to $_SESSION['showCity'] I think (if your are trying to do what I think you are) the problem is a flaw in your basic logic. You are checking if the session variable is an empty string, and if it is loading up the default, however, as you never assign anything to the variable it's never going to change. It's also not what you want to be checking. You want to check the $_GET[''] value, which is the one that will change depending on which link is clicked. something like

session_start();
if(!isset($_GET['showCity'])){
$cityToShow = 'Philadelphia PA, 19128';
}
else{
$cityToShow = $_GET['showCity'];
}
$_SESSION['showCity'] = $cityToShow;

also, your <a> tag is missing a closing single quote at the end of the href variable

Link to comment
Share on other sites

Hello:

 

Thanks for showing me this! I do have it working on the initial page.

<?php

session_start();
if(!isset($_GET['showCity'])){
$cityToShow = 'Philadelphia PA, 19128';
}
else{
$cityToShow = $_GET['showCity'];
}
$_SESSION['showCity'] = $cityToShow;
?>

<html>
<? echo $cityToShow; ?>
</html>

 

But, how to I "swap" the city to another one of a new link is clicked (on this page or a different page)?

 

I tried this:

sitemap.php

<?php

session_start();
if(!isset($_GET['showCity'])){
$cityToShow = 'Lancaster';
}
?>

echo "<li class='site-map-ul-li'><a href='$id.$myPageURL.$cityToShow.html' title='".$myTitle."'>".$myButtonTitle."</a></li>";

 

But it did not work ...

"$cityToShow" writes the word "Lancaster" into the URL, so I assume it is working.

 

I am using mod re-write to write the URLs"

.htaccess

RewriteRule ^([0-9]+).([a-zA-Z0-9\-]+).([a-zA-Z0-9\-]+)\.html$ myPage.php?id=$1&myPageURL=$2cityToShow=$3 [L]

 

Any ideas on how to accomplish this .. ??

Edited by spacepoet
Link to comment
Share on other sites

First off I'd just like to point out that the code you're using, and the example, are completely void of any security. Which means you're open to HTML injection attacks, such as XSS and similar. You should look into how to validate input, to make sure that what you get adheres to a rule which specifies how a "city name" looks like; And output escaping, which'll ensure that all characters that has a special meaning to HTML gets translated to something safe.

 

Then to your question:

I'd rewrite your code a bit, to do away with the $cityToShow variable. You don't need it, as you have the information in the $_SESSION array already. Just print that out directly, and you're set.

<?php

session_start();

// If the showCity GET parameter has been set in the URL.
if (isset ($_GET['showCity']) {
   // Make sure that showCity only contains letters or numbers.
   if (!ctype_alphanum ($_GET['showCity'])) {
       // City contained invalid charcters, show error.
       $error = 'Not a valid city name';
   } else {
       // City name validated, add to session array.
       $_SESSION['city'] = $_GET['showCity'];
   }
}

// If the city name is not set, add default.
if(empty ($_SESSION['city'])){
   $_SESSION['city'] = 'Philadelphia PA, 19128';
}
?>

<html>
<!-- TODO: Write out the error message, if set. -->
<?php echo htmlspecialchars ($_SESSION['city']); ?>
</html>

 

Now if you want to change the city name on another page, then you'll want to do exactly the same as you did above. You may want to do something else if the validation fails, or if the city name isn't set, but the actual change is the same. ;)

 

Note that this code is just an example, and you'll still need to handle the error message. You'll also see that I've used htmlspecialchars () to escape the HTML output, and ctype_alphanum () to validate the input.

There's only one (potential) problem with the input validation, when compared to the default example you've given: It does not accept spaces nor commas. So if you expect these two characters to be legit for a city name, then you'll need to use a Regular Expression to validate the value.

Edited by Christian F.
Link to comment
Share on other sites

Hi Christian (and everyone else!):

 

OK - thanks!! This is starting to come together for me. This was driving me nuts for days .. lol ..

 

I have two questions:

 

1 - Is there a relatively easy way to store the SESSION in a cookie, in case a user bookmarks the site? I am trying to get them to land on the site with the city/state/zip they type into a search engine, and then hopefully it will grab that city from the SESSION.

I am writing it into the page URL as well. I was hoping to store it for a year, actually.

 

2 - I wanted to see if you new a way to display and/or write the SESSION in two ways, based on what you showed me:

session_start();

// If the showLocation GET parameter has been set in the URL.
if (isset ($_GET['showLocation'])) {
 // Make sure that showLocation only contains letters or numbers.
 if (!ctype_alphanum ($_GET['showLocation'])) {
		 // City contained invalid charcters, show error.
		 $error = 'Not a valid city name';
 } else {
		 // City name validated, add to session array.
		 $_SESSION['myLocation'] = $_GET['showLocation'];
 }
}

// If the city name is not set, add default.
if(empty ($_SESSION['myLocation'])){
 $_SESSION['myLocation'] = 'Lancaster, PA 19480';

}

 

I wanted to be able to be able to display it on the page as is:

Lancaster, PA 19480

 

But somehow do a replace to change the comma and empty space into dashes for when I write it into the page URL:

Lancaster-PA-19480

 

Can both of these be done .. ??

 

Thanks much!

Edited by spacepoet
Link to comment
Share on other sites

Hi again:

 

Can you see why the SESSION is not getting carried onto the main page .. ??

 

I am listing the records of locations entered from the database (and I *THINK* starting a SESSION for them ..??);

sitemap.html (re-written from "sitemap.php" in the .htaccess file):

<?php

session_start();
$_SESSION['myLocation'] = $myLocationContent;


<html>
  	 <?
       $query2 = "SELECT myLocationActive, myLocationContent, l_listorder FROM myLocations WHERE myLocationActive='Yes' ORDER BY l_listorder";
       $result2 = mysql_query($query2);
       $num_rows2 = mysql_num_rows($result2);

       for($j=0;$j<$num_rows2;$j++)
       {
       $row2 = mysql_fetch_array($result2);
       $myLocationContent = $row2['myLocationContent'];

       echo "<li class='site-map-ul-li'><a href='1.Private-Music-Lessons-Private-Music-Teacher.$myLocationContent.html' title='".$myLocationContent."'>".$myLocationContent."</a></li>";
       }
       ?>


</html>

 

The "1.Private-Music-Lessons-Private-Music-Teacher..." page is the homepage/default page on the site that I create with mod re-write in .htaccess:

# This makes the default page the one with an id of 1
RewriteRule ^$ myPage.php?id=$1&myPageURL=$2myLocationContent=$3 [L]

# This is for all the other pages
RewriteRule ^([0-9]+).([a-zA-Z0-9\-]+).([a-zA-Z0-9\-]+)\.html$ myPage.php?id=$1&myPageURL=$2myLocationContent=$3 [L]

 

Regardless if that is relevant, I set-up the link for the locations on the "sitemap.html" page in .htaccess like this:

RewriteRule ^1.Private-Music-Lessons-Private-Music-Teacher.([a-zA-Z0-9\-]+)\.html$ 1.Private-Music-Lessons-Private-Music-Teacher.$myLocationContent\.html [L]

 

Then on "myPage.php (re-written for each page with .htaccess):

<?php

session_start();

if (isset ($_GET['myLocationContent'])) {
    if (!ctype_alphanum ($_GET['myLocationContent'])) {
		    $error = 'Not a valid city name';
    } else {
		    $_SESSION['myLocation'] = $_GET['myLocationContent'];
    }
}

if(empty ($_SESSION['myLocation'])){
    $_SESSION['myLocation'] = 'Philadelphia';
}
?>

<html>
<?php echo htmlspecialchars ($_SESSION['myLocation']); ?>
</html>

 

 

I keep getting "Philadelphia" every time, even though the link(s) on "sitemap.html" might be "Lancaster" or "Atlanta"

 

The URL are written properly (2.this-is-a-page.Lancaster.html"), but once I click the link and go to "myPage..." it/the SESSION goes to (2.this-is-a-page.Philadelphia.html").

 

Any idea what I'm doing wrong and how I can get this to work .. ??

 

Thanks!

Link to comment
Share on other sites

Hi there:

 

Not sure ... I assume that function is pre-defined in the mySQL database (if that is even possible; I always assumed that's how a function like "my_real_escape_string" worked) .. ??

 

I do know I am almost there with my project, but can't get this last part to work ..

 

Any ideas?

 

Can I somehow transfer "myLocationContent" as a variable onto the main page, and then create the SESSION .. ??

 

Thanks.

Link to comment
Share on other sites

Oh, I see what you mean.

 

I found (via GOOGLE) that it should be:

if (!ctype_alnum ($_GET['myLocationContent'])) {

 

not alphanum

 

But, it has not changed how the page works (meaning, I still get the same results).

 

Do you even have error reporting turned on?

 

I'm going to say no, because my next question is to ask how I turn that on ...

 

??

 

I'm still learning ..

 

EDIT:

 

I just added this (exactly as I listed it) to the php.ini file:

ini_set('error_reporting', E_ALL);

 

but no errors are displayed ..

 

Is this the correct way to do it .. ??

Edited by spacepoet
Link to comment
Share on other sites

You really should be developing locally. It would save you a ton of time not having to FTP files every time you make a change and need to test it.

 

In the meantime, then first lines in that file after the opening php tag should be:

 

error_reporting(-1);
ini_set('display_errors', 'On');

 

You also need to remove the line you said in a previous post that you added to the php.ini file. The syntax is incorrect.

Link to comment
Share on other sites

Hello:

 

I will have to explore getting a local server.

 

But, I did get it to work this way:

echo "<li><a href='myPage.php?id=1&myPageURL=Private-Music-Lessons-Private-Music-Teacher&myLocationContent=$myLocationContent' title='".$myLocationContent."'>".$myLocationContent."</a></li>";

 

which is not ideal, but at least it is a start.

 

Can you recommened how I might use mod re-writing to make a "better" URL .. ??

 

I do want the id to always be 1 and the myPageURL to always be "Private-Music-Lessons-Private-Music-Teacher"

 

I use this to re-write the other pages, but it does not work for this.

RewriteRule ^([0-9]+).([a-zA-Z0-9\-]+).([a-zA-Z0-9\-]+)\.html$ myPage.php?id=$1&myPageURL=$2myLocationContent=$3 [L]

 

One other thing I noticed (it is always something!): when I use 1 word for the "myLocationContent (like "Philadelphia") it writes the URL fine, but if it is 2 or more words (like "Philadelphia PA" - I assume the space is the issue) it does not work.

 

Can this be fixed .. ??

 

Thanks for all the advice and input!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.