I'm creating an online store using ajax and php. My index has a login section that appears with ajax and also have a navigator bar that gets the name of the user when completes the login.
So, when you login to the page the form sends you to Login.php, where you can see the content of the session and the navigator bar changes as explained before.
I only had session_start() on the index page, and it worked fine; the SESSION stored everything I wanted and the navigation bar worked, showing the name. But then when I changed something with ajax and printed out the session (print_r($_SESSION)) it turned out that the session had disappeared and it wasn't defined.
A friend told me to put session_start() in every page, so I put it in the Login.php file and now the session variable appears to be empty right after the login, so the navigator bar doesn't even work.
Also, when refreshing the index after getting logged in, it doesn't stay logged at all.
So it appears that the Session stores the variables but they don't stay stored for long.
I'm trying to use the MVC scheme (it's an assignment) so I only use the session_start on the index and the login page, not on the "controllers" and the "views"
To sum up, my session works at the beggining, it stores data, I change to the second page and still works and after loading the page the content is gone and the session undefined, but if I write down "session_start()" on the second file it doesn't even work
Here is the code where I get info from the db. (I don't think it's usefull but)
function Login()
{
// Skiping conection code
$sql = "SELECT * FROM Usuario WHERE nombre = '$username' && password = '$password'";
$resultat = mysqli_query($connexio,$sql)or die(mysqli_error($connexio));
$usuaris = array();
while ($fila = mysqli_fetch_array($resultat))
{
$usuaris = $fila;
}
$_SESSION['ID'] = $usuaris['ID'];
$_SESSION['nombre'] = $usuaris['nombre'];
$_SESSION['admin'] = $usuaris['Admin'];
mysqli_close($connexio);
return $usuaris;
}
Thanks for the attention
Add following before session_start()
session_set_cookie_params(0, "/");
Related
I have this in my $_SESSION setting script:
<?php
//----------------------// Start session----------------------
if(!isset($_SESSION))
{
session_start();
}
//------------------------------------------------------------
//------------------// Check if Username $_SESSION is set------------------------------------------
if (!$_SESSION['Username']) { // If not current User
header("Location: ./logout.php"); // Session destroy file that leads to session logout landing page
exit();
}
//------------------------------------------------------------
?>
Now, what I basically do is just check if Username SESSION is set. But, I have come to notice something strange while putting another user through:
If we click the same link at the same time and arrive on the landing page same time, I noticed I can see my Username displayed as his Username and his personal data like email and phone replaced mine in my very own PC! This is really strange to me as we do not even live in the same country or even share same PC.
So, it is obvious I have not secured my SESSION and I have used a lame approach without thinking about security and this can be abused with SESSIONS hijacked.
How do I resolve this conflict? How do I restrict each logged in user to a particular session without conflicts if two or more users access the same resource at the very same time? I need help. I can't sleep since I found this.
After reading your responses, I will now show a snippet of the functions.php file which outputs Use data from DB.
First, I get the UserName value from session using:
$UserName = $_SESSION['Username'];
With this value, I query DB to get more user details:
//------------Get User Info -- All user column
$Get_User_Info = mysqli_query($conn,"SELECT * FROM customers WHERE User='$UserName'");
/************************************************************/
/************************************************************/
$Get_User_Info_row = mysqli_fetch_array($Get_User_Info,MYSQLI_ASSOC);
/************************************************************/
//---- Now list all user rows
$GLOBALS['Skype'] = $Get_User_Info_row['Skype'];
$GLOBALS['Jabber'] = $Get_User_Info_row['Jabber'];
$GLOBALS['ICQ'] = $Get_User_Info_row['ICQ'];
$GLOBALS['Join_Date'] = $Get_User_Info_row['Join_Date'];
$GLOBALS['Join_Date_Time'] = $Get_User_Info_row['Join_Date_Time'];
$GLOBALS['Balance'] = number_format($Get_User_Info_row['Balance'],2);
The above is what is contained in the functions.php which I require with each page I need protected.
As you can see, I barely see where I have done too much wrong there.
For a website, I need to route users to their own page. I have a login form, which sends data to a PHP file to check if the user's information is correct, and if so, forwarding the user to their page. The only problem is that I need to validate the user on arrival, to check if they logged in or just typed out the URL. I plan to use this with a POST, but how can I auto-send the constant (i.e. "logged-in")? Is there a way to do that through an HTML form (outputted from an echo) and sending it when the page loads? Thanks in advance!
EDIT 1: I understand that I must use Sessions, but whenever the page redirects it clears the session. The whole reason I was asking this was because I needed a way to keep the session active. How do I redirect in a way that doesn't clear the session?
In the PHP file that validates their credentials, start a "session". You can then apply session variables that can be called at any time while the session is valid. You can do this with POST, which is sounds like you're using, or by querying a database upon validation.
For example, upon validation:
session_start();
$_SESSION['username'] = $_POST['username'];
$security_check = mysql_query("SELECT * FROM userList WHERE username = '$username'");
$row = mysql_fetch_assoc($security_check);
$_SESSION['userId'] = $row['userId'];
$_SESSION['userFullName'] = $row['userFullName'];
On subsequent pages, you can put the following code at the top to check if the user logged in. If not, it will kick them back to the index page; otherwise the $_SESSION variables will be maintained.
<?php
session_start();
if (!isset($_SESSION['userId'])) {
echo "<script> window.location.replace('index.php?login=no') </script>";
}
?>
As suggested in the comments, I would recommend doing some further research on sessions to get a full understanding of how they work.
Basically I want to grab an id send via the url (ex. www.website.com/?id=432432) and take it accross my website till the user hits the contact page. I created a variable and a session variable
session_start();
$getId = $_GET["id"];
$_SESSION['session_browser_test'] = $getId;
$adv_id = $_SESSION['session_browser_test'];
and used
echo $adv_id;
on my index.php Joomla template so it applies to all the pages.
But the issue is when i go to www.website.com/?id=432432 it echos the id on my web page, but if I click on the next link to go to another page (ex. www.website.com/nextPage) it doesnt hold the session value from the previous page. Why is that? and how can I carry the ID through out the site?
you will not get an id from URL on next page, likely
echo $getId;
instead you need to use id from session like,
$_SESSION['session_browser_test']; // your id stored in session
Start the session in each page
session_start();
In order to access the variable in a session, you have to call the $_SESSION variable.
echo $_SESSION['session_browser_test'];
HTTP is stateless, so you have to do something to remember your variable throughout the website .
make sure you correctly use session , like session_start();
when you send your id through get method ,it works, but when you go to any other page ,it doesn't make any sense to remember this.
use this for send id through pages:
<?php echo get_permalink(910); ?>?userid=<?php echo $value['userId'];?>
send this in url and use on next page as:
$sql = "select * from `wp_pelleresuser` where userId =".$_GET['userid'];
using this approach you can use a single variable on every page you want without using session. try google to how wordpress manage variable through all pages without using session. it will help you.
happy coding!
Start
session_start();
(if not started) in the index.php in root of your app (session probably will start on every pages) and then call (when desired):
$_SESSION['session_browser_test'];
instead of assi8gning this sess var to your own variable and then calling it in different places.
if(isset($_GET["adv_id"])){
$_SESSION['session_browser_test2'] = $_GET["adv_id"];
$adv_id = $_SESSION['session_browser_test2'];
}
else {
$adv_id = $_SESSION['session_browser_test2'];
}
I am trying to redirect users to the page they were viewing before attempting to login. For example, if they were looking at baseurl/people/abraham_lincoln and then decided to log in, after they login they would be redirected to baseurl/people/abraham_lincoln. The weird thing is that it is working for some URLs and not others. For some URLs, I am getting "javascript/jsFunctions.js" appended as the URL instead of the URL they were previously on.
At the top of every controller, I set a session variable to do my redirect:
$this->session->set_userdata('Redirect', current_url());
I am printing this session variable to the top of my controller and at the top of my log in view for testing purposes. Here are a few results I am receiving when I go to my login.
An example of a URL that's working:
URL I attempt to log in from:
baseURL/people
What gets printed at the top of my controller as my Redirect session variable:
baseURL/people
What gets printed at the top of my log in view as my Redirect session variable:
baseURL/people
An example of a URL that's not working:
URL I attempt to log in from:
baseURL/people/abraham_lincoln
What gets printed at the top of my controller as my Redirect session variable:
baseURL/people/abraham_lincoln
What gets printed at the top of my log in view as my Redirect session variable:
baseURL/people/javascript/jsFunctions.js
I'm not sure if it matters, but I am also routing some of these URLs from the routes.php file:
$route['people/(:any)'] = "people/index/$1";
$route['people/(:any)/(:num)'] = "people/index/$1/$2";
I have tried to build my session variable many different ways, including:
current_url()
base_url().uri_string()
base_url().$this->uri->segment(1)....
base_url().$this->uri->rsegment(1)....
If anyone can think of why I'm getting those javascript variables instead of the URL I'm looking for I would appreciate any input.
Thanks!
P.S. I forgot to mention that if I refresh a page that isn't working, for example the abraham_lincoln page, and then go to login, I receive the correct Redirect session variable. Almost like it isn't getting set correctly the first time through, but don't know how I can solve this since I have tried setting the session variable both at the very top and right before the views are loaded.
the use case should only apply to the login process. thus putting this on the top of every controller would probably not what we want.
instead of putting current_url in session at the start, you should append it to the login link
<?php echo anchor('/home/login/' . url_encode(current_url()), 'login');?>
in the login function
<?php
public function login($redirecturl) {
$this->form_validation->set_rules('username', 'Username', 'required');
// etc.
if($this->form_validation->run()) {
$query = "select id from users where username=? and password=sha(?)";
// etc.
$this->session->set_userdata('userid', $row->id);
redirect($redirecturl);
} else {
$data['redirecturl']=$redirecturl;
$data['content']='loginview';
$this->load->view('template', $data);
}
}
?>
In the login view
<?php
echo form_open('/home/login/' . url_encode($redirecturl));
// etc.
?>
I am working on creating a website from scratch and am currently stuck with session stuff.. I know generally how sessions work and how to store things into $_SESSION after session_start() but my main problem is this. After clearing the cache and opening a new window, submitting a login request the FIRST time wont submit correctly and the page reloads and nothing has changed, but AFTER the first time, it works fine...
my login.php handles either a) the post request, or b) the login via url (for testing purposes) so a link to "user/login.php?username=facebook&method=get" would be sent to the code below and set the user to logged in with the name facebook..
<?php
session_start();
$method = $_GET['method'];
if($method == "get") $_SESSION['username'] = $_GET['username'];
else $_SESSION['username'] = $_POST['username'];
header('Location: http://www.imggroups.com');
?>
Im not sure if this matters, but, on the index page, I check to see if the user is logged in by doing this. starting session obviously, then doing. if(isset($_SESSION['username'])) echo whatever i need for logged in.. else echo whatever for not logged in.....
The issue is that you are redirecting the user to a new page, but the old page has not finished closing, so the session is not yet saved.
In order to fix this I usually setup an interum page which redirects to the correct page.
Alternatively you might be able to use session_write_close() (http://www.php.net/manual/en/function.session-write-close.php) before using the header redirect
The fact of the matter is, it is setting the session, BUT it's redirecting you to a different domain that the session isn't allowed on. If you access the website without the 'www.' in front then get redirected to the www version afterwards, then it's going to say your session doesn't exist. Use the following:
session_set_cookie_params(0, '/', ".imggroups.com");
Put it before your session_start() and it will work for both www and non-www versions of your site.
If that is the total of the login.php, I believe there is easier ways to do that:
If it does not matter whether the username actually comes in via _GET or _POST, then use _REQUEST as it encapsulates both.
if( isset($_POST['username'] ) {
$_SESSION['username'] = $_REQUEST['username'];
}
If it does matter, you don't have to trust or use an external parameter, just look at what's there:
if( isset($_POST['username'] ) {
$_SESSION['username'] = $_POST['username'];
} else if( isset($_GET['username'] ) {
$_SESSION['username'] = $_GET['username'];
} else {
// whinge
}
I've not run into that issue with PHP before, but you can also do a session_write_close(); to force it to write out the session before it redirects to the other page.
I also had this same issue if i open new window after logout in new tab or browser and try to log in login page stuck at loading i can see that session has been started because if i refresh on same stuck window i logged in to my dashboard.
But it was resolved later by redirecting it right:
Before
login.php (after ajax successful) --> index.php (if logged in) --> dashboard.php
After
login.php (after ajax successful) --> dashboard.php
hope it saves anybody's time & effort because i suffered alot!