I am trying to write a script that changes a veriables content depending on there session status and what ID that was in the URL of the page (e.g www.example.com/profile.php?id=1) so it would display one set of content if they arnt logged in and viewing someone elses profile, another if there logged in and on there own profile, and another if there logged in and viewing someone elses profile.
Firstly the script gets the ID from the url:
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
Then it runs some other code i wont include, then this code:
// ------- DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If session is set and ID matches the profiles ID
$content = ""Your viewing your own profile";
} else if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION is set, but ID dosent match profiles ID
$follow_option = "Your viewing someone elses profile";
} else {
$content = "Your are not logged in";
}
// ------- END DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
print $content;
Now to my problem, all it does is display the option for being logged in and viewing someone elses profile "Your viewing someone elses profile". If you see any errors that would lead to this, please answer below. Thanks! :)
It seams your variables don't hold the expected values when the $logOptions_id != $id runs, or you either forget to start the session. I don't see reference where $logOptions_id gets assigned. Use your IDE tool to debug the code.
Related
I'm creating a profile page where the name of the user can be edited. I can't seem to figure out how to update the name of the user that is displayed at the top page (i.e. Hi Kana!) after a successful edit.
The name is generated using a session variable at the top of my page, $_SESSION['username']
<?php
session_start();
if(isset($_POST['submit']) && isset($_SESSION['newusername'])){
unset($_SESSION['username']); //clear existing username session
$_SESSION['username'] = $_SESSION['newusername']; //replace with the new username
echo $_SESSION['username'];
} else {
echo $_SESSION['username'];
}
?>
After hitting the submit button with a different name set on the text input it should change but it does not. These are the lines of codes after the code I mentioned above.
<?php
$textinput = $_POST['textinput'];
if(isset($_POST['submit']))
{
if(strlen($_POST['textinput']) < 2)) {
$errormessage = 'too short';
}
else
{
$_SESSION['newusername'] = $textinput; //setup a new session for the new username to be used above.
}
}
?>
Note that the two quoted set of codes are in the same page.
What happens is that the name still shows the previous name, which is supposedly overwritten. I tried refreshing the page but it still does not change, I need to submit again (2nd time) to show the new name.
You can and should drastically simplify your code. Currently there are a variety of unnecessary operations here. Consider semantically what you want to accomplish:
If the user submits their name, update the session with the new value. Then output the value.
That's it. Let the semantics of what you want to accomplish guide how you accomplish it. Start the session, check for the form post, conditionally update the value, output the current state of the value. For example:
<?php
session_start();
// update the value
if(isset($_POST['submit'])) {
$_SESSION['username'] = $_POST['textinput'];
}
// output the value
echo $_SESSION['username'];
?>
Maybe you'll want to add a sensible default in the absence of a username. That would just be something like:
<?php
session_start();
// set a default value
if (!isset($_SESSION['username'])) {
$_SESSION['username'] = "Default User";
}
// update the value
if(isset($_POST['submit'])) {
$_SESSION['username'] = $_POST['textinput'];
}
// output the value
echo $_SESSION['username'];
?>
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
$goHere = 'Location: /index2.php?id=' . $id;
header($goHere);
exit;
}
I have the following code that once logged in, it $_GET the id and prepends to the url like index2.php?id=5 . How do I keep this id=5 in the URL no matter WHAT link they click on??
This id is grabbed from this:
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
What I want to do
Well way i have it setup, you login, it then sends you to the homepage such as index2.php?id=[someint] , if you click another link say 'prof.php', it removes the id=[someint] part, I want to keep it there in the url, so as long as a user is LOGGED in -- using my code above, the url might read: index.php?id=5, then go to another page it might read prof.php?id=5, etc, etc. This integer would obviously be dynamic depending on WHO logged in
Instead of passing around an ID in the URL, consider referring to the id value in the $_SESSION variable. That way the user can't modify the URL and see data they aren't supposed to see (or much worse), and you don't have to worry over appending it to every URL and reading it into a value every time you go to process a script. When the user logs in, you determine their ID - read it from a database, determine it realtime, whatever. Then store it in the $_SESSION and refer to it as needed. You can even use this as part of a check to see if the user is logged in - if they have no $_SESSION['id'] value, something is wrong and you make them log in.
The query string isn't the place for that, for a whole host of reasons. The most obvious one is that I can log in with a valid account, then change the number in the URL and it'll think I'm someone else.
Instead, just continue using the session as it's the proper way.
If you REALLY want to do it, you'd probably want to write a custom function for generating links
function makeLink ($link, $queryString = '')
{
return $link . '?id=' . (int) $_SESSION['id'] . ((strpos($queryString, '?') === 0) ? substr($queryString, 1) : $queryString);
}
called like
Click me
As a basic auth example using the ID...
<?php
// Session start and so on here
if (!isset($_SESSION['id']))
{
// Not logged in
header('Location: /login.php');
exit;
}
http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/ is a pretty straightforward full example of it.
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Errors for changing variables content depending on session status
Hello! I am trying to write a script that changes a veriables content depending on there session status and what ID that was in the URL of the page (e.g www.example.com/profile.php?id=1) so it would display one set of content if they arnt logged in and viewing someone elses profile, another if there logged in and on there own profile, and another if there logged in and viewing someone elses profile.
Firstly the script gets the ID from the url:
if(isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
Then it runs some other code i wont include, then this code:
// ------- DECIDES WHAT TO DISPLAY, DEPENDING ON SESSION---------
if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If session is set and ID matches the profiles ID
$content = ""Your viewing your own profile";
} else if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION is set, but ID dosent match profiles ID
$follow_option = "Your viewing someone elses profile";
} else {
$content = "Your are not logged in";
}
// ------- END DECIDES WHAT TO DISPLAY, DEPENDING ON SESSION---------
print $content;
Now to my problem, all it does is display the option for being logged in and viewing someone elses profile "Your viewing someone elses profile". If you see any errors that would lead to this, please answer below. Thanks! :)
From what I can see, there are no errors.
The id just doesn't match logoptions.
Most likely, you are changing the id or logoptions somewhere between tha assignment and the final check. Try a vardump in both locations on both variables to see if they still match.
Btw, you can use intval() or simply cast as (int) instead of the regex
i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? ยป Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.
I'm using a login system, and I'm trying to keep the user logged in for 10 days unless they specifically log out. I thought by using session_set_cookie_params('864000'); that it would make the user stay logged in for 10 days. But it's not doing that, at least in Chrome. The user only seems to be logged in for the standard 20-30 minutes before being automatically logged out. When I check the cookies in Chrome, there are two PHP Session cookies listed for my URL with expiration dates 10 days into the future. But this seems to be unrelated to the login variables. Most of the relevant code should be below.
Any idea why the user is not logged in for 10 days?
Thanks in advance,
John
In the index file, I have the following:
require_once "header.php";
//content
include "login.php";
In the header.php file, the following is included:
session_set_cookie_params('864000');
session_start();
In the login.php file, the following is included:
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
}
Here is the function "checkLogin":
function checkLogin($u, $p)
{
global $seed; // global because $seed is declared in the header.php file
if (!valid_username($u) || !valid_password($p) || !user_exists($u))
{
return false; // the name was not valid, or the password, or the username did not exist
}
//Now let us look for the user in the database.
$query = sprintf("
SELECT loginid
FROM login
WHERE
username = '%s' AND password = '%s'
AND disabled = 0 AND activated = 1
LIMIT 1;", mysql_real_escape_string($u), mysql_real_escape_string(sha1($p . $seed)));
$result = mysql_query($query);
// If the database returns a 0 as result we know the login information is incorrect.
// If the database returns a 1 as result we know the login was correct and we proceed.
// If the database returns a result > 1 there are multple users
// with the same username and password, so the login will fail.
if (mysql_num_rows($result) != 1)
{
return false;
} else
{
// Login was successfull
$row = mysql_fetch_array($result);
// Save the user ID for use later
$_SESSION['loginid'] = $row['loginid'];
// Save the username for use later
$_SESSION['username'] = $u;
// Now we show the userbox
return true;
}
return false;
}
Looks more likely that your server is discarding the sessions -- you'd need to store pertinent information in a local friendly database and load from there, based on the cookies as appropriate