Session php Dont work - php

I built an Admin-login using sessions, however it doesn't work, it requests me to login again. It does not recognize the session.
What's wrong?
<!DOCTYPE HTML>
<html>
<head>
<?php
session_start();
include "../header.php";
echo $_SESSION['username'];
?>
<title></title>
</head>
<body dir="rtl">
<?php if(!isset($_SESSION['username'])) { ?>
<h1>כניסה לפאנל ניהול</h1>
<form action="index.php" method="post">
<input name="adminName" placeholder="שם משתמש">
<br>
<input name="adminPass" placeholder="סיסמה">
<br>
<input type="submit" name="login" value="כניסה" class="btn btn-primary">
</form>
<br>
<?php
$username = $_POST['adminName'];
$password = $_POST['adminPass'];
if(isset($_POST['login'])) {
$connect_db = mysql_connect("X", "X", "X");
$select_db = mysql_select_db("X");
$login_query = mysql_query("SELECT * FROM `X`.`admin_login` WHERE `Username` = '$username' and `Password` = '$password';");
$login_num = mysql_num_rows($login_query);
if($login_num == 1) {
$da = mysql_query("SELECT * FROM `X`.`admin_login` WHERE `Username` = '".$_SESSION['username']."'");
while($row = mysql_fetch_array($da)) {
$_SESSION['username'] = $username;
$_SESSION['name'] = $row['Name'];
$_SESSION['date'] = $row['Date'];
}
echo '<div class="alert alert-success">
<strong>הצלחה!</strong> התחברת בהצלחה לפנאל ניהול! רענן
</div>';
}
else {
echo '<div class="alert alert-warning">
<strong>שגיאה:</strong> שם המשתמש או הסיסמה אינם נכונים
</div>';
}
}
}
else if(isset($_SESSION['username'])) {
echo 'ברוך הבא, '.$_SESSION['username'];
}
?>
<br>
</body>
</html>

You need to put session_start() before anything that produces output. So change the beginning of the script to:
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<?php
include "../header.php";
See How to fix "Headers already sent" error in PHP

Related

php is not showing the else-block

i'm trying to learn about session_start() but when i run the file, it only show what is inside the
if (isset($_SESSION['username'])&& isset($_SESSION['password'])==$password) {
?>
log out
<?php } ?>
and not showing else{...} and even after i click log out, it won't print anything in else statement and only print inside the if statement. I use another file to do the log out proses but i don't know the right code for session_destroy()
here's the logout.php code below:
<?php
session_start();
session_destroy();
header("location: home.php");
?>
here's the full code:
<?php
session_start();
include("DB/db.php");
$_SESSION['username']=$username;
$_SESSION['password']=$password;
$_SESSION['is_log_in'] = true;
?><!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/css.css">
</head>
<body>
<div id="blank"></div>
<div id="panel">
<nav id="bar">
<div id="submen">
<form id="sir">
<input type="Search" name="search" placeholder="Search.." id="search">
</form>
Walpaper
Art
Photos
Image
<?php
if (isset($_SESSION['username'])&& isset($_SESSION['password'])==$password) {?>
<?php echo $username?>
log out
</div>
</nav>
</div>
</table>
<?php } else {
?>
login
register
</div>
</nav>
</div>
</table>
<?php } ?>
</body>
</html>
UPDATE for log in script
<?php
session_start();
include("DB/db.php");
if ($_GET['log']=='out'){
session_destroy();
}
if ($_POST['user']){
$sql = "Select password from user where username = '".$_POST['user']."' ";
$result = mysqli_query($koneksi, $sql);
if (mysqli_num_rows($result)){
$row = mysqli_fetch_assoc($result);
if ($row['password'] == md5($_POST['pass'])) {
$_SESSION['login'] = TRUE;
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
}else{
$pesan = "Username and password mismatch";
}
}else{
$pesan = "please register";
}
}
?><!DOCTYPE html>
<html>
<head>
<title>Log in</title>
</head>
<body>
<?php
if ($_SESSION['login']) {
echo "text";
}else{
?>
<h1>Login</h1>
<form method="post" action="rahasia.php">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" name="" value="Login">
</form>
<form method="post" action="register.php">
<input type="submit" name="register" value="register">
</form>
<?php
}
echo $pesan;
?>
</body>
</html>
where have i gone wrong
Your $_SESSION vars are always set, and $password always equals $_SESSION['password'].
$_SESSION['username']=$username; // null, plus notice in error_log
$_SESSION['password']=$password; // null, plus notice in error_log
Unless those two vars are set in include("DB/db.php");, in which case that is bad practice. Can you paste db.php to see what is happening inside?
UPDATE.
Okay so the vars are being set. This now means:
$_SESSION['username']=$username; // a
$_SESSION['password']=$password; // 123456789
Therefore they will still match. You need to refactor these lines to function properly. Are you sure the mysql credentials is what you want for your logged in user
?

Undefined index in session

