Passing php variable from this.php to that.php - php

So I need to pass a variable from one php to another php page but I dont know how to do it. I got this piece of code "$realname= $row['name'];" that stores the real name of the person to display it in another page after they successfully login, but when I try to use $realname variable in the other page it wont display it. How can I make this posible??? thanks in advance
page one login.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
include 'functions.php';
if(loggedin())
{
header("Location: userarea.php");
exit();
}
if(isset($_POST['login']))
{
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];
//validate
if($username&&$password)
{
$login = mysql_query("SELECT * FROM users WHERE username='$username'");
if(mysql_num_rows($login) == 1)
{
while($row = mysql_fetch_assoc($login))
{
$db_password = $row['password'];
if($password == $db_password)
$loginok= TRUE;
else
$loginok = FALSE;
if($loginok==TRUE)
{
$realname= $row['name'];
if($rememberme == "on")
setcookie("username", $username, time() + 7200);
else if ($rememberme == "")
$_SESSION['username'] = $username;
header("Location: userarea.php");
exit();
}
else
die("Incorrect username or password. Please try again or contact your local admin.");
}
}die("Incorrect username or password. Please try again or contact your local admin.gdfgdfgdfg");
}
else
die("Please enter a username and password.");
}
?>
<h>Welcome!</h>
<form action="login.php" method="POST">
Username:<br />
<input type="text" name="username"><p />
Password:<br />
<input type="password" name="password"><p / >
<input type="checkbox" name="rememberme"> Remember me<br />
<input type="submit" name="login" value="Log in">
</form>
</body>
</html>
Page 2 userarea.php (as you can see I declared $realname variable but I cant use it)
<html>
<body>
<?php
include 'functions.php';
if(!loggedin())
{
header("Location: login.php");
exit();
}
echo "Hello $realname";
?>
<h>Access Granted! Yeiy! </h>
Log out
</body>
</html>

This is exactly what sessions are for:
Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.
page one login.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
$_SESSION['realname'] = $row['name'];
Page 2 userarea.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
echo "Hello $_SESSION['realname']";

First pass $_SESSION['var_name']; on login page and then
start session_start() on the top of the userarea page and echo your session variable
echo $_SESSION['var_name'];

Related

PHP Session not recognizing variable when heading to another page

