472,358 Members | 2,054 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,358 software developers and data experts.

passing a variable from page to another page

25
Hi there, I would like to ask a question about how to pass a variable from page to page. For example, I have my first page for login and used a session with cookie and after submitting successfully and redirect my page to another page I want show statement like Hello Smith or Welcome Smith, and it doesn't work properly. Anyone knows the soulution would be appreciated. Thanks

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. if (loggedin())
  3.     {
  4.     header("Location: redirectpage.php");
  5.     exit();
  6.     }
  7. if ($_POST["login"])
  8. {
  9.     global $username;
  10.     $username = $_POST['username'];
  11.     $password = $_POST['password'];
  12.     $rememberme = $_POST['rememberme'];
  13.  
  14.  
  15.     if($username&&$password)
  16.     {
  17.  
  18.     $login = mysql_query("SELECT * FROM usersystem where username='$username'");
  19.     while ($row = mysql_fetch_assoc($login))
  20.     {
  21.         $db_password = $row['password'];
  22.         if($password==$db_password)
  23.  
  24.     else
  25.         setcookie("username", $username, time()+7200);
  26.         else if ($rememberme=="")
  27.         $_SESSION['logged_in']== $username;
  28.         $_SESSION['username'] =$_POST['username'];
  29.  
  30. //userarea.php
  31.         header("Location: redirectpage.php");
  32.         exit();
  33.  
  34.         }
  35.  
  36.     }
  37.  
  38.     }
  39.     else
  40.     die("Please enter a username and password");
  41.  
  42. }
  43. ?>
  44.  
This is the code for the second page that I want the name of the user to show up.

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3.  
  4. $username = $_SESSION['username'];
  5.  
  6. echo $_SESSION['username'];
  7.  
  8.  
  9.  
  10. echo "Hello ". $username ;
  11. ?>
So what's wrong with my code. Thanks again
Jan 21 '10 #1
20 3255
Atli
5,058 Expert 4TB
Hey.

There is a syntax error there on line 24. The if, else and else if statements don't match up.

It is generally best to always use brackets with if statements, even if they only execute on line of code. It helps to avoid problems like these.

Expand|Select|Wrap|Line Numbers
  1. // Avoid this:
  2. if(true == true)
  3.     echo "It is true!";
  4. echo "A completely unrelated line...";
  5.  
  6. // Rather do this:
  7. if(true == true) {
  8.     echo "It is true!";
  9. }
  10. echo "A completely unrelated line...";
There are a couple of extra charachters required, but it makes it a whole lot clearer to read, especially if your indentations are sloppy.
Jan 21 '10 #2
RomeoX
25
Actually the I wrote the code and I knew that it's wrong because I picked up just for example of how to pass session variable to another page and I was asking about this. Anyway thanks a lot of passing my thread.
Jan 21 '10 #3
johny10151981
1,059 1GB
you can try this

Expand|Select|Wrap|Line Numbers
  1. redirectpage.php?user_name=johny&user_age=100
then in redirectpage.php usign $_GET you can have the data. i.e
Expand|Select|Wrap|Line Numbers
  1. $name=$_GET[user_name];
  2. $age=$_GET[user_age];
Regards
johny
Jan 22 '10 #4
RomeoX
25
Thanks for reply I'm really thankful to u

by the way, actually the first code that I submitted in the first topic that will be in the login screen and I can't pass the login and password in the tool bar of the browser so I'm using POST instead of get because it's much secure. I tried your code but I used POST but couldn't get the username.

So what should I do?
Jan 22 '10 #5
johny10151981
1,059 1GB
I dont know what is your plan.

But if you try session it may help. After user log in you can save the user_name and Password using session. your php page will be able to use these session anytime if session is valide. Cookie is a solution but a very easy solution to destroy the security.

Regards,
Johny
Jan 23 '10 #6
Atli
5,058 Expert 4TB
OK, to answer the original question: there are a couple of methods you can use to pass things between pages.
  1. Sessions
    These are the most secure of the methods, because the actual data is stored on the server, while only a session identifier is passed to the browser (usually as a cookie). Any page on the domain can then activate the session and use the data, given that the cookie is not destroyed. This is highly recommended for storing sensitive data, such as user login information.
  2. Cookies
    Less secure and reliable than sessions, but more long-term. Whereas a session is destroyed every time the browser is closed (by default), a cookie can remain indefinitely. It is usually best not to use these to store sensitive info, only info that would not be a security threat if it fell into the wrong hands.
  3. GET parameters
    Adding variables to the URL can serve as a (very) short-term method of passing data between pages. This is usually reserved for things like passing paging information via navigation links. In general, if the same piece of data needs to be passed to more than a couple of pages, a session or a cookie is a better choice.
