How to persist user data in different pages using php - php

I have 3 pages, I am trying to create a simple member login system using session .
In my first page ( index.php) I have database connection, session setup and this following login from :
<form action="index.php" method="POST">
<table>
<tr>
<td><label>Username</label></td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td><label>Password</label></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitbtn" value="Login" /></td>
</tr>
</table>
</form>
In member's profile page (member.php), I have a table to fetch data from database of that specific member logged in :
<table>
<?php $members=getMember(); ?>
<?php while($member = $members->fetch_assoc()) : ?>
<tr><td><label>Name</label></td><td><?php echo $member['name'];?></td></tr>
<tr><td><label>Age</label></td><td><?php echo $member['age'];?></td></tr>
<?php endwhile; ?>
</table>
and at dbconnection.php page I have this function :
<?php
function getMember(){
$db_conn = getConnection();
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if(!$db_conn) return false;
$sql = "SELECT * FROM member WHERE username ='$username' AND password='$password'";
$result = $db_conn->query($sql);
$db_conn->close();
return $result;
}
The code of session setup are :
<?php
$username="";
$password="";
$success=true;
$_SESSION['username']=$username;
if(isset($_POST['username']) && isset($_POST['password']))
{
$username=$_POST['username'];
$password=$_POST['password'];
if(check_in_db($username,$password)){
$_SESSION['logged_in']=1;
$_SESSION['username']=$username;
header("Location: adminPanel.php");
}
else{
$success=false;
}
}
?>
But when I am logging in, data ( name and age ) is not fetching ( displaying) there in member.php page ( I can't add image, since my reputation is under 10 ).
Thank you for your time .

I would suggest you take a look at php type comparisons for how isset() works. To let you know how php session works and how users persist in different pages, you have to digg into php session. I would recommend you use PDO and its prepare method when you're dealing with user data. Here you would get a very simple example of it.
The following code is working. So please take a look at them how they are constructed:
dbconnection.php
<?php
function getConnection() {
$servername = "localhost";
$username = "root";
$password = "12345";
$dbname = "db_test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function check_in_db($username, $password) {
$db_conn = getConnection();
if (!$db_conn) {
return false;
}
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $db_conn->query($sql);
return $result->num_rows > 0;
}
function getMember($username, $password) {
$db_conn = getConnection();
if (!$db_conn) {
return false;
}
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $db_conn->query($sql);
return $result;
}
index.php
<?php
session_start();
require_once('./dbconnection.php');
$success = true;
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(check_in_db($username, $password)) {
$_SESSION['logged_in'] = 1;
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("Location: adminPanel.php");
}
else{
$success=false;
}
}
?>
<form action="index.php" method="POST">
<table>
<tr>
<td><label>Username</label></td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td><label>Password</label></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitbtn" value="Login" /></td>
</tr>
</table>
</form>
and member.php
<?php
session_start();
require_once('./dbconnection.php');
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$members = getMember($username, $password);
?>
<table>
<?php while($member = $members->fetch_assoc()) : ?>
<tr><td><label>Name</label></td><td><?php echo $member['name'];?></td></tr>
<tr><td><label>Age</label></td><td><?php echo $member['age'];?></td></tr>
<?php endwhile; ?>
</table>

Related

Fatal error: Call to a member function check_login() on a non-object

I have the following login form :
<?php
include 'database/db_connect.php';
$link = mysqli_connect($host_name, $user_name, $password, $database);
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?><?php
session_start();
include 'database/websrvc.php';
$user = new Websrvc();
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $websrvc->check_login($emailusername, $password);
if ($login) {
// Registration Success
header("location:main.php");
} else {
// Registration Failed
echo 'Wrong username/email or password';
}
}
?>
<form action="" method="post" name="login">
<table class="table " width="400">
<tr>
<th> <label class="fieldstyle_with_label"> UserName or Email: </label> </th>
<td><input type="text" name="emailusername" required></td>
</tr>
<tr>
<th><label class="fieldstyle_with_label"> Password : </label></th>
<td><input type="password" name="password" required></td>
</tr>
<tr>
<td> </td>
<td><input class="large_button" type="submit" name="submit" value="Login" onclick="return(submitlogin());"></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</form>
When I try to log in using the folowing script, I get the following Fatal Error :
Fatal error: Call to a member function check_login() on a non-object in /homepages/23/d81301375/htdocs/emarps/login
Below is my class web_srvc.php that is supposed that handles the check_login :
public function check_login($emailusername, $password) {
$link = $this->db_connection();
$password = md5($password);
//checking if the username is available in the table
$result = mysqli_query($link, "SELECT user_id,user_name,role_id,status from users WHERE email='$emailusername' or user_name='$emailusername' and password='$password'");
$user_data = mysqli_fetch_array($result, MYSQLI_BOTH);
$count_row = mysqli_num_rows($result);
if ($count_row == 1) {
$_SESSION['login'] = true; // this login var will use for the session thing
$_SESSION['uid'] = $user_data['uid'];
return true;
} else {
return false;
}
}
$login = $websrvc->check_login($emailusername, $password);
change to
$login = $user->check_login($emailusername, $password);

