Hello Everyone I am new in PHP and I am trying to create a very small application in php
I am trying to access the userid of a user using session in php for this I am following these steps
I create these classes in my application
My first class is Database Manager which I place in model folder
public function executeQuery($query) {
$result = mysql_query($query);
if ($result === false) {
$this->closeConnection($this->conn);
exit;
}
// extract data from results, returning an associative array
$rows = Array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
and then I create these two classes
First is loginManager
class LoginManager
{
function checkLogin($arr)
{
require_once(FRONT_ROOT_PATH.'DatabaseManager.php');
$query ="Select * from tbusers where username='".$arr['username']."' and password='".$arr['password']."'";
$db= new DatabaseManager();
$result=$db->executeQuery($query);
return $result;
}
}
and second is LoginInit
<?php
session_start();
include(LIB_PATH."Login/LoginManager.php");
if(isset($_POST['addlogin']))
{
$obj= new LoginManager();
$userlist=$obj->checkLogin($_POST);
if(Count($userlist)>0)
{
$_SESSION['uid']=$userlist['userid'];
header('location:/ProjectDream/view/home/home.php');
}
else
{
echo "Login Failed";
}
}
}
In this class I add the session and after that I call these classes on this php page
<?php
include('Include/config.inc.php');
include(LIB_PATH."Login/Logininit.php");
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login</title>
<!-- CSS -->
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<!-- Main HTML -->
<body>
<!-- Begin Page Content -->
<div id="container">
<form action="" method="post">
<input type="hidden" name="addlogin"/>
<label for="name">Username:</label>
<input type="name" name="username">
<label for="username">Password:</label>
<p>Forgot your password?
<input type="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div>
</form>
</div>
<!-- End Page Content -->
</body>
</html>
and when user login I send user to home.php page I write this code on home.php
<?php
session_start();
if(isset($_SESSION['uid']))
{
echo $_SESSION['uid'];
}
else
{
echo "No Session ";
}
?>
Now when I run this application then it show me no value in my $_SESSION variable
Is it possible to call session on class level in php. Please tell me how can I use session here
Thanks
try it like this it should work:
$_SESSION['uid']=$userlist[0]['userid'];
In your code:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
You are adding $row to $rows so you're having $rows[0]=$row; then $rows[1]=$row;
so actually $rows['userid'] isn't set, it is $rows[0]['userid'] that is set
the varible to which the value is assigned should be in left side of equation.
so
change
$userlist['userid']=$_SESSION['uid'];
to
$_SESSION['uid']=$userlist['userid'];
You must assign some value to $_SESSION['uid'] when reading values from database. Something like:
$_SESSION['uid'] = $row['uid'];
Also note that when you want to use data from $_SESSION variable you must call session_start().
Related
I'm making a very simple login script (beginner at PHP) and here is my code. I can't figure out how to redirect after true login credentials. I know this probably is a duplicate but I can't figure this out without help on my exact script (as mentioned above I'm not that good).
update: So I have fixed name in password, form method, and the redirect . But now I'm getting to a empty page, something is wrong with my function as one comment earlier. I'm also a dummie at MySQL can someone help me further? My code is updated
Another update
Okay so i have finished all of my script, but the problem is my sql functions. So does anyone know mysqli and can translate it?
<?php $tilkobling = mysqli_connect("localhost","root","root","login_form");
if(isset($_POST["name"], $_POST["password"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$result1 = mysql_query("SELECT username, password
FROM user
WHERE username = '".$name."'
AND password = '".$password."'");
if(mysql_num_rows($result1) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>login</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>bypass to information site</h2>
<div class="login-page">
<div class="form">
<h1>Login</h1>
<form method="post" class="login-form">
<input name="name" type="text" placeholder="username"/>
<input name="password" type="password" placeholder="password"/>
<button name="submit">login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script type="text/javascript">
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
</html>
You're using mysqli connector and mysql functions so let's assume you'll use mysql for all
$tilkobling = mysql_connect("localhost","root","root");
mysql_select_db( "login_form", $tilkobling );
and you'll need to add session_start() before using/setting any session variables
session_start();
$_SESSION["logged_in"] = true;
Your header needs to be in the true portion of the if/else, which is where you set your $_SESSION variables, here you are:
if(mysql_num_rows($result1) > 0 )
{
session_start();
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
Have you Tried the HTML meta tag, this subtitutes the header() function.
Of course initially convert it into PHP code. Like this:
Echo "<meta http-equiv='refresh' content='0; URL=put your url in here to the page you like to redirect to'>" ;
This should probably operate correctly.
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
So, i am learning how to write php now.I want to build a small shopping website. My index.html looks something like this:
<!DOCTYPE html>
<html>
<head>
<link href="index.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="topnav">
<a class="active" href="#index.html">Home</a>
Administrator
Register User
Register New Account
</div>
<img class="centerImage" src="eshop.jpg">
</body>
</html>
and the loginAdmin.php file looks like this:
<?php
session_start();
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";
$link = mysqli_connect(localhost,$user,$passwd);
#mysqli_select_db($link,$database) or die ("Unable to select database");
// try to create a new record from the submission
$username = mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);
if ($username && $password) {
// here we define the SQL command
$query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";
// submit the query to the database
$res=mysqli_query($query);
// make sure it worked!
if (!$res) {
echo mysql_error();
exit;
}
// find out how many records we got
$num = mysqli_numrows($res);
if ($num==0) {
echo "<h3>Invalid login</h3>\n";
exit;
} elseif ($num!=1) {
echo "<h3>Error - unexpected result!\n";
exit;
}
// valid login, set the session variable
$_SESSION['userid']=mysql_result($res,0,'userid');
echo "<h3>Welcome $username</h3>\n";
?>
<head>
<link href="login.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form">
<input type="text" placeholder="User Name:" />
<input type="password" placeholder="Password:" />
<button onclick="writeMsg()">login</button>
</form>
</div>
</div>
</body>
If the user pressed on the loginAdmin link so the php code will be executed, and i dont want that, only after the user pressed on the login button i want the php code block will be executed. How can i do that? Maybe i should seperate the files (php and html) and not user href on the php files in the index.html ? and the index.html file should be index.php?
You need to add your php code within a condition which satisfies when the form submission happens. Also you need to add name to your input fields
Your code will look like this,
<?php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])) { //Added this line
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";
$link = mysqli_connect(localhost,$user,$passwd);
#mysqli_select_db($link,$database) or die ("Unable to select database");
// try to create a new record from the submission
$username = mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);
if ($username && $password) {
// here we define the SQL command
$query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";
// submit the query to the database
$res=mysqli_query($query);
// make sure it worked!
if (!$res) {
echo mysql_error();
exit;
}
// find out how many records we got
$num = mysqli_numrows($res);
if ($num==0) {
echo "<h3>Invalid login</h3>\n";
exit;
} elseif ($num!=1) {
echo "<h3>Error - unexpected result!\n";
exit;
}
// valid login, set the session variable
$_SESSION['userid']=mysql_result($res,0,'userid');
echo "<h3>Welcome $username</h3>\n";
}
} //Added this line
?>
<head>
<link href="login.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form" method="POST"> <!-- edited this line -->
<input type="text" name="username" placeholder="User Name:" /> <!-- edited this line -->
<input type="password" name="password" placeholder="Password:" /> <!-- edited this line -->
<button onclick="writeMsg()">login</button>
</form>
</div>
</div>
</body>
I have just added name to the form fields & then kept all your PHP code within a condition
having an issue with page chrome saying there are too many redirects, the page, finally does what i want(at least does function correctly as far as i know, as i tested it with a close connection, sticking at the top of page, and it is displaying the userID. When logged in this page does the redirecting, im not too sure how to fix this, found lots of different posts online, and each one was so different from the next.
<?php session_start();
include'../../connection.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href=".../../../../style.css">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include('../../main/main.php');?>
</head>
<body>
<div class=containermain>
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating" >
<option>
<option value="1">1 </option>
<option value="2">2</option>
<option value="3">3 </option>
<option value="4">4</option>
<option value="5">5</option>
</option>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
<?php echo "Hello " . $_SESSION['user']; ?>
<p> </p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div
class="fb-like"
data-share="true"
data-width="450"
data-show-faces="true">
</div>
<!---------------------------------------COMMENT BOX---------------------------------------------------->
<div class="comments" align="center">
<form action="" method="post" >
<textarea rows="4" cols="50" name="comment">
Please type a comment if you are logged in....
</textarea>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])) {
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
if(mysqli_query($conn, $sqlinsert)){
header("Location: i5-6600k");
} else {
echo "ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn);
}
}
// close connection
$sql = "SELECT `users`.`username`, `comment`.`comment`, `comment`.`timestamp`\n"
. "FROM `users`\n"
. "LEFT JOIN `comment` ON `users`.`userID` = `comment`.`userID` \n"
. "where dCpuID = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Username</th><th>Comment</th><th>Timestamp</th>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["username"]. "</td><td>" . $row["comment"]."</td><td>" . $row["timestamp"]. "</td>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</div>
<?php include('../../assets/footer.php');?>
<div class="fb-comments" data-href="http://www.computercomparison.tk/#home" data-numposts="5"></div>
</body>
</html>
I think I see what you are doing here, you are missing how to effectively process an action. You are triggering your comment by checking if something, which is persistent, exists and acting on it. If it's a session variable, it will persist, therefore the action is infinite until it stops persisting. You need an action in your submission.
I would have a config page that you include with all pages that contains re-usable variables. It would be stored in the root of the site. In general, you have some HTML errors and some unsafe SQL injection issues. I have created a little more complicated version of your page (without the bottom half, that needs a lot of work and should be wrapped as well) but it's only complicated to make the view less complicated...if that makes sense. Anyway, if you have issues let me know, I haven't tested this.
/config.php
<?php
# Create some absolute defines for consistent includes
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('VENDOR',ROOT_DIR.DS.'vendor');
define('SITE_URL','http://www.example.com');
# Start session
session_start();
# Autoloads all the classes we intend to use
spl_autoload_register(function($class){
$path = VENDOR.DS.trim(str_replace('\\',DS,$class),DS).'.php';
if(is_file($path))
require_once($path);
});
/vendor/App.php
<?php
# General/base class used for various time-saving actions
class App
{
# Store this object for re-use
protected static $singleton;
# Store others (if using getHelper() method)
protected static $apps;
# Create singleton
public function __construct()
{
if(!(self::$singleton instanceof \App))
self::$singleton = $this;
# Return back the same object
return self::$singleton;
}
# Get either the full post or just one key/value
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
# Get session or just one key/value pair
public function getSession($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return $_SESSION;
}
# Write and destroy session value
public function writeError($key)
{
$error = $this->getSession($key);
$this->destroy($key);
return $error;
}
public function destroy($key = false)
{
if(!empty($key)) {
if(isset($_SESSION[$key]))
$_SESSION[$key] = NULL;
return;
}
session_destroy();
}
# Sets a session value
public function setSession($key,$value)
{
$_SESSION[$key] = $value;
}
# Consistent way to write the site url (set in the config)
public function siteUrl($path = false,$ssl=false)
{
return ($ssl)? str_replace('http://','https://',SITE_URL).$path : SITE_URL.$path;
}
# Creates an instance if this object
public static function call()
{
return new \App();
}
# Saves and uses classes
public function getHelper($class,$inject=NULL)
{
$setKey = str_replace('\\','',$class);
if(isset(self::$apps[$setKey]))
return self::$apps[$setKey];
self::$apps[$setKey] = new $class($inject);
return self::$apps[$setKey];
}
}
/vendor/Router/Model.php
<?php
# Use for redirects, can be expanded out to do other router-type things
namespace Router;
class Model extends \App
{
public function addRedirect($path)
{
header('Location: '.$path);
exit;
}
}
/vendor/View/Model.php
<?php
# This is a wrapper for the page
namespace View;
class Model extends \App
{
public function render($path)
{
if(!is_file($path))
return;
# Create a buffer and render contents
ob_start();
include($path);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
/vendor/Commenter/Model.php
<?php
namespace Commenter;
class Observer extends \Router\Model
{
# Listen for action name, do action when required
public function listen($conn)
{
if($this->getPost('action') != 'addcomment')
return false;
if(!empty($this->getSession('login_id'))) {
$id = $this->getSession('login_id');
# You will want to bind parameters on this. This is an opening for SQL Injection (Google it)
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '".$this->getPost('comment')."', '1')";
if(mysqli_query($conn, $sqlinsert))
$this->addRedirect("i5-6600k");
else
$this->setSession('error',"ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn));
}
}
}
whatever this page is called...
<?php
# Create separator
$DS = DIRECTORY_SEPARATOR;
# Include config file
include(realpath(__DIR__.$DS.'..'.$DS.'..').$DS.'config.php');
# Check to see if this file is being wrapped by render class
if(!isset($this)) {
# Include this file into the renderer
echo \App::call()->getHelper('\View\Model')->render(__FILE__);
exit;
}
# Include connection
include(ROOT_DIR.DS.'connection.php');
# Listen for the add comment action
$this->getHelper('\Commenter\Observer')->listen($conn);
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href="<?php echo $this->siteUrl('/style.css') ?>">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include(ROOT_DIR.DS.'main'.DS.'main.php');?>
</head>
<body>
<div class="containermain" style="padding-bottom: 60px;">
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating">
<?php for($i=1; $i<=5;$i++) { ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php } ?>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
Hello <?php echo $this->getSession('user') ?>
</div>
<div class="fb-like" data-share="true" data-width="450" data-show-faces="true"></div>
<!--- COMMENT BOX --->
<div class="comments" align="center">
<?php echo $this->writeError('error') ?>
<form action="" method="post" >
<!-- YOU NEED TO SEND AN ACTION WORD HERE AND CHECK FOR IT
TO PROCESS POST -->
<input type="hidden" name="action" value="addcomment" />
<textarea rows="4" cols="50" name="comment">Please type a comment if you are logged in...</textarea>
<input type="submit" value="Submit">
</form>
...etc.
I've looked through multiple web articles and stackoverflow answers, however I cannot find the bug in my code. Maybe I've been looking at it too long.
Basically I'm just setting up a simple login for a demonstration, yes I know its inject-able and outdated, this doesn't matter. Basically I'm using a login with sessions and then redirecting the user to secure content when they're logged in. I've also created a script that checks for the session variables, to see if the user is logged in or not. Basically, I'm beating a dead horse and I don't know why this isn't working, could someone please help?
index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome, please log in</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<?PHP require_once"scripts/mysql_connect.php"; // Establish a database connection ?>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<?PHP
echo "<form method='post' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' value='Log In'>
</form>"
?>
</div>
</body>
</html>
checklogin.php:
<!doctype html>
<html>
<head>
<title>Checking login...</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<?php
require_once"scripts/mysql_connect.php";
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
$sql = "SQL";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$active = $row['active'];
$count = mysql_num_rows($result);
// If result matched, table row must be 1 row.
if($count == 1) {
$_SESSION["login"] = "OK";
$_SESSION["aEmail"] = $aEmail;
echo "<h1>Log in successfull!</h1>
<hr><br />
Your details checked out! Redirecting you now...";
// Wait 1 seconds then redirect to the secure content.
header("Location: http://www.website.com/secure_content.php");
} else {
echo "<h1>Log in unsuccessfull!</h1>
<hr><br />
Sorry. It seems your log in detials were incorrect. Please go back and try again.";
// Wait 2 seconds then redirect back to the log in page.
header("Location: http://www.website.com/index.php");
}
exit;
?>
</div>
</body>
</html>
loginstatus.php:
<?php session_start();
if(!(isset($_SESSION["login"]) && $_SESSION["login"] == "OK")) {
header("Location: http://www.website.com/index.php");
exit;
}
?>
Thanks for any help!
In checklogin.php and index.php you need to start the session. Add the following code before <!doctype html>
Add this code:
<?php session_start(); ?>
You forgot to put that line in this file because you are creating a new session during the checks in the database.
Looks like you haven't started the session in the first place. On the top of your page please write the following code:
<?php session_start(); ?>
Now, secondly, I'd suggest you to write your HTML and PHP separately instead of writing your HTML for the form within the echo.
Also, it's better if you add a name to your submit button.
Let me show a sample below.
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<form method='POST' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' name='submit' value='Log In'>
</form>
Now, in your checklogin.php. you should place an isset condition and see if you're getting any POST request.
Try this:
<?php
require_once"scripts/mysql_connect.php";
if (isset($_POST['submit']) { // Add this condition
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
/* Other code */
if($count == 1) {
/* Other code */
} else {
/* Other code */
}
}
Hope this helps.
I have a page (index.php) is a login page so I need to validate a user and redirect to other page but header(Location:"welcome.php"); is not working, the sql query is ok but I only get the message "Login Successful" and the page doest redirect to the other called welcome.php
I'm newbie in PHP so any help is great!
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="favicon.ico">
<title>Login</title>
<link href="bootstrap.min.css" rel="stylesheet">
<link href="signin.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form class="form-signin" role="form" action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<h2 class="form-signin-heading"><center>Bienvenido!</center></h2>
<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
<input type="password" name="password" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label><input type="checkbox" value="remember-me"> Remember me </label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
<?php
$link = mysqli_connect("localhost","root","root","testdb") or die ("error".mysqli_error($link));
$username = $_POST['username'];
$password= $_POST['password'];
if (isset($_POST['username'])) {
$sql = "SELECT * FROM testdb.user WHERE username='$username' and password='$password'";
$result = mysqli_query($link,$sql);
if ($result);
{
$num=mysqli_num_rows($resultado);
}
if($num==1)
{
header("Location: welcome.php");
exit();
}else{
header("Location:wrong.php");
}
mysqli_free_result($result);
mysqli_close();
}
?>
It is because you are sending output before issuing the redirect. You can't change the HTTP headers once you have started printing the body of the HTTP message.
// echo "Login Successful"; // remove this line and all other HTML
header("Location: welcome.php");
exit();
Basically you have to restructure the program so that when the form is submitted you are not sending output to the browser.
Example pseudo code:
if user has submitted the form then
authenticate user
if authentication is successful then
redirect user to welcome.php
else
show login page and error message
else
show login page
thought this might help on top of the real answer that robbmj provided
Create 3 folders...
Views
Models
Controllers
In the Views folder, create a php file called "Login.php"
Inside that php page paste your html form:
<!DOCTYPE html>
<head>
</head>
<body>
<div class="container">
<form class="form-signin" role="form" action="<?=$_SERVER['PHP_SELF']?>/Controllers/Login.php" method="POST">
<h2 class="form-signin-heading"><center>Bienvenido!</center></h2>
<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
<input type="password" name="password" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label><input type="checkbox" value="remember-me"> Remember me </label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
</body>
</html>
Inside your Models folder, create a file called SQLDbContext.php
Inside that file place the code like so:
class SQLDbContext
{
public $link;
public function Connect()
{
$this->link = mysqli_connect( "localhost", "root", "root", "testdb")
or die ( "error" . mysqli_error( $enlace ) );
}
public function __Destruct()
{
mysql_free_result($result);
mysql_close();
}
}
Inside your Models folder, create a file called AuthenticationRepository.php
Inside that file, place the code like so:
require_once( "SqlDbContext.php" );
class AuthenticationRepository extends SQLDbContext
{
public function __Construct()
{
$this->Connect();
}
public function GetUsersByUsernameAndPassword( $username, $password )
{
$sql = "SELECT * FROM testdb.user WHERE username='$username' and password='$password'";
$result = mysqli_query( $this->link, $sql );
return $result;
}
}
Create a Login.php file inside Controllers (You'll notice I changed your action to /Controllers/Login.php in your Login view
Inside that php file, place your logic to login:
require_once( "../Models/AuthenticationRepository.php" );
$authenticationRepository = new AuthenticationRepository();
$username = $_POST[ "username" ];
$password = $_POST[ "password" ];
$usersInDb = $authenticationRepository->GetUsersByUsernameAndPassword( $username, $password );
$num = mysqli_num_rows( $usersInDb );
if( $num == 1 )
{
header("Location: Views/Welcome.php");
}
else
{
// Set a $_SESSION here and in the Views/Login.php check for that $_SESSION being set
header("Location: Views/Login.php");
}
NOTES:
- You will notice that nothing has been echo'd to the screen before a header(...) has been issued.
- You will notice that all logic has been divided up (wrongly but itll get you started).
- YOU STILL NEED TO DO SQL injection checks and validation etc, but i'll leave that for you to do buddy
By doing all of this, you avoid alot of the problems you have at the moment... There is so much you can do here to improve this code, In fact, the above code really isn't too hot either, but it's a step in the right direction... Seperate all of your stuff out... Check out http://www.laravel.com which is an MVC framework made to help you not screw things up too much :)