There are a few more possible methods, but they are generally so situational and questionable that they are hardly worth mentioning.

For the purposes of storing user login data, a session would be ideal. Putting the user name and ID into the session is pretty standard.

This is a pretty generic example of how that would be done.
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Make sure the login info was passed
  3. if(isset($_POST['name'], $_POST['password'])) 
  4. {
  5.     // Fetch the user name from POST.
  6.     // Note the use of the mysql_real_escape_string function.
  7.     // It should ALWAYS be used on data that is to be
  8.     // inserted into a SQL query.
  9.     $name = mysql_real_escape_string($_POST['name']);
  10.  
  11.     // Fetch the password. Note that I hash() the password.
  12.     // This ensures the password is secure, even if
  13.     // the database itself is comprimized. You should
  14.     // ALWAYS hash passwords, and never store them as
  15.     // plain text. The above rule about the escape_string
  16.     // function does not apply here, as a hash is always 
  17.     // safe to put into a SQL query.
  18.     $pwd_hash = hash('sha1', $_POST['password']);
  19.  
  20.     // Verify that the login info is valid.
  21.     // It is better to fetch the user info based on
  22.     // the username and the password, rather than to pass
  23.     // it only the username and verify the password with
  24.     // PHP. This way, if the login is invalid, the real
  25.     // password never enters your PHP code, making it more
  26.     // secure.
  27.     $sql = "SELECT `id` FROM `user` 
  28.             WHERE (`name` = '{$name}')
  29.             AND   (`password` = '{$pwd_hash}')";
  30.  
  31.     $result = mysql_query($sql) or trigger_error(mysql_error(), E_ERROR);
  32.  
  33.     // If a single row was returned, the user info is
  34.     // valid. If more than a single row was returned,
  35.     // odds are that something went rong, or that your
  36.     // code has somehow been comprimized. This is why
  37.     // you should validate ONLY if a single row is returned.
  38.     if(mysql_num_rows($sql) == 1) 
  39.     {
  40.         $row = mysql_fetch_assoc($sql);
  41.  
  42.         // Here we start the session and enter the
  43.         // user info into it. Note that session values
  44.         // can be arrays themselves, so that you can group
  45.         // similar elements together, like I do here.
  46.         session_start();
  47.         $_SESSION['user']['id'] = $row['id'];
  48.         $_SESSION['user']['name'] = $name;
  49.     }
  50.     else
  51.     {
  52.         echo "Login failed. Please try again!";
  53.     }
  54. }
  55. else
  56. {
  57.     echo "Username and/or password were not passed.";
  58. }
  59.  
  60. ?>
You can then verify a user as logged in on other pages by doing something like:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3.  
  4. // Check if the user session element exists.
  5. // If it does, we can assume the client has
  6. // already logged in. If not, we can not.
  7. if(!isset($_SESSION['user']))
  8. {
  9.     // Redirect back to the user login page.
  10.     header('Location: login.php');
  11.     exit;
  12. }
  13.  
  14. // Display the rest of the user-secure content.
  15. echo "Welcome, {$_SESSION['user']['name']}!";
  16. ?>
@johny10151981
You should NEVER store the password anywhere, especially in it's plain-text form. If you absolutely can not avoid it, you should at least hash it before doing so. Passwords are one of the more sensitive pieces of info your application will ever handle and they should be used as little as possible.

I mean, consider if a malicious user managed to inject a PHP script to your server. It would be fairly easy for him to hijack sessions and view all the session data, including the password. Limiting this to usernames and IDs makes this sort of breach a lot less damaging.
Jan 23 '10 #7
kovik
1,044 Expert 1GB
I disagree. The password should be stored in its hashed form. What if two users are logged into the same account at once? What if the valid user knew that someone knows his password and he needs to change it before the other user harms his account? He would then change his password. If the password was re-authenticated on every page request (as I believe it should be), then the false user would be essentially logged out.
Jan 23 '10 #8
Atli
5,058 Expert 4TB
That's an extremely rare scenario, to be honest, and preventing it hardly takes priority over the security of all passwords being used. Even in it's hashed form, in the hands of a malicious user a password would be a major security concern.