I have 2 pages:
index.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="wrapper">
<h1>Welcome to the Great Number Game!</h1>
<h3>I am thinking of a number between 1 and 100</h3>
<h3>Take a guess!</h3>
<?php
echo $_SESSION['message'];
?>
<form method="post" action="process.php">
<input type="hidden" name="action" value="guess">
<input type="text" name="number">
<br>
<input type="submit" value="Submit">
</form>
</div>
</div>
</form>
</body>
</html>
and process.php
<?php session_start(); ?>
<?php header('Location: index.php'); ?>
<?php
if (!isset($_SESSION["message"])) {
$_SESSION["message"] = "";
}
if(!isset($_SESSION['num'])) {
$_SESSION['num'] = rand(1, 100);
}
$new_game = "<a href='logout.php'><button class='btn'>Play again</button></a>";
if ($_POST['number']) {
$number = $_POST['number'];
if (is_numeric($_POST['number'])) {
if ($number > $_SESSION['num']) {
$_SESSION['message'] = "<div class='bad-guess'>Too high!</div>";
}elseif ($number < $_SESSION['num']) {
$_SESSION['message'] = "<div class='bad-guess'>Too low!</div>";
}else{
$_SESSION['message'] = "<div class='lucky-guess'>Congratulations! ".$_POST['number']." was the number!</div><br>".$new_game;
}
}else{
$_SESSION['message'] = "<div> <b>'$number'</b> is not a number. Please insert a number!</div>";
}
}
?>
Problem is that then I am starting session, I got the error that my $_SESSION['message'] index is undefined. Then I start guessing number, I got correct messages. So how can I define $_SESSION['message'] for sessions beggining?
in your index.php page
Put this
echo $_SESSION['message'] != '' ? $_SESSION['message'] : 'No messages';
Check if it is set first in index.php
if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
}

PHP user login: Limit to one simultaneous session per user id

