I have a class named User which has a function named logout(). I create an instance of this class in index.php and i pass it's value to $_SESSION[usr] before i call memberspage.php . In memberspage.php i have a link named logout which when clicked i want the logout() function to run and also send the user to index.php. For this purpose i've done something like this.
Log out
I know that -> causes the problem but i don't know how to fix it. thnx for your time.
The following code worked for me
Log out
but there is a problem. If i go to the page(memberspage.php) where the above code is and i press the back arrow (not logout link) the logOut() function will still be used(the session is destroyed and i will have to log in again to access memberpage.php) . I don't get it because i thought that the only way to call the logOut() function was to click on Log out link.
If $_SESSION[usr]->logout() is working for you as you said in your comment. I don't know how.
But here is just for calling a php function inside anchor tag.It's totally depend on your function response.
<?php
function usr(){
return "abc";
}
?>
Log out
First i suggest that you change your use of session you can create a page for example session.php where all your session is place, it can also be the re directory page of your login page.
like this one named login.php
create in your form make action redirect to session.php
i also suggest that all your php codes of login are inside the session.php then make this one.
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$db = "mydb;
//database connection
$conn = mysqli_connect($host, $uname, $pass, $db);
mysqli_select_db($conn, $db);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysqli_real_escape_string($username);
//$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM table WHERE username = '" .$username. "' AND password = '".$password."' LIMIT 1";
$res = mysqli_query($conn, $sql);
if(mysqli_num_rows($res) > 0){
if($data = mysqli_fetch_assoc($res))
{
$_SESSION['type'] = $data['type'];
if(isset($_SESSION["login_user"]))
{
if($data['type'] == 'admin'){
header('location: admin.php');
}
else if($data['type'] == 'customer'){
header('location: customerhome.php');
}//header('location: uservalidation.php');
}
}
}
else{
//header('location: #');
echo '<script>';
echo 'alert("Invalid no?")';
echo '</script>';
header('location: logind.php');
}
}
?>
then create another page which is logout.php
put this code inside:
<?php
session_start();
header('location: index.php');
session_destroy();
?>
then save put the a link your page for logout.php
Add file logout.php and put into them your logout implementation:
<?php
header('Content-Type: application/json');
$_SESSION[usr]->logout();
echo json_encode(['message' => 'ok']);
And call this file with AJAX:
<script>
function logout() {
$.ajax({
url: '/logout.php'
}).then(function (res) {
window.location.href = '/';
});
}
</script>
Log out
Related
I will describe my problem in two parts (previous problem and current problem).
Previous Problem:
Initially, on page3.php, I wasn't able to retrieve the username using the session variable and hiding //require('../myDBFolder/db.php'); solved the problem and I was able to see the username on that page.
Current Problem:
Since, I have commented out the line //require('../myDBFolder/db.php');, I am not able to access the other variables defined in db.php like $connection variable and hence I am trying to figure out how to make sure I have $connection variable available in page3.php.
A Quick explanation of the working of files is in the following order:
User submits username from page1.html, page2.php does the authorization work with db.php as required file and upon successful authorization, it directs the user to page3.php.
Please consider my files below:
page1.html
<form method="post" action= "page2.php" name="lform">
<span class="style1">User Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
db.php
<?php
session_start();
$user = $_POST["user"];
$_SESSION['username']=$user;
$db_server = "localhost";
$db_name = "PracticeDB";
$db_user = $user;
$table_name_data = "collegestudents";
$connection = mysqli_connect($db_server,$db_user,$db_password) or trigger_error("Could Not Connect to the Database : ". mysqli_connect_error(), E_USER_ERROR);
$db = mysqli_select_db($connection , $db_name) or trigger_error("Could Not Select the Database : " . $db_name . ':' .mysqli_error($connection));
?>
page2.php
<?php
session_start();
require('../myDBFolder/db.php');
$user = $_POST["user"];
$_SESSION['username'] = $user;
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
$result=mysqli_query($connection,$sql) or trigger_error("Couldn't Execute Query in page2.php: ". mysqli_error($sql));
$num = mysqli_num_rows($result);
if ($num != 0) {
print "<script>";
print "self.location='page3.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
page3.php
<?php
session_start();
//require('../myDBFolder/db.php');
$user = $_SESSION['username'];
$sql = "SELECT * FROM $table_name_data WHERE username = '$user'";
$result = mysqli_query($connection,$sql) or trigger_error("Could Not Execute the Query ! : ". mysqli_error($connection));
?>
Troubleshooting Steps:
1) I have tried to include require('../myDBFolder/db.php'); in page3.php file and it solves the problem of $connection parameter but I don't see username coming onto that page via session for some reason and also by including //require('../myDBFolder/db.php'); in page3.php I will be making db connection twice as I have already done that in page2.php and haven't closed it.
2) Another thing, I was looking at some of the threads discussed before like this one, it seems like storing $connection in a session variable is not a good idea.
Just to point in a direction:
Change this
$user = $_POST["user"];
$_SESSION['username'] = $user;
to
if(isset($_POST["user"])){
$user = $_POST["user"];
$_SESSION['username'] = $user;
}
So, only update the SESSION if POST is given.
By the way, it is not good practise to give each user an db user account.
Your SQL check if a user is in the database, but your connectin also uses this username!? Rething that..
If you only use one db_user you can move the session username setting stuff completly from the db.php and move it to a better place (e.g. session.php).
the error of you dont see the username if you require db.php is :
in your db.php first thing to do is to put the username in the session so when you call it from the page3 you the code put blank in the session
this code
$user = $_POST["user"];
$_SESSION['username'] = $user;
There is two solution for that :
1 - put connection in one file and the session put in the other file
$user = $_POST["user"];
$_SESSION['username'] = $user;
in different file of connection
2 - the second is you put if condition before this code like this
if(!empty($_POST["user"])) {
$user = $_POST["user"];
$_SESSION['username'] = $user;
}
try it .
I am having problems with my code. This is a login/register script I've made by following a tutorial.
The problem I have is that I want the script to echo "logged in" ONLY when the user has entered correct login details, and yet it still echoes "logged in" even if I don't enter any login details. I checked it and if I delete the "session_start()" function, it doesn't do the same thing, but it still doesn't give me access to the session when I want to login.
This is the init.php file, used to initiate the connection with the database and define some other functions:
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
This is the connect.php file, used to connect to the database :
<?php
$connect_error = 'Sorry, we are experiencing connection issues. This will be solved as soon as possible.';
$con=mysqli_connect("localhost","root","","lr") or die ($connect_error);
mysqli_select_db($con,'lr') or die($connect_error);
mysqli_close($con);
?>
The general.php file is not important for this question.
This is the users.php file, where I keep some other functions.
function user_id_from_username ($username){
$username = sanitise($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
while($row=$result->fetch_row()){
if ($row[1]==$username){ //username == $username
return $row[0];//user_id;
}
}
}
function login ($username, $password){
$user_id= user_id_from_username($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$username = sanitise($username);
$password =md5 ($password);
$query = "SELECT * FROM users";
$result = $mysqli -> query($query);
while ($row =$result -> fetch_row()){
if($row[1]==$username && $row[2]==$password){
return TRUE;
}else {
return FALSE;
}
}
}
This is the file that calls the login function, presented above:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) ===TRUE || empty ($password) === TRUE) {
$errors[]='You need to enter a username and password!';
} else if (user_exists($username) ===FALSE) {
$errors[]="We can't find that username, have you registered?";
} else if (user_active($username)===FALSE){
$errors[]="You have not activated your account!";
} else{
$login = login($username, $password);
session_start();
if ($login ==false) {
$errors[] ='That username/password combination is incorrect!';
}else if ($login==true) {
//set the user session
$_SESSION['username'] = $login;
//redirect user to homepage
header('Location: index.php');
exit();
}
}
if ($errors){
print_r($errors);
}
}
?>
And now the index.php file, in which I have the if statement that echoes 'logged in' even if I am not logged in :
<?php
if (empty($_SESSION['username'])) {
echo 'not logged_in';
}else {
echo 'logged in';
}
?>
Now I think the problem is located somewhere either in the users.php, login.php or in the index.php file. I presented all of the files so you could get an idea of what I am trying to achieve. This code is spread over so many files because I have functions and interfaces that I have included and I want to be able to reuse the code, so I am using includes.
For you to get a better idea, if my files did not help you enough, I will leave the Youtube link of the tutorial I am following :
https://www.youtube.com/watch?v=JUk2e8oqOvI&list=PLE134D877783367C7&index=7#t=6.296979
Thank you,
Waiting for your answer,
Best regards,
If you don't use $_GET requests to include the pages, you need to put session_start() on top of each file where you are using the $_SESSION variable otherwise you can't use the sessions.
<?php
session_start();
// Rest of your script
I hope this will help you.
Please help me. I got this error everytime I tried to login. - "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Please help me and I'll appreciate your help very much. thanks.
This is my index.php
<?php
include('login.php'); // Includes Login Script
?>
This is my login.php
<?php
session_start();
$error = "";
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$usernameLogin = $_POST['email'];
$passwordLogin = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "apple", "Apple318992");
// To protect MySQL injection for Security purpose
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("TS", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from Users where password='$password' AND email='$usernameLogin'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user'] = $usernameLogin; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
}
if (isset($_SESSION["login_user"])) {
header("Location:timesheets.php");
}
?>
This is my session.php
<?php
include ('DBConnect.php');
session_start(); // Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select email from Users where email='$user_check'", $conn);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['email'];
if (!isset($login_session)) {
mysql_close($conn); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
instead of : header('Location: index.php');
try to do it with javascript :
echo '< script> document.location.href="index.php"< /script>';
In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
unset(); for all the session variables unset($_SESSION['login_user']); for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session_start(); should be at very first line in your php file if I am correct, or it throws error.
I wrote custom login script for users to login to the main control page. I found out that even when users are not login they can still visit the main control of which I want someone to help me to write a restrict access to page().
Please look through my php login script and based on that code help me write the restrict access to the main control page. assume that my main crontrol page is: cecontrolpage.php
I know we use $_SESSION to that but I have little idea of it.
this is my login.php code which is working fine:
<?php
Session_start();
$Email = $_POST["email"];
$Password = $_POST["password"];
$cn = "localhost";
$db_username = "root";
$pas = "***";
$db_name = "cemembers";
//Open a connection to a MySQL Server
if ($Email && $Password) {
$connect = mysqli_connect($cn, $db_username, $pas, $db_name) or die("Could not connect to database");
//sending MySqli query
$query = mysqli_query($connect, "SELECT * FROM users WHERE Email= '$Email'");
$numrows = mysqli_num_rows($query);
//After PHP declaration we are going to create index file[form]
if ($numrows !== 0) {
while ($row = mysqli_fetch_array($query)) {
$dbEmail = $row["Email"];
$dbPassword = $row["Password"];
}
if ($Email == $dbEmail && $Password == $dbPassword) {
header("location:ce membership birthday system control_pannel.php");
#$_SESSION("Email") == $Email;
} else
header("location:index.php?login_attempt=1");
} else
header("location:index.php?login_attempt=2");
} else
header("Location:index.php?login_attempt=0");
?>
please can someone help me write the php code to restrict access to cecontrol.php ??
Please STEP by STEP with php comments on each part.
First you need to check if the user is logged in:
you do that by checking if the session has been set.
//Check if the user is logged in
function userlogged_in()
{
return(isset($_SESSION['userid']))?true:false;
}
Then you need to redirect the user to a page that says the access to is not authorised, they need to be logged in to view that page:
You do this by checking if the userlogged_in function returned a true or false
function user_restricted()
{
if (userlogged_in()=== false)
{
header('Location: permission.php ');
exit();
}
}
Then you need to call the user_restricted() function on each page, just after starting the session.
First you have to save user values in session after authentication from database like
$_SESSION['username'] = "name"; $_SESSION['user_id'] = 1;
function check_session() {
session_start();
if ($_SESSION['user_id']=='')
{
// redirect to login
}
}
On every page that you want to restrict access you can call check_session().
I haven't been able to trace what's wrong with this code. I am trying to login the user by taking his username and password. Here is what I am trying to do.
index.php:
This file checks if the username cookie is set and displays the file accordingly. This file submits the username and password to a file called validate.php.
validate.php:
<?php
session_start();
include("connector.php");
$var=connect();
if($var==10)
{
$valid=false;
$row= mysql_query('select * from users where username="'.$_POST["username"].'"');
if($row['password']==$_POST["password"])
$valid=true;
if($valid)
{
$_SESSION["username"]=$_POST["username"];
$_SESSION["userid"]=$row['userid'];
echo "<script>document.location.href='./session_creator.php'</script>";
}
else
{
echo "invalid";
}
}
?>
connector.php==>
<?php
$connection=0;
function connect()
{
$dbc = mysql_connect('localhost:3306','root','root');
if (!$dbc)
{
die ('Not connected:'. mysql_error());
return -10;
}
else
{
$connection = mysql_select_db("citizennet",$dbc);
if(!$connection)
{
die("Not connected: ". mysql_error());
return -20;
}
}
return 10;
}
?>
session_creator.php:
<?php
session_start();
setcookie("username",$_SESSION['username'],time()+3600);
setcookie("userid",$_SESSION['userid'],time()+3600);
echo "<script>document.location.href='./index.php'</script>";
?>
the redirected index.php file reports that the cookie is not set. I am newbie, please correct me if the process I am following is wrong.
I am adding index.php that verifies if the user is logged in:
<?php
if(!isset($_COOKIE["username"]))
echo '<a id="login_button">login</a> <div id="login_box_pane"><form action=validate.php method="post">Username: <input type="text"/> Password:<input type="password"/><input type="submit"/></form></div>';
else
echo "<a>".$_COOKIE["username"]."</a>";
?>
When you set your cookie on your page it should be like this:
<?php //login page
session_start()
$username = $_POST['username'];
$password = $_POST['password'];
/*
Check authentication with database values
*/
//if login successful set whatever session vars you want and create cookie
$_SESSION['username'] = $username;
setcookie($username, $password, time()+3600);
?>
Prior to this you will have check the users credentials and log them in or deny them. Once logged in you set the session variables. Then to create the cookie you use the code above.
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
That will take care of your sql injection vulnerabilities and also get you the correct account only if both the username and password are correct
Now you can use your conditions to set the cookies and sessions