But if this scenario is of great concern to you, a far more sensible method - surely - would be to add a "modified" timestamp to the user account that would be updated with the password. The value of that timestamp at the time when a user is logged in would then be stored with the session and checked on every reload.

There is rarely a situation where you need to store the password anywhere - outside normal login and account maintenance - and you really should avoid it wherever possible, for obvious security reasons. That is what I would generally recommend, in any case.
Jan 24 '10 #9
johny10151981
1,059 1GB
Hi Atli,
You have comment out one of my line. Actually I am explaining it. I did tell to store data using SESSION but I didnt mean to store in storage device like hard disk. If I am not wrong session data get stored in the server and in the RAM. My understanding says Session stores run time data.

I also strongly disagree password in server's storage device.

Regards,
Johny
Jan 24 '10 #10
kovik
1,044 Expert 1GB
... Session data is stored on the HDD. Computers don't really "store" anything on the RAM. The contents of the RAM have the potential to be ever changing.

And in regards to the password, what if someone gained access to the session data? I think the risk of them simply guessing a user ID and gaining access to that account is less secure than them having to know the user name and the hashed password from the database.
Jan 24 '10 #11
Atli
5,058 Expert 4TB
You have comment out one of my line. Actually I am explaining it. I did tell to store data using SESSION but I didnt mean to store in storage device like hard disk. If I am not wrong session data get stored in the server and in the RAM. My understanding says Session stores run time data.
Session data is stored on the server's HDD by default. It can be configure to store it in shared memory (RAM), or even using a custom save handler, but that is usually not the case.

Anyways, it doesn't matter. If the server is secure, either method works fine. Your PHP application will never know the difference. - Your server's performance may vary, but that's irrelevant to our discussion.

And in regards to the password, what if someone gained access to the session data? I think the risk of them simply guessing a user ID and gaining access to that account is less secure than them having to know the user name and the hashed password from the database.
I don't follow. How would guessing a user ID allow them access to an account?
(I'm getting close to 28 hours without sleep, so forgive me if I am missing something obvious xD)
Jan 24 '10 #12
kovik
1,044 Expert 1GB
@Atli
In the event that they have access to the session data. It is more likely that this would be a trusted user that you had given your server password, but this user could potentially log in to any account that they wanted without needing to know their password. They would simply alter the user ID in their session data.
Jan 24 '10 #13
Atli
5,058 Expert 4TB
@kovik
If we are indeed talking about a trusted user, I would assume that trust covered not logging into other user's accounts. And if it were not a trusted user, and he manage to get your server passwords or hack into the server, the risk of him access random user accounts should be the least of your worries.

In any case, having the password in the session wouldn't really prevent this either. Any open session, or one that has not yet been cleaned up, would also be vulnerable. He would just have to copy the session as-is.

And if you implemented the "modified" timestamp, as I suggested before, guessing the ID of a user would not work. He would have to guess that exact timestamp as well. (Although this would of course not protect users with open/garbage sessions, no more than with the passwords.)
Jan 24 '10 #14
kovik
1,044 Expert 1GB
Security is such a nitpicky subject, ain't it? :P
Jan 24 '10 #15
Markus
6,050 Expert 4TB
@kovik
Rightly so.

And, while we're picking nits, johny10151981, array indexes should have quotes around them (unless they are indeed declared constants). Otherwise the PHP engine wastes time determining its stored data.

Expand|Select|Wrap|Line Numbers
  1. // Bad:
  2. echo $some_array[the_array_index];
  3.  
  4. // Fine:
  5. echo $some_array['the_array_index'];
  6.  
  7. // Also fine:
  8. define('the_array_index', 'some_index');
  9. echo $some_array[some_index];
  10.  
Jan 24 '10 #16
kovik
1,044 Expert 1GB
define($name, $value)

I think you switched the name and value, Markus.
Jan 24 '10 #17
Markus
6,050 Expert 4TB
My bad. You thunk correct :)