When a user logs in, how can I check whether another person is logged in already with the same username and display an error such as "This user is already logged in"?
LogIn_form.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<link rel="stylesheet" href="NewFile.css">
</head>
<body>
<div id=warper>
<?php include 'Menu.php'; ?>
<div class="box">
<form method="POST" id="formReg">
<div id="account">
<div id="accountN">Account:</div>
<div id="accountV"><input type="text" name="account"></div>
</div>
<div id="pass">
<div id="passN">Password:</div>
<div id="passV"><input type="password" name="password"></div>
</div>
<input type="submit" value="submit" name="submit">
<?php
if (isset ($_POST ['submit'])) {
include 'LogIn_database.php';
}
?>
</form>
</div>
</div>
</body>
</html>
LogIn_database.php
<?php
session_start();
$username = htmlspecialchars($_POST ['account'], ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars($_POST ['password'], ENT_QUOTES, 'UTF-8');
$password_sha1 = sha1($password);
if ($username && $password_sha1) {
//-------------------------------------------------------------------------------------------------------------
include 'MySQL_connect.php';
//------------------------------------------------------------------------------------------------------------------
$query = mysqli_query($conn, "SELECT * FROM portofoliu_table WHERE account= '$username' ");
$numrows = mysqli_num_rows($query);
if ($numrows != 0) {
while ($row = mysqli_fetch_assoc($query)) {
$db_account = $row['account'];
$db_password = $row['password'];
}
if ($username == $db_account && $password_sha1 == $db_password) {
#$_SESSION['account'] = $username;
$_SESSION["logged"] = true;
header("location: AboutMe.php");
exit();
} else
echo "<div id='err'>Your password is incorrected</div>";
$_SESSION["logged"] = false;
exit();
} else
die("<div id='err'>That user don't exists</div>");
} else
die("<div id='err'>Please enter a username and password</div>");
Logout.php
<?php
session_start();
session_destroy();
header("location: AboutMe.php");
?>

Not showing the greeting message

I was working on my login - register system when i realized i made a problem yet i don't know what it :/
In the index.php page the header should show a welcome guest and link to the login and register page ... and if the gust login show Welcome $username for example.
Yet when i test it ... if i log in it redirect me to the index.php page as i typed in the code yet the msg wont change ...
Here is the codes :
index.php / header.php:
<?php
error_reporting(E_ALL ^ E_NOTICE);
error_reporting(0);
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<LINK REL=StyleSheet HREF="css/test-style.css" TYPE="text/css">
</head>
<body id="body">
<div id="header">
<div id="Greeting">
<?php
if ($userid && $username) {
echo "<p>Welcome <b>$username</b></p></p><a href='logout.php'>Logout</a></p>";
} else {
echo "<p>Welcome Guest <br><a href='login.php'>Log in</a> | <a href='register.php'>Register</a></p>";
}
?>
</div>
<div id="logo"><h2>Testing website</h2></div>
</div>
<div id='cssmenu'>
<ul>
<li><a href='#'><span>Test link 1</span></a></li>
<li><a href='#'><span>Test link 2</span></a></li>
<li><a href='#'><span>Test link 3</span></a></li>
<li><a href='#'><span>Test link 4</span></a></li>
</ul>
</div>
<div>
and here is the login.php page :
<?php
error_reporting(E_ALL ^ E_NOTICE);
error_reporting(0);
include 'includes/header.php';
?>
<div id="login">
<h2>Log in</h2>
<?php
if ($_POST['loginbtn']) {
$user = $_POST['user'];
$password = $_POST['pass'];
if ($user) {
if ($password) {
require ("core/connect.php");
$query= mysql_query("SELECT * FROM users WHERE username='$user'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
$dbid = $row['id'];
$dbuser = $row['username'];
$dbpass = $row['password'];
$dbactive = $row['active'];
if ($password == $dbpass){
if ($dbactive == 1) {
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
header('Location: index.php');
} else {
echo "<font color='red'>You must activate your account to login.</font>";
}
}else {
echo "<font color='red'>You've entered an invalid username or password.</font>";
}
}else{
echo "<font color='red'>You've entered an invalid username or password.</font>";
}
mysql_close();
}else{
echo "<font color='red'>You must enter a password.</font>";
}
} else {
echo "<font color='red'>You must enter a username.</font>";
}
}
?>
<form action="index.php" method="POST">
<font color="black">Username: </font><br><input type="text" name="user"><br><br>
<font color="black">Password: </font><br><input type="password" name="pass"><br><br>
<input type="submit" value="Login" name="loginbtn" />
<br><br>
<font color="black">Don\'t have an account ? Register</font>
</form>
</div>';
<?php include 'includes/footer.php'; ?>
Thanks for reading.
In your login.php you're using this:
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
right after session_start()
You should initialize them before, like this:
$userid = $dbid;
$username = $dbuser;
and them you can set your $_SESSION:
$_SESSION['userid'] = $userid;
$_SESSION['username'] = $username;
In login.php replace
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
to
$_SESSION['userid'] = $dbid;
$_SESSION['username'] = $dbuser;
You actually never set the session variables. Those two line above do that.
Your script needs a lot of work but I just answer the question. Keep learning that's the only way!

Delete row with PHP - PDO on webpage

I am trying to delete a row from a table using PHP (PDO) on a page listing the rows entered into the database. I've been tinkering with the delete.php code to try to make it work but to no avail. I appreciate any help.
Below is my code:
listview.php
session_start();
include_once('../includes/connection.php');
include_once('../includes/events.php');
$event = new Event;
$events =$event->fetch_all();
if(isset($_SESSION['logged_in'])) {
//display index
?>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to the admin page</title>
</head>
<body>
<div class="container">
<h1>The List of Events</h1>
<ol>
<?php foreach ($events as $event) { ?>
<li>
<?php echo $event['event_name']; ?>
<?php echo $event['event_date']; ?>
<?php echo $event['event_location']; ?>
<?php echo $event['description']; ?>
<?php echo $event['start_time']; ?>
<?php echo $event['end_time']; ?>
<?php echo $event['poc_name']; ?>
<?php echo $event['poc_email']; ?>
<?php echo $event['poc_number']; ?>
<!--edit/delete links-->
Edit
Delete
<!--end edit/delete links-->
</li>
<?php } ?>
</ol>
</div>
</body>
</html>
<?php
} else {
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
//check the fields in the login form
if(empty($username) or empty($password)) {
$error = 'All fields are required';
} else {
$query = $dbh->prepare("SELECT * FROM admin WHERE username = ? AND userpassword = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if($num == 1) {
//correct
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//incorrect
$error = 'Incorect details';
}
}
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Squeegee Admin Login</title>
</head>
<body>
<div class="container">
Squeegee Admin
<br/>
<?php if (isset($error)) { ?>
<small style="color:#aa000; "><?php echo $error; ?> </small>
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</body>
</html>
<?php } ?>
Connection
<?php
// mysql hostname
$hostname = 'localhost';
// mysql username
$username = 'root';
// mysql password
$password = '';
// Database Connection using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=squeegee", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
events.php
<?php
class Event {
//queries from database
public function fetch_all() {
global $dbh;
$query = $dbh->prepare("SELECT * FROM events");
$query->execute();
return $query->fetchAll();
}
//queries specific article via id
public function fetch_data($event_id) {
global $dbh;
$query = $dbh->prepare("SELECT * FROM events WHERE event_id = ? ");
$query->bindValue(1, $event_id);
$query->execute();
return $query->fetch();
}
}
?>
delete.php
<?php
include('../includes/connection.php');
$event_id=$_GET['event_id'];
$result = $dbh->prepare("DELETE FROM events WHERE event_id= :event_id");
$result->bindParam(':event_id', $event_id);
$result->execute();
header("location: index.php");
?>
As your question stands, it seems you're accessing the wrong index.
In your link it is defined as id:
Delete
// ^
But then accessed in your PHP file as:
$event_id=$_GET['event_id'];
Must be: $event_id = $_GET['id'];
Either you change your url as ?event_id in the anchor or change the array index in your PHP $event_id = $_GET['id'];. The important things is they must match.

Categories