How to get data for specific user, but from different table

I want to display the data for user 1 from database A right after he logged in, right now the page showing all the data from the table.
currently I have 2 table which is for user login and user transaction. so after they logged in, i want them to be able to view their own record. After do searching, im thinking that it has something to do with session.
can someone help me?
connection.php
<?php
$mysql_host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
$mysl_database = "mockup";
$conn = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_select_db($mysl_database, $conn);
?>
login.php
<?php
include("connection.php");
if(isset($_POST["submit"])) {
$username = $_POST["username"];
$password = $_POST["password"];
$sql = "SELECT * FROM user
WHERE username='$username' AND password='$password'";
$result = mysql_query($sql);
$numRows = mysql_num_rows($result);
if($numRows==1) {
session_start();
$_SESSION["ID"] = $ID;
header("Location: ./profile_page.php");
} else {
echo "Invalid Login Information";
}
}
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post">
<table>
<tr><td>User Name</td><td><input type="text" name="username" /></td></tr>
<tr><td>Password</td><td><input type="password" name="password" /></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Login" /></td></tr>
</table>
</form>
profile_page.php
<?php
session_start(); // start the session
include("connection.php");
$ID = $_SESSION["ID"]; // store the user id into session
$sql = "SELECT * FROM transaction WHERE ID='$ID'";
$result = mysql_query($sql);
if($row = mysql_fetch_array($result)) {
$deposit = $row["deposit"];
echo "
<table>
<tr><td>transaction</td><td> : </td><td>$transaction</td></tr>
</table>
";
}
?>
connection.php
<?php
$mysql_host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
$mysl_database = "database_name";
$conn = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_select_db($mysl_database, $conn);
?>
login.php
<?php
include("connection.php");
if(isset($_POST["submit"])) {
$username = $_POST["username"];
$pass = $_POST["pass"];
$sql = "SELECT * FROM tbl_user
WHERE username='$username' AND pass='$pass'";
$result = mysql_query($sql);
$numRows = mysql_num_rows($result);
if($numRows==1) {
session_start();
$_SESSION["userid"] = $userid;
header("Location: ./profile_page.php");
} else {
echo "Invalid Login Information";
}
}
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post">
<table>
<tr><td>User Name</td><td><input type="text" name="username" /></td></tr>
<tr><td>Password</td><td><input type="password" name="pass" /></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Login" /></td></tr>
</table>
</form>
profile_page.php
<?php
session_start(); // start the session
include("connection.php");
$user_id = $_SESSION["userid"]; // store the user id into session
$sql = "SELECT * FROM tbl_user WHERE user_id='$user_id'";
$result = mysql_query($sql);
if($row = mysql_fetch_array($result)) {
$username = $row["username"];
$name = $row["name"];
$email = $row["email"];
echo "
<table>
<tr><td>User Name</td><td> : </td><td>$username</td></tr>
<tr><td>Name</td><td> : </td><td>$name</td></tr>
<tr><td>Email</td><td> : </td><td>$email</td></tr>
</table>
";
}
?>
you can protect and access the user data after they logged in sucessfully by the help of session.
you could use session_start() for start new session or resume existing session.
<?php
session_start();
if(empty($_SESSION['user_sesion_variable']))
{
header("location:login.php");
die();
}
// here go your user database value

Trying to change login page from mysql_connect to work with PDO, with no luck