P.S Good to see you posting again.
Jan 24 '10 #18
kovik
1,044 Expert 1GB
Been busy gettin' paid. ;)
College starts back up today. I post here on my in-between time in school. That means I'm back. lol :3
Jan 25 '10 #19
RomeoX
25
Thanks a lot guys for this posts, I really appreciate your comments and your answer. It's working now fine.


I have a question related to Session. I made a login screen and all pages except than the login page should be secure so no one can access to any page unless access from the main login page so I did this coding but even if someone did a log off I still can access any page unless I remove the cookies from the folder. In my login screen I have option of "Remember Me" but I didn't check it and I still can open the pages that I already browsed.

This code I putted in my important pages
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include 'functions.php';
  3. session_start();
  4. if($_SESSION["a"]!=1)
  5. {
  6. header("location:index.php");    
  7.  
  8. }

And this is my login screen. You can read my comments inside the code I putted two slashes.
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include 'functions.php';
  3.  
  4.  
  5. if ($_POST["login"])
  6. {
  7.     global $username;
  8.     $username = $_POST['username'];
  9.     $password = $_POST['password'];
  10.     $rememberme = $_POST['rememberme'];
  11.  
  12.  
  13.     if($username&&$password)
  14.     {
  15.  
  16.     $login = mysql_query("SELECT * FROM usersystem WHERE username='$username'");
  17.     while ($row = mysql_fetch_assoc($login))
  18.     {
  19.         $db_password =  $row['userpass'];
  20.         if(md5($password)==$db_password)
  21.         $loginok = TRUE;
  22.     else
  23.         $loginok = FALSE;
  24.  
  25.         if ($loginok==TRUE)
  26.         {
  27.             $_SESSION["a"] = 1; // This line responsible for not allow anybody to access another page unless entered the user name and password correct. But I still access another pages even if I don't check the Remember Me check. What's the soulution?.
  28.             if ($rememberme=="on")
  29.             setcookie("username", $username, time()+7200);
  30.         else if ($rememberme=="")
  31.         $_SESSION['username']== $username;
  32.         $_SESSION['username'] =$_POST['username'];
  33.  
  34.         header("Location: redirectpage.php");
  35.         exit();
  36.  
  37.         }
  38.  
  39.     }
  40.  
  41.  
  42.     }
  43.     else
  44.     die("Please enter a username and password");
  45. }
  46.  
  47. ?>
  48.  
Jan 26 '10 #20
Markus
6,050 Expert 4TB
Please create a new thread for separate questions.
Jan 26 '10 #21

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Paul | last post by:
Hmmm, didn't seem to work. I have set session.use_cookies = 1 and session.use_trans_sid = 1 in my php.ini file. Index.php contains:...
4
by: Jason Us | last post by:
Does anyone have experience with passing variables from an ASP page to a JSP page. The way it currently works in passing the SSN in the URL. This cannot be good. I thought that storing a...
58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
4
by: opt_inf_env | last post by:
Hello, I know three ways to pass variables form one page to another. The first one is to declare and set session variable. In this case if one goes to another page (by clicking on hyperlink or...
10
by: Geoff Cox | last post by:
Hello, I have written before that I can pass a variable from page 1 to page 2 if I call the variable "name". Stephen Chalmers has written, >'name' is effectively a reserved word as the...
2
by: Mike P | last post by:
When you are passing a value to another page, and will need access to it throughout the page and on any postbacks, what is the best way to store it? By making it a variable accessible to the whole...
3
by: James Robertson | last post by:
I am new to the ASP and VB thing so be kind. Question I have is that I have created an ASPX web site to use as an E-Mail page. But I want to use this for a lot of users. Can I create the link on...
3
by: DaTurk | last post by:
If I call this method, and pass it a byte by ref, and initialize another byte array, set the original equal to it, and then null the reference, why is the original byte array not null as well? I...
1
by: rfr | last post by:
I have a need to use a single version of a Visitor Response Feedback Form on numerous HTML documents. Rather than have numerous versions of this, one on each HTML document, it makes more sense to...
5
by: aelred | last post by:
I have a web page where a member can open up a chat window (child window) with another member. - From there the member can also navigate to other web pages. - From other pages in the site, they...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
0
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.