solving problems in session? [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have created two pages , one is index.php and admin.php . In the first page or index.php , i have created a loggin form so that i can access the admin.php page trough the loggin or like this enter image description here
Now by logging in i go to admin.php page. Here is the question what i want to ask about that now when ever i click the back button or next button in the chrome. I am returning to the admin.php page . I have tryed the session_start() and the if(!isset($password) || !isset($user)){}. But this code for obvious reasons doesnt work . So can someone help me out with this ?
The code for the example is here index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Admin</title>
</head>
<body>
Reset
<div class="image">
<img src="img/adi.png" alt="image"> <!-- image -->
</div>
<form action="inc/login.php" method="POST"><br>
<p class="title">Log In</p>
<label for="Username">User :</label>
<input type="text" name="username" id="user"> <br> <!--username -->
<label for="Password">Password :</label>
<input type="password" name="password" id="password" ><br><br> <!-- password -->
<label for="showpassword" class="showpassword">Show Password</label>
<input type="checkbox" name="checkbox" id="chk" ><br><br> <!-- checkbox -->
<input type="submit" name="submit" value="Log in" > <!-- enter -->
</form>
<?php
if(!isset($_GET['Login'])){
exit();
}else{
$check=$_GET['Login'];
if($check=="userEmpty"){
echo "<p class='class_login'>user is empty</p> ";
}elseif($check=="passwordEmpty"){
echo "<p class='class_login'>password is empty</p> ";
}elseif($check=="wrongUser"){
echo "<p class='class_login'>user is wrong</p> ";
}elseif($check=="Password"){
echo "<p class='class_login'>password is wrong</p> ";
};
} ;
?>
<script src="js/main.js"></script>
</body>
</html>
and the code for the admin.php is this one :
<?php
session_start();
if(!isset($username) || !isset($password)){
header("location:index.php?data=closed");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
window.history.forward();
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="top">
Log Out
</div>
</body>
</html>

Besides using of session_start you need to store something in the session, using something like this:
$_SESSION['userId'] = <value>;
which must be set in your login.php and checked by your admin.php if user has access rigths to visit secured page. I.e. you need to check:
if (isset($_SESSION['userId']) && $_SESSION['userId'] == <value>) {
// access granted
}

Related

PHP Form does not log in and move to next page

I ran into another problem with my website that I can't get around.
I'm trying to make it so when the admin logs in he will be taken to the admin page but for some reason when I enter the correct details into the log in and press the submit button it just brings me back to the admin log in page again.
Here is a Gyazo of my problem
https://gyazo.com/34f133fea4b20ec285ee7ff491053145
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<title>Login</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<link href='https://fonts.googleapis.com/css?family=Ubuntu:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/148866/reset.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<body>
<main id="cd-main-content">
<section id="cd-intro">
<h1>Admin Log In</h1>
<header class="cd-header">
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$adminusername = stripslashes($_REQUEST['adminusername']);
//escapes special characters in a string
$adminusername = mysqli_real_escape_string($con,$adminusername);
$adminpassword = stripslashes($_REQUEST['adminpassword']);
$adminpassword = mysqli_real_escape_string($con,$adminpassword);
//Checking is user existing in the database or not
$query = "SELECT * FROM `admin` WHERE username='$adminusername'
and password='".md5($adminpassword)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $adminusername;
// Redirect user to admin page /////////////////////////////////////////////////////////////////////
header("Location: adminpage.php");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='admin.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<form action="" method="post" name="login">
<input type="text" name="adminusername" placeholder="Username" required />
<input type="password" name="adminpassword" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
<a class="cd-menu-trigger" href="#main-nav">Menu<span></span></a>
</header>
<div class="cd-blurred-bg"></div>
</section> <!-- cd-intro -->
</main>
<div class="cd-shadow-layer"></div>
<nav id="main-nav">
<ul>
<li><span>Login</span></li>
<li><span>What's On</span></li>
<li><span>Favourites</span></li>
<li><span>About</span></li>
<li><span>Admin</span></li>
</ul>
Close<span></span>
</nav>
</body>
<script src='js/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
You are doing:
if (isset($_POST['username'])) {
//...
}
Try this
if (isset($_POST['adminusername'])) {
//...
}
As a note, I suggest you to try use a framework, like laravel.
first I would debug by var_dump($_POST) and see what you get. I would bet that since you dont have an ID set for the input value name it is not working. If anything checking for ISSET($_POST['username']) would never work because you do not have a vairable set for that name.
var_dump($_POST) and see what you get. If not add an ID='username' to the input
try this :-
if (isset($_POST['submit'])){
// rest of code...
}

How can ask login if it write on url

index.php
<?php session_start(); ?>
<?php include('dbcon.php'); ?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="form-wrapper">
<form action="#" method="post">
<h3>Login here</h3>
<div class="form-item">
<input type="text" name="user" required="required" placeholder="Username" autofocus required></input>
</div>
<div class="form-item">
<input type="password" name="pass" required="required" placeholder="Password" required></input>
</div>
<div class="button-panel">
<input type="submit" class="button" title="Log In" name="login" value="Login"></input>
</div>
</form>
<?php
if (isset($_POST['login']))
{
$username = mysqli_real_escape_string($con, $_POST['user']);
$password = mysqli_real_escape_string($con, $_POST['pass']);
$query = mysqli_query($con, "SELECT * FROM users WHERE password='$password' and username='$username'");
$row = mysqli_fetch_array($query);
$num_row = mysqli_num_rows($query);
if ($num_row > 0)
{
$_SESSION['user_id']=$row['user_id'];
header('location:home.php');
}
else
{
echo 'Invalid Username and Password Combination';
}
}
?>
</div>
</body>
</html>
Here is my page for login the system. When the username and password is then it will go to home pages. It work properly. but if I write in browser after log out.
localhost/logg/home.php it is automatically go to that pages it not asking for login. So How to make proper login page where it asking log or automatically it will go login panned for all the pages is that is connected with home page.
home.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Client Management System</title>
<link rel="stylesheet" type="text/css" href="css/style_entry.css" />
<link rel="stylesheet" type="text/css" href="css/home_menu.css" />
<link rel="stylesheet" type="text/css" href="css/container.css" />
</head>
<body style="background-color:gray"/>
<div class="container">
<div class="dropdown">
<button class="dropbtn">Entry</button>
<div class="dropdown-content">
Market Information
bank Information
Client Information
</div>
</div>
Edit
Bill Process
Bill Print
Bill Posting
Report
Admin
Help
Help
<li style="float:right"><a class="active" href="logout.php">Logout</a></li>
</body>
logout.php
<?php
session_start();
session_destroy();
header('location:index.php');
?>
How can I secure it ?? how can I set if I write the url in browser then it will automatically go to the login page.
1st : On top of every page you need to check session is exists or not . if session exists allow user to see the page otherwise redirect the page to login page .
if(!isset($_SESSION['user_id'])){
header('Location:login.php');
exit();
}
Note : Session is globally accessible variable . Based on that you need to make logic .
make a file 'login_check.php'
<?php
if(isset($_SESSION['user_id'])){
}else{
header("location:login.php");
}
?>
include this file in those pages which should only be accessible to logged in user.

passing id on href and submitting form on same page

I am making social project form and im trying to add reply ..the reply button is a link that sends user to reply.php page with post id saved in href...on the reply.php my form action is the same page but when i click button to submit form it doesnot get the id and refreshes page with post and display error undefined id need help..
here is my reply.php
<?php
require('session.php');
$id=$_GET['id'];
//echo $id;
$submit=#$_POST['submit'];
$reply=#$_POST['reply'];
if(isset($submit)){
$id=#$_GET['id'];
$sql=mysqli_query($con,"INSERT INTO REPLY (reply,Username,post_id) VALUES '$reply','$user_check','$id'");
$sql2=mysqli_query($con,"SELECT * FROM REPLY WHERE post_id= '$id'");
while($row=mysqli_fetch_array($sql2)){
echo $row['Username']."<br/>".$row['reply']."<br/>";
}
}
else "error in submission";
?>
<!DOCTYPE html>
<html>
<title>Studhelp</title>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<?php
$sql=mysqli_query($con,"select * from posts where post_id='$id'");
while($row=mysqli_fetch_array($sql)){?>
<!-- Middle Column -->
<div class="w3-col m7">
<div class="w3-row-padding">
<div class="w3-col m12">
<div class="w3-card-2 w3-round w3-white">
<div class="w3-container w3-padding">
<h3 class="w3-opacity"><?php echo $row['Username'] ;?></h3>
<?php
echo $row['Posts']."<br/>".$row['date']."<br/>";
}
?>
</p>
</div>
</div>
</div>
</div>
<form action="reply.php" method="post">
<input type="text" name="reply" >
<input type="submit" name="submit" value="reply">
</form>
this is the anchor tag send id to reply.php
Reply
If I understand correct you need to be able to read your "id" variable after you post the form. To achieve this use $_REQUEST instead of $_GET, like this:
$id = $_REQUEST['id'];
And also pass the variable with your form, as a hidden field:
<form action="reply.php" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="reply" />
<input type="submit" name="submit" value="reply" />
</form>
You didn't check if the fom was submitted
Enclose other PHP code after session.php inside a conditional checker such as:
if ($_POST):
You can use form tags to create a form and put the id field as hidden.
GET requests shouldn't be use to modify data

Cannot Modify Header Information Session Cookie Create? [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
Firstly I like to say this is not a duplicate I tried everything on google such as ob_functions and space not luck
PHP should of made this simple but they haven't which is stupid..
Why am I getting this error for just starting a cookie in my script?
I have commented the cookie start I am having the issue with and hope someone can help fix it
I tried and now gave up wasting my time..
<!DOCTYPE html>
<?php
session_start();
?>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<title>Welcome To Spud Gaming</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- CSS -->
<link rel='stylesheet' href='http://fonts.googleapis.com/css?family=PT+Sans:400,700'>
<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/supersized.css?vvssv">
<link rel="stylesheet" href="assets/css/style.css?v12">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<?php
require "../core/links.php";
if(isset($_SESSION['user'])) {
die;
}
if(isset($_COOKIE['user'])) {
die;
}
?>
<div class="page-container">
<br><br><br>
<h1>Sign In</h1>
<div style='color:black;'>
<?php
if((isset($_POST['username'])) && (isset($_POST['password']))) {
require "../core/data_connect.php";
$username = mysqli_real_escape_string($connection,$_POST['username']);
$password = mysqli_real_escape_string($connection,(sha1(md5($_POST['password']))));
if(($username) && ($password)){
$login_query_string = "SELECT * FROM spud_members WHERE ( username='$username' OR email = '$username') and password='$password'";
$login_query = mysqli_query($connection,$login_query_string);
$login_rows = mysqli_num_rows($login_query);
$login_array = mysqli_fetch_array($login_query);
$mid_login = $login_array['mid'];
$active_login = $login_array['active'];
//if we found a user with that information then sign them in
if($login_rows==1) {
//if the user as not been suspended then start there session
if($active_login==1) {
//if the user has not checked the remember me box
if($_POST['start_cookie_true_checked']!='on') {
$_SESSION['user']=$mid_login;
die;
} else if($_POST['start_cookie_true_checked']=='on') {
//otherwise if the remember me box has been checked then start a cookie instead
$date_of_expiry = time() + 60 ;
//THIS COOKIE HAS A ISSUE AND POPS UP THESE ERRORS!!!!!!!!!!!!!!!!!!!!!!!!!
setcookie("user", 'Mark', time()+3600);
die;
}
} else {
echo "<b>Account Suspended</b><br>
Your Account Has Been Suspended:<br>
This May Be Because You Have Broken Our Terms Of Use Guidelines<br><br>";
}
} else {
echo "<b>Invalid Username/Email Or Password</b><br>
The Username/Email Or Password That You Supplied Is Invalid<br>
Please Try Again or <a href=''> Reset Your Password</a>";
}
} else {
echo "<b>Blank Username/Email And Password</b><br>
You Haven't Entered A Username/Email And Password";
}
}
?>
</div>
<form action='' method='post'>
<input type='text' name='username' placeholder='Username Or Email' size='25' maxlength='30' /><br />
<input type='password' name='password' placeholder='Password' size='25' />
<input type='checkbox' name='start_cookie_true_checked'>
<input type='hidden' name='action' value='do_login'>
<input type='hidden' name='url' value='index.php' /> <br><br>
<style>
a {
color:blue;
text-decoration:none;
}
</style>
<div>
<a href='signup'> Need An Account? </a> | <a href='forgot'> Forgot Password?</a>
</div>
<button type="submit">Sign In</button>
</form>
</div>
<!-- Javascript -->
<script src="assets/js/jquery-1.8.2.min.js"></script>
<script src="assets/js/supersized.3.2.7.min.js"></script>
<script src="assets/js/supersized-init.js?ddsddfd"></script>
<script src="assets/js/scripts.js"></script>
</body>
</html>
Thanks :)
Move HTML outpout after to session_start function.
<?php
session_start();
?>
<!DOCTYPE html>
You can't try to set a cookie (which is done in response headers) after you have started to make output to the page (which starts on your first line of code).

Can't register variable session (I've search, but nothing help me :( [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I've got a problem to register variable session. I've ordered my code with MVC (View=Vue in french) modele. Like this :
My problem : Index.php include all of others files, so I put the 'session_start();' here. (Anyway I can't put it on other place without taking error log "session has already started")
Firstly index.php 'open' connexion.php, with connexion form for user. When he submit it, my controleur look if it's good, and redirect user to the Accueil.
I would like to register variable 'user' on my controler, but this doesn't work anymore.
My code :
Index.php
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="fr" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="Style/style.css" type="text/css" />
<title>Saisie des temps</title>
</head>
<body>
<div id=page>
<?php
include_once 'Vues/Header.php';
?>
<div id=corps>
<?php
include_once 'Vues/Menu.php';
if (!empty($_GET['page']) &&
is_file('Controleurs/'.$_GET['page'].'.php')){
include_once (dirname(__FILE__).'../../SaisieTemps/Controleurs/'.$_GET['page'].'.php');
}
else{
include_once (dirname(__FILE__).'../../SaisieTemps/Controleurs/GestionConnexion/connexion.php');
}
?>
</div>
<?php
include_once 'Vues/Footer.php';
?>
</div>
</body>
</html>
Controler : COnnexion.php
<?php $_SESSION['test']='test'; ==> WORKS BUT TO EARLY ^^
//Inclusion modele
include(dirname(__FILE__).'/../../Modeles/GestionConnexion/Connexion.php');
$login = isset($_POST['username'])?$_POST['username']:'';
$password = isset($_POST['password'])?$_POST['password']:'';
if(isset($_POST['submit'])){
$intError = verifConnexion($login, $password);
switch ($intError){
case 0:
//Connexion OK
$_SESSION['login']=$login; ==> DOESN'T WORK
?><script type="text/javascript">
document.location.href = '../../../SaisieTemps/index.php?page=GestionConnexion/Accueil';
</script><?php
break;
case 1:
//Pb mdp
?><script type="text/javascript">
document.location.href = '../../../SaisieTemps/index.php?page=GestionConnexion/Connexion.php&Error=1';
</script><?php
break;
case 2:
//Pb login
?><script type="text/javascript">
document.location.href = '../../../SaisieTemps/index.php?page=GestionConnexion/Connexion.php&Error=2';
</script><?php
break;
default:
?><script type="text/javascript">
document.location.href = '../../../SaisieTemps/index.php?page=GestionConnexion/Connexion.php&Error=3';
</script><?php
break;
}
}
else{
//Inclusion vue
include(dirname(__FILE__).'/../../Vues/GestionConnexion/Connexion.php');
}
View:Connexion.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<div id=contenu>
<form action="../../SaisieTemps/Controleurs/GestionConnexion/Connexion.php" method="POST" id=login>
<h1>Connexion</h1>
<fieldset id="inputs">
<label for="username">Identifiant : </label>
<input id="username" name="username" type="text"
placeholder="Identifiant" autofocus required/><br/>
<label for="password">Mot de passe : </label>
<input id="password" name="password" type="password"
placeholder="Mot de passe"required/>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="Connexion" name="submit">
</fieldset>
</form>
<label class="errorLabel"><?php
if(isset($_GET['Error'])){
switch ($_GET['Error']){
case 1:
echo'Mauvais mot de passe';
break;
case 2:
print'Le login n\'existe pas';
break;
}
}?>
</label>
</div>
Thank's for your help, and sorry for my bad english
In your login form action is direct to PHP file (to Controller) not via index.php
And in Controler : COnnexion.php session not started.
Change logic of your application or add session_start() to this controller
Remove the whitespace before you php code. It is not allowed to put input before the session_start(); a space or a tab is also seen as content.

Categories