I'm trying to change my login page from mysql_connect(which work's perfectly) to work with PDO, with no luck.
Every time i hit 'login' with a correct username and password it just refresh the same login page.
Thanks in advance!
Working code with mysql_connect:
<?
session_start();
$user = "XXXX";
$password = "YYYY";
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<br><br><br><br><br><br><br><br>
<div align="center"><h1>Home</h1>
<h3>
<? if (isset($_SESSION["authenticated"])) { ?>
You are logged in!
<br />
log out
See page
<? } else { ?>
You are not logged in!
<? } ?>
</h3>
<br>
<?
if (($connection = mysql_connect("localhost", $user, $password)) === false)
die("Could not connect to database");
// select database
if (mysql_select_db("123456", $connection) === false)
die("Could not select database");
// if username and password were submitted, check them
if (isset($_POST["name"]) && isset($_POST["password"]))
{
// prepare SQL
$sql = sprintf("SELECT * FROM students WHERE name='%s'",
mysql_real_escape_string($_POST["name"]));
// execute query
$result = mysql_query($sql);
if ($result === false)
die("Could not query database");
// check whether we found a row
if (mysql_num_rows($result) == 1)
{
// fetch row
$row = mysql_fetch_assoc($result);
// check password
if ($row["password"] == $_POST["password"])
{
// remember that user's logged in
$_SESSION["authenticated"] = true;
$host = $_SERVER["HTTP_HOST"];
$path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\");
header("Location: http://$host$path/userpage.php");
exit;
}
}
}
?>
<form action="<?= $_SERVER["PHP_SELF"] ?>" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input name="name" type="text"></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" type="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Log In"></td>
</tr>
</table>
</form></div>
</body>
</html>
New code with PDO(doesn't work):
<?
session_start();
$user = "XXXX";
$password = "YYYY";
$dbh = new PDO('mysql:host=localhost;dbname=123456', $user, $password);
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<br><br><br><br><br><br><br><br>
<div align="center"><h1>Home</h1>
<h3>
<? if (isset($_SESSION["authenticated"])) { ?>
You are logged in!
<br />
log out
See page
<? } else { ?>
You are not logged in!
<? } ?>
</h3>
<br>
<?
// if username and password were submitted, check them
if (isset($_POST["name"]) && isset($_POST["password"]))
{
// prepare SQL
$idd = $_POST["name"];
$qry = "SELECT * FROM students WHERE name='$idd'";
$result = $dbh->query($qry);
if ($result === false)
die("Could not query database");
if (mysql_num_rows($result) === false)
die("No luck!");
if (mysql_num_rows($result) == 1)
{
// fetch row
$row = mysql_fetch_assoc($result);
// check password
if ($row["password"] == ($_POST["password"]))
{
// remember that user's logged in
$_SESSION["authenticated"] = true;
$host = $_SERVER["HTTP_HOST"];
$path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\");
header("Location: http://$host$path/userpage.php");
exit;
}
}
}
?>
<form action="<?= $_SERVER["PHP_SELF"] ?>" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input name="name" type="text"></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" type="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Log In"></td>
</tr>
</table>
</form></div>
</body>
</html>
You are using the mysql_* functions on a PDOStatement object returned by the query method. To get the number of rows try $result->rowCount(). To fetch the record use one of the fetch methods. See this link

PHP while...if statement not working, seems to ignore the ELSE

Can anyone help, I have been trying to get this php code to work, with limited success, it seem the else statement in the while statement is being ignored, i have looked at other examples and just can't see what I've done wrong. The code is used within a login form and the part that doesn't work is when a user inputs the wrong password. I am new to PHP and this is for a college assignment. I will include the code for the login page also.
<?php
ob_start();
session_start();
error_reporting(0);
$username = $_POST['username'];
$password = $_POST['password'];
//sanitize username
$username = mysql_real_escape_string($username);
if($username&&$password) {
include 'db.php';
$query = mysql_query("SELECT id, username, password, salt
FROM member
WHERE username = '$username';");
$numrows = mysql_num_rows($query);
$result = mysql_query($query);
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$salt = $userData['salt'];
$hash = hash('sha256', $salt . hash('sha256', $password) );
if ($numrows !=0) {
while ($rows = mysql_fetch_assoc($query))
{
$dbusername = $rows['username'];
$dbpassword = $hash;
if ($username===$dbusername&&$hash===$dbpassword)
{
$_SESSION['username']=$dbusername;
header("location: index.php?remarks=success");
}
else
{
header("location: index.php?remarks=incorrect");
}
}
}
else
header("location: index.php?remarks=register");
}
else
header("location: index.php?remarks=other");
?>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form method="post" action="code_index.php">
<table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td colspan="2">
<div align="center">
<?php
$remarks=$_GET['remarks'];
if ($remarks==null and $remarks=="")
{
echo "Login Here<br/> <a href='registration.php'>Or Click Here to Register.</a>";
}
if ($remarks=='register')
{
echo "That username Does not Exists.<br/><a href='registration.php'>Click Here to register.</a>";
}
if ($remarks=='incorrect')
{
echo "Incorrect Password.<br/>Please Re-enter Password";
}
if ($remarks=='success')
{
echo "Login Successful. <br/> <a href='membersarea.php'>Click Here to go to the Members Area.</a>";
}
if ($remarks=='other') {
echo "Please enter a Username and Password<br/><a href='registration.php'>Or Click Here to register.</a>";
}
?>
</div></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="username" placeholder="Enter your Username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="Enter your Password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
You need to assign dbpassword from database
//$dbpassword = $hash; //This is wrong
Do it like this.
$dbpassword = $rows['password'];
if ($username===$dbusername&&$hash===$dbpassword)
Can you try this,
ob_start();
session_start();
error_reporting(0);
$username = $_POST['username'];
$password = $_POST['password'];
//sanitize username
$username = mysql_real_escape_string($username);
if(isset($username) && isset($password)) {
include 'db.php';
$query = mysql_query("SELECT id, username, password, salt
FROM member
WHERE username = '$username' ");
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($rows = mysql_fetch_array($query))
{
$dbusername = $rows['username'];
$salt = $rows['salt'];
$hash = hash('sha256', $salt . hash('sha256', $password) );
$dbpassword = $hash;
if ($username==$dbusername && $hash==$dbpassword)
{
$_SESSION['username']=$dbusername;
header("location: index.php?remarks=success");
}
else
{
header("location: index.php?remarks=incorrect");
}
}
}else{
header("location: index.php?remarks=register");
}
}else{
header("location: index.php?remarks=other");
}

php login register error

I do have some code in OOP in PHP that's supposed to login/register a user, and a register function works great, but the login function doesn't work and I can't login. And I also have notices that in the array $_SESSION I have undefined indexes "login", "password".
Here is the main page:
<?php
require_once "libs/user_class.php";
$user = User::getObject();
$auth = $user->isAuth();
if(isset($_POST["reg"])){
$login = $_POST["login"];
$password = $_POST["password"];
$reg_success = $user->regUser($login,$password);
}
elseif (isset($_POST["auth"])){
$login = $_POST["login"];
$password = $_POST["password"];
$auth_success = $user->login($login,$password);
if($auth_success){
header("Location:index.php");
exit;
}
}
?>
<html>
<head>
<title>REGISTER</title>
</head>
<body>
<?php
if($auth){
echo "Welcome".$_SESSION["login"];
}
else{
echo '<h2>REGISTRATION</h2>
<form action="index.php" method = "post" name="reg">
<table>
<tr>
<td>Log in</td>
<td>
<input type="text" name = "login" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name = "password" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type="submit" name="reg" value = "register" />
</td>
</tr>
</table>
</form>
<h2>LOGIN</h2>
<form action="index.php" method = "post" name="auth">
<table>
<tr>
<td>Log in</td>
<td>
<input type="text" name = "login" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name = "password" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type="submit" name="auth" value = "authorize" />
</td>
</tr>
</table>
</form>';
}
?>
</body>
</html>
And the user_class.php:
<?php
class User{
private $db;
private static $user = null;
private function __construct(){
$this->db = new mysqli("localhost", "root", "root", "temp");
$this->db->query("SET NAMES 'utf8'");
}
public static function getObject(){
if(self::$user === null) self::$user = new User();
return self::$user;
}
public function regUser($login, $password){
if($login == "")return false;
if($password == "")return false;
$password = md5($password);
return $this->db->query("INSERT INTO `users` (`login`, `password`) VALUES ('$login','$password')");
}
private function checkUser($login, $password){
$result_set = $this->db->query("SELECT `password` FROM `users` WHERE `login` = '$login'");
$user = $result_set->fetch_assoc();
$result_set->close();
if(!$user) return false;
return $user["password"] === $password;
}
public function isAuth(){
session_start();
$login = $_SESSION["login"];
$password = $_SESSION["password"];
return $this->checkUser($login,$password);
}
public function login($login, $password){
if($this->checkUser($login, $password)){
session_start();
$_SESSION["login"] = $login;
$_SESSION["password"] = $password;
return true;
}
else return false;
}
public function __destruct(){
if ($this->db) $this->db->close();
}
}
?>
In your database, you are storing the password field with md5 encryption. So, while checking username and password in your login and checkuser function, you nee to check password as md5($password).
Also, I wonder why you have kept the form name and submit button name same.

Categories