So I'm making a Login - Successful Login page with PHP, and using MySQL Database. My code successfully checked the Username and Password and only allowed me to head to the next page once they are correct.
However, I cannot print out the Username on Successful Login page. So I'm not sure if my session is running properly or not.
login.php
<!DOCTYPE HTML>
<html>
<?php
session_start();
?>
<head>
<title>Login</title>
</head>
<body>
<!--<form action ="SuccessfulLogin.php" method = "get"> --> // If I put this in my code, the whole program stops checking Username and Password, and just put me to the next page
<?php
//define variables and set to empty values
$nameErr = $loginErr = "";
$Username = $website = $Password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Username"])) {
$nameErr = "Name is required";
} else {
$Username = test_input($_POST["Username"]);
}
if (empty($_POST["Password"])) {
$passErr = "Password is required";
} else {
$Password = test_input($_POST["Password"]);
}
//continues to target page if all validation is passed
if ( $unameErr ==""&& $passErr ==""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$hashpass=hash('sha256',$Password);
$sql="SELECT * from Members WHERE Username ='$Username' AND Password='$hashpass';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database");
$a=mysqli_num_rows($result);
if ($a===0){
$loginErr="Invalid username or password";
}else{
$_SESSION["Username"]=$Username;
header('Location: /SuccessfulLogin.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Login </h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
User Name: <input type="text" name="Username" value="<?php echo $Username;?>"/>
<span class="error">* <?php echo $unameErr;?></span>
<br/><br/>
Password:
<input type="text" name="Password" value=""/>
<span class="error">* <?php echo $passErr;?></span>
<br/><br/>
<span class="error">* <?php echo $loginErr;?></span>
<input type="submit" name="submit" value="Login"/> 
</form>
<!--</form>--> // closing tag of form action SuccessfulLogin.php
</html>
SuccessfulLogin.php
<!doctype html>
<html>
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<body>
<!--<form action ="MemberMenu.php" method = "get">-->
<h2><?php echo "User $Username LOGGED IN"; ?></h2> // Doesn't print out the $Username
<p align="center"> Click here to be redirected to the menu page </p>
<!--</form>-->
</footer>
</body>
</html>
you need to check session isset or not.
Change
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
With
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
echo $Username;
}
?>
You're using $_GET["Username"] which will be empty in this example, and then setting $_SESSION["Username"] to the empty variable.
Also this is a very odd way to do user auth.
Change this line of code
<?php
session_start();
$Username=$_SESSION['Username'];
$_SESSION['Username']=$Username;
?>
Into:
<?php
session_start();
$Username=$_SESSION['Username'];
?>
Read more about PHP session here

How can I secure my HTML page using PHP? I am getting error [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have created session in php and restricted the admin.php page. If user is not logged in he/she or any alien/robot cannot access the page. After login it must go to admin page. But it goes to contact.php which is mentioned in check.php. If I do not include check.php in admin.php. It goes to admin.php after login but admin.php can be access without login also. Can you check where I am wrong?
This is login.php--
<?php
include('connect.php'); // Include connect for login Script
if ((isset($_SESSION['username']) != ''))
{
header('Location: admin.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<meta charset="UTF-8">
<title>Admin Login</title>
</head>
<body>
<div class="login-block">
<form action="" method="POST">
<h1>Login</h1><span><img src="/img/loginlogo.png"/></span>
<span id="invalid"><?php echo $error; ?></span>
<input type="text" name="username" placeholder="Username" id="username" />
<span><?php echo $usererror; ?></span>
<input type="password" name="password" placeholder="Password" id="password" />
<span><?php echo $pwderror; ?></span>
<input id= "btn" name="submit" type="submit" value=" Login "/>
Forgot Password
Register Now
</form>
</div>
</body>
</html>
This is admin.php--
<?php
include('check.php');
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
<br><br><br>
Logout?
</body>
</html>
This is check.php--
<?php
include('db.php');
session_start();
$user_check=$_SESSION['username'];
$sql = mysqli_query($db,"SELECT username FROM credentials WHERE username='$user_check' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user=$row['username'];
if(!isset($user_check))
{
header("Location: contact.php");
}
?>
This is my connect.php--
<?php
session_start();
include("db.php"); //Establishing connection with our database
$error = ""; //Variable for storing our errors.
if(isset($_POST["submit"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$usererror = "Username can not be left blank";
$pwderror = "Password can not be left blank";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
//$password = md5($password);
//Check username and password from database
$sql="SELECT id FROM credentials WHERE username='$username' and password='$password'";
$result=mysqli_query($db, $sql);
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: admin.php"); // Redirecting To Other Page
}
else
{
$error = "Incorrect username or password.";
}
}
}
?>
I have fixed this issue.
I replaced my code in connect.php from:
$_SESSION['username'] = $login_user; // Initializing Session
to:
$_SESSION['username'] = $username; // Initializing Session
Thanks everyone.
I can help you and say that you should stop following that tutorial. Everything it is telling you about how to use HTML, PHP, MySQL is deprecated, not best pracise and just wrong. STOP using that tutorial, throw your work away and read up on Prepared SQL Statements as well as HTML5 and PHP 7 .
Always put die() or exit after a header("Location: ...); call.
Your login is checking your session value, therefore once you've logged in once correctly, then the session value will be remembered and you will always be "logged in". To break this cycle, clear your browser data for this website. Refresh the page.
I can't provide more detailed help without you Showing me what PHP errors (if any) you are getting and clarifying if you've been able to login correctly at all?

Full password protected website

Good day!
I'm trying to make a website where you could only access it by first typing the password in the front page(www.mywebsite.com/index.php)
Once I enter the password, It will get the file home.html from outside my public_html.
Then in that page(home.html) there will be links using the variable z (www.mywebsite.com/index.php?z=one) which will return 1.html or other pages.
Here's what I tried so far, but even if i use www.mywebsite.com/index.php?z=one
it still opens home.html
Can I get some help? And/or is what I'm trying possible?
<?php
$pass = $_POST['pass'];
if ($pass == "1234") {
$page = $_GET['z'];
if ($page == "one") {
include("../1.html");
} else {
include("../home.html");
}
} else {
if (isset($_POST)) {
?>
<!DOCTYPE html>
<html lang="en">
<form role="form" method="POST" style="margin: 0px" action="index.php">
<input type="password" name ="pass" class="form-control" id="pwd"> </input>
<input type="submit" class="btn btn-danger" value="Enter"></input>
</form>
</html>
<?php
}
}
?>
Thats not the way to approach this.
First make use of a session, but only hold a isLoggedIn flag in the session not the password.
Second, all scripts can be in the public_html folder, but what you do is add a little script that checks the loggedIn state to all scripts and if not loggedIn throw the login page
Heres a simple example
login_check.php
<?php
session_start();
if ( ! isset($_SESSION['loggedIn']) || $_SESSION['loggedIn'] == 0) {
header('Location: login.php');
exit;
}
Now in your login script
login.php
<?php
session_start();
if ( isset($_SESSION['loggedIn'] && $_SESSION['loggedIn'] == 1) {
// already logged in
header('Location: index.php.php'); // or some other page
exit;
}
If ( "The password is correct" ) { // this is of course pseudo code
$_SESSION['loggedIn'] = 1;
header('Location: somepage.php');
exit;
} else {
unset($_SESSION['loggedIn']);
header('Location: login.php');
exit;
}
?>
Now in all your other scripts
<?php
// first thing is always to check if this user is logged in
// so any access from a user not yet logged in just get
// thrown to the login page, or maybe your index.php
require_once 'login_check.php';
You can also use this session to hold useful but not sensitive things like
$_SESSION['user_id']; // id of the users info in user table
$_SESSION['FirstName'];
$_SESSION['LastName'];
$_SESSION['nickname'];
and anything else that might be useful to know across your application that you dont want to go to the database each time to collect.
Additional info
Your HTML is not well formed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>
<form role="form" method="POST" style="margin: 0px" action="index.php">
<input type="password" name ="pass" class="form-control" id="pwd" />
<input type="submit" name="login" class="btn btn-danger" value="Login" />
</form>
</body>
</html>
You could store the get/post pass in a session like $_SESSION['pass']
But you better encrypt it with a sha1 a least like
$_SESSION['pass'] = sha1($pass);
and to get it back
if($_SESSION['pass'] == sha1("1234")){}
You should use session.
But it is not a good practice to store your password in a session.
<?php
session_start();
if(isset($_POST['pass'])){
$_SESSION['p'] = md5($_POST['pass']);
//$pass = $_POST['pass'];
if($_SESSION['p'] == md5("1234"))
{
$page = $_GET['z'];
if($page == "one")
{
include("../1.html");
}
else
{
include("../home.html");
}
}
}
?>
I'm sure this will help you.
<?php
session_start();
if (!empty($_POST['pass']) && $_POST['pass'] == "1234") {
$_SESSION['pass'] = $_POST['pass'];
}
if (empty($_SESSION['pass'])) {
?>
<!DOCTYPE html>
<html lang="en">
<form role="form" method="POST" style="margin: 0px" action="index.php">
<input type="password" name ="pass" class="form-control" id="pwd"> </input>
<input type="submit" class="btn btn-danger" value="Enter"></input>
</form>
</html>
<?php
die;
}
$page = $_GET['z'];
if ($page == "one") {
include("../1.html");
} else {
include("../home.html");
}
?>

PHP login system without a database, sessions is not working?

First of all I won't build a login system that uses a database, I know it's more secure but in this case it's not relevant...
I have three files login.php, admin.php and config.php. The users email and password is stored in variables in config.php. If the user is logging in a session should be set. Then if a user that hasn't logged in trying to access admin.php ":-(" should be printed. But now the ":-(" is always printed and something needs to be wrong with how I coded it all...
config.php:
<?php
//site data
$title = "Abbesplace";
$siteurl = "index.php";
//user data
$password = "testtest";
$email = "example#example.com";
$name = "Albin Larsson";
?>
login.php:
<?php
require_once("config.php");
if (($_POST['email'] == $email && $_POST['password'] == $password)) {
//login
session_start();
$_SESSION['logged']= "welcometomoon";
header("Location: admin.php");
} else {
echo "login faild";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
</head>
<body>
<div>
<form method="post" action="login.php">
Email:<input type="email" name="email"/>
Password:<input type="password" name="password"/>
<input type="submit"/>
</form>
</div>
</body>
</html>
admin.php:
<?php
if(isset($_SESSION['logged'])){
echo "Hello";
} else {
echo ":-(";
}
?>
Any suggestions on what I should make different?
(I'm a newbie when i comes to PHP)...
You have to call session_start on every page. Right now you are only calling it when you post to the login form.

php mysql + session problems

i am creating a simple login and logout script using php and mysql but when i try to enter the login.php or the index file i get an error message that say :
**The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept
cookies.**
i do not know how to solve or what is the error if anyone help me i will be appreciate
index.php
<?php
require_once('connect.php');
ob_start();
session_start();
//checked wether the user is loged in or not
$user = $_SESSION['username'];
if(!isset($_SESSION['username']))
{
$user = $_SESSION['username'];
header("Location: index.php");
exit();
}
else
{
header("Location: home.php");
}
// login script
if(isset($_POST['username'])&& isset($_POST['password']))
{
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['username']);
$user_password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['password']);
$md5password = md5($user_password);
$sql = mysql_query("SELECT id FROM members WHERE username = '".$user_login."' AND password = '".$user_password."'") or die ("could not select from database");
$userCount = mysql_num_rows($sql);
if($userCount ==1)
{
while($row = mysql_fetch_array($sql))
{
$id = $row['id'];
}
$_SESSION['id'] = $id;
$_SESSION['username'] = $user_login;
$_SESSION['password'] = $user_password;
header("Location: index.php");
exit();
}
else
{
echo "that info is incorrect";
exit();
}
}
?>
<!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>Untitled Document</title>
</head>
<body>
<form action="login.php" method="post">
<input name="username" type="text" value="username" size="32" />
<input name="pass" type="password" value="password" size="32" />
<input name="login" type="submit" value="login" />
</form>
</body>
</html>
<?php ob_end_flush(); ?>
home.php
<?php
//home.php
session_start();
$user = $_SESSION['username'];
if(!isset($_SESSION['username']))
{
header("Location: index.php");
exit();
}
else
{
echo "hi $user you are loged in //Welcome to our website Logout";
}
?>
logout.php
<?php
session_start();
session_destroy();
header("Location: index.php");
?>
In index.php you need to put this if condition on top after 'session_start();'
if($_SESSION['username'])
{
header("Location: home.php");
exit();
}
In while loop it should be header("Location: home.php"); instead of header("Location: index.php");
In home.php page you should put on top after opening php tag
ob_start();
session_start();
Hope it will work.
++++++++++++++++++++++++++++++++++++++++++
Use this code
index.php
<?php
require_once('connect.php');
ob_start();
session_start();
//checked wether the user is loged in or not
$user = $_SESSION['username'];
if($_SESSION['username'])
{
$user = $_SESSION['username'];
header("Location: home.php");
exit();
}
// login script
if(isset($_POST['username'])&& isset($_POST['password']))
{
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['username']);
$user_password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['password']);
$md5password = md5($user_password);
$sql = mysql_query("SELECT id FROM members WHERE username = '".$user_login."' AND password = '".$user_password."'") or die ("could not select from database");
$userCount = mysql_num_rows($sql);
if($userCount ==1)
{
while($row = mysql_fetch_array($sql))
{
$id = $row['id'];
}
$_SESSION['id'] = $id;
$_SESSION['username'] = $user_login;
$_SESSION['password'] = $user_password;
header("Location: home.php");
exit();
}
else
{
echo "that info is incorrect";
exit();
}
}
?>
<!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>Untitled Document</title>
</head>
<body>
<form action="login.php" method="post">
<input name="username" type="text" value="username" size="32" />
<input name="pass" type="password" value="password" size="32" />
<input name="login" type="submit" value="login" />
</form>
</body>
</html>
<?php ob_end_flush(); ?>
home.php
<?php
ob_start();
session_start();
//home.php
$user = $_SESSION['username'];
if(!isset($_SESSION['username']))
{
header("Location: index.php");
exit();
}
else
{
echo "hi $user you are loged in //Welcome to our website Logout";
}
?>
logout.php is correct
First, in index.php you don't need to "//checked wether the user is loged in or not", we should check that in home.php.
This code is causing your error : "The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete". You made a repetition (The session is not created but it is checked ...).
Second, in home.php, You have to write session_start() method, this is the code require when using session.
Refer my code:
index.php
<?php
ob_start();
session_start();
//check session is existed
if (isset($_SESSION['username'])) {
header("Location: home.php");
}
if (isset($_POST['username']) && isset($_POST['password'])) {
$user_login = $_POST['username'];
$user_password = $_POST['password'];
if ($user_login == 'namluu' && $user_password =='123456') {
$_SESSION['username'] = $user_login;
$_SESSION['password'] = $user_password;
header("Location: home.php");
exit();
} else {
echo 'Infor not correct';
exit();
}
}
?>
<html>
<head></head>
<body>
<form action="index.php" method="post">
<input type="text" name="username" />
<input type="text" name="password" />
<input type="submit" name="login" value="login" />
</form>
</body>
</html>
<?php
ob_end_flush();
?>
home.php
<?php
session_start();
//home.php
$user = $_SESSION['username'];
if(!isset($_SESSION['username']))
{
header("Location: index.php");
exit();
}
else
{
echo "hi $user you are loged in //Welcome to our website Logout";
}
?>
You haven't got session_start() at the top of home.php, which means you will have created an infinite loop between home.php and index.php.
Currently what is happening is when you access index.php, it recognises the session and redirects the user to home.php. As there is no session_start() in home.php, it doesn't recognise the session and redirects the user back to index.php. Thus you have an infinite loop.

Categories