PHPMailer won´t send emails - php

I´m working on netbeans, on winsows and with xampp. I believe it has something to do with the version of PHPMailer, I see examples with
PHPAutoload.php
but with the version I downloaded from gitHub I don´t see that file. Everything look fine, it does insert into the data base but got to this part of the code
$msg = "Something wrong happened! Please try again!";
I pasted the PHPMailer folder into c:/xampp/htdocs/pojectmail/PHPMailer.
Here is my register.php code
<?php
$msg = "";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if (isset($_POST['submit'])) {
$con = new mysqli('localhost', 'root', '', 'research_phpEmailConfirmation');
$name = $con->real_escape_string($_POST['name']);
$email = $con->real_escape_string($_POST['email']);
$password = $con->real_escape_string($_POST['password']);
$cPassword = $con->real_escape_string($_POST['cPassword']);
if ($name == "" || $email == "" || $password != $cPassword)
$msg = "Please check your inputs!";
else {
$sql = $con->query("SELECT id FROM users WHERE email='$email'");
if ($sql->num_rows > 0) {
$msg = "Email already exists in the database!";
} else {
$token = 'qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM0123456789!$/()*';
$token = str_shuffle($token);
$token = substr($token, 0, 10);
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
$con->query("INSERT INTO users (name,email,password,isEmailConfirmed,token)
VALUES ('$name', '$email', '$hashedPassword', '0', '$token');
");
include_once "PHPMailer/PHPMailer.php";
include_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
$mail->setFrom('hello#codingpassiveincome.com');
$mail->addAddress($email, $name);
$mail->Subject = "Please verify email!";
$mail->isHTML(true);
$mail->Body = "aa";
if ($mail->send()) {
$msg = "You have been registered! Please verify your email!";
} else {
$msg = "Something wrong happened! Please try again!";
}
}
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Register</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<img src="images/logo.png"><br><br>
<?php if ($msg != "") echo $msg . "<br><br>" ?>
<form method="post" action="register.php">
<input class="form-control" name="name" placeholder="Name..."><br>
<input class="form-control" name="email" type="email" placeholder="Email..."><br>
<input class="form-control" name="password" type="password" placeholder="Password..."><br>
<input class="form-control" name="cPassword" type="password" placeholder="Confirm Password..."><br>
<input class="btn btn-primary" type="submit" name="submit" value="Register">
</form>
</div>
</div>
</div>
</body>
</html>

Related

Fatal error: Uncaught PDOException: SQLSTATE[HY093]:

If someone can help me with this, I'm not good with php but I'm trying to learn but this problem I encounter makes my head hurt.
Here's the full error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampp\htdocs\website\register.php:34 Stack trace: #0 C:\xampp\htdocs\website\register.php(34): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\website\register.php on line 34
<?php
include 'config.php';
if(isset($_POST['submit'])){
$name = $_POST['name'];
$name = filter_var($name, FILTER_SANITIZE_STRING);
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_STRING);
$pass = md5($_POST['pass']);
$pass = filter_var($pass, FILTER_SANITIZE_STRING);
$cpass = md5($_POST['cpass']);
$cpass = filter_var($cpass, FILTER_SANITIZE_STRING);
$user_type = $_POST['user_type'];
$image = $_FILES['image']['name'];
$image_tmp_name = $_FILES['image']['tmp_name'];
$image_size = $_FILES['image']['size'];
$image_folder = 'uploaded_img/'.$image;
$select = $conn->prepare("SELECT * FROM `users` WHERE email = ?");
$select->execute([$email]);
if($select->rowCount() > 0){
$message[] = 'user already exist!';
}else{
if($pass != $cpass){
$message[] = 'confirm password not matched!';
}elseif($image_size > 2000000){
$message[] = 'image size is too large!';
}else{
$insert = $conn->prepare("INSERT INTO `users`(name, email, password, image, user_type) VALUES(?,?,?,?)");
$insert->execute([$name, $email, $cpass, $image, $user_type]);
if($insert){
move_uploaded_file($image_tmp_name, $image_folder);
$message[] = 'registered succesfully!';
header('location:login.php');
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>register</title>
<!-- font awesome cdn link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<!-- custom css file link -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php
if(isset($message)){
foreach($message as $message){
echo '
<div class="message">
<span>'.$message.'</span>
<i class="fas fa-times" onclick="this.parentElement.remove();"></i>
</div>
';
}
}
?>
<section class="form-container">
<form action="" method="post" enctype="multipart/form-data">
<h3>register now</h3>
<input type="text" required placeholder="enter your username" class="box" name="name">
<input type="email" required placeholder="enter your email" class="box" name="email">
<input type="password" required placeholder="enter your password" class="box" name="pass">
<input type="password" required placeholder="confirm your password" class="box" name="cpass">
<input type="file" name="image" required class="box" accept="image/jpg, image/png, image/jpeg">
<select name="user_type">
<option value="admin">admin</option>
<option value="user">user</option>
<option value="company">company</option>
<p>already have an account? login now</p>
<input type="submit" value="register now" class="btn" name="submit">
</form>
</section>
</body>
</html>
Change this line:
$insert = $conn->prepare("INSERT INTO `users`(name, email, password, image, user_type)
VALUES(?,?,?,?)");
to:
$insert = $conn->prepare("INSERT INTO `users`(name, email, password, image, user_type)
VALUES(?,?,?,?,?)");
Because you want to use 5 parameters , you also need 5 ? marks.

the login page does not moving me to the welcome page in php

Is this code okay? as I do not receive any errors at all.
session.php
<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to welcome page
if (isset($_SESSION["userid"]) && $_SESSION["userid"] === true) {
header("location: welcome.php");
exit;
}
?>
login.php
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// validate if email is empty
if(empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
// validate if password is empty
if(empty($password)) {
$error .= '<p class="error">Please enter your password.</p>';
}
if(empty($error)) {
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s', $email);
$query->execute();
$row = $query->fetch();
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$_SESSION["user"] = $row;
// Redirect the user to welcome page
header("location: welcome.php");
exit;
} else {
$error .= '<p class="error">The password is not valid.';
}
} else {
$error .= '<p class="error">No User exist with that email address.';
}
}
$query->close();
}
// Close connection
mysqli_close($db);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Login</h2>
<p>Please fill in your email and password.</p>
<form action="" method="post">
<div class="form-group">
<label>Email Address</label>
<input type="email" name="email" class="form-control" required />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<p>Don't have an account? Register here.</p>
</form>
</div>
</div>
</div>
</body>
</html>
welcome.php
<?php
// start the session
session_start();
// Check if the user is not logged in, then redirect the user to login page
if (!isset($_SESSION["userid"]) || $_SESSION["userid"] !== true) {
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome <?php echo $_SESSION["name"]; ?></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Hello, <strong><?php echo $_SESSION["name"]; ?></strong>. Welcome to demo site.</h1>
</div>
<p>
Log Out
</p>
</div>
</div>
</body>
</html>
welcome.php changed to -
<?php
// start the session
session_start();
// Check if the user is not logged in, then redirect the user to login page
if (empty($_SESSION['user'])) {
header("location: login.php");
exit;
}
?>
session.php changed to =
<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to welcome page
if (empty($_SESSION['user']) === false) {
header("location: welcome.php");
exit;
}
?>
register.php -
<?php
require_once "config.php";
require_once "session.php";
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['submit'])) {
$fullname = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$error = '';
$query->bind_param('s', $email);
$query->execute();
$query->store_result();
if ($query->num_rows > 0) {
$error .= '<p class="error">The email address is already registered!</p>';
} else {
if (strlen($password ) < 6) {
$error .= '<p class="error>Password must have atleast 6 characters.</p>';
}
// Validate confirm password
if (empty($confirm_password)) {
$error .= '<p class="error">Please enter confirm password.</p>';
} else {
if (empty($error) && ($password != $confirm_password)) {
$error .= '<p class="error">Password did not match.</p>';
}
}
if (empty($error) ) {
$insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
$insertQuery->bind_param("sss", $fullname, $email, $password_hash);
$result = $insertQuery->execute();
if ($result) {
$error .= '<p class="success">Your registration was successful!</p>';
} else {
$error .= '<p class="error">Something went wrong!</p>';
}
}
}
}
$query->close();
$insertQuery->close();
// Close DB connection
mysqli_close($db);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Register</h2>
<p>Please fill this form to create an account.</p>
<form action="" method="POST">
<div class="form-group">
<label>Full Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group">
<label>Email Address</label>
<input type="email" name="email" class="form-control" required />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<p>Already have an account? Login Here.</p>
</form>
</div>
</div>
</div>
</body>
</html>
logout.php -
<?php
// Start the session
session_start();
// Destroy the session.
if (session_destroy()) {
// redirect to the login page
header("Location: login.php");
exit;
}
?>
config.php
<?php
define('DBSERVER', 'localhost'); // Database server
define('DBUSERNAME', 'root'); // Database username
define('DBPASSWORD', ''); // Database password
define('DBNAME', 'demo'); // Database name
/* connect to MySQL database */
$db = mysqli_connect(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
// check db connection
if($db === false){
die("Error: connection error. " . mysqli_connect_error());
}
?>
db.sql - that connects to the server verifed it adds to the database using phpmyadmin so the registration is working.
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(75) NOT NULL,
`password` varchar(7255) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
EDIT: added the changes to the session.php + welcome.php + added the whole files of the whole code.

no change to the page after clicking log in button?

creating a log in page using php and PDO however once I fill out the form with the correct username and password to log into the system and click log in, nothing changes except the boxes are now empty as if I never entered a username and password, can someone advise me as to what is going wrong?
this is the php code:
<?php
session_start();
$server = "127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$db = "movie1";
$message = "";
try
{
$handle = new PDO("mysql:host=$server; dbname=$db", $dbusername, $dbpassword);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
}
else
{
$query = "SELECT * FROM register WHERE username = :username AND password = :password";
$statement = $handle->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:login_success.php");
}
else
{
$message = 'Wrong Data';
}
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
?>
and this is the html form to which it applies to:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>log in</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<form class="w3-container w3-card-4" action="login.php" method="post">
<h2 class="w3-text-black">Log in</h2>
<?php
if(isset($message))
{
echo '<label class "text-danger">'.$message.'</label>';
}
?>
<p>
<label class="w3-text-black"><b>username</b></label>
<input class="w3-input w3-border" name="username" type="text" placeholder="username"></p>
<p>
<label class="w3-text-black"><b>Password</b></label>
<input class="w3-input w3-border" name="password" type="text" placeholder="********"></p>
<p>
<input type="submit" name="login" class="w3-btn w3-black">Log in</input>
</p>
<p>
please ignore that passwords are not hashed, I will fix that later. the first image is what the log in form looks like with information entered and the next will be what happens after I click log in (pic one)1
pic two 2
I have made only minor changes to get your script working, see comments below. I think your login_success.php sends the authenticated user back to the login page.
<?php
/* my table in db named 'movie1':
CREATE TABLE `register` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL
);
INSERT INTO `register` (`username`, `password`) VALUES
('User1', '1111'),
('User2', '2222');
*/
session_start();
$server = "127.0.0.1";
$dbusername = "www"; //Changed
$dbpassword = "www"; //Changed
$db = "movie1";
$message = "";
try
{
$handle = new PDO("mysql:host=$server; dbname=$db", $dbusername, $dbpassword);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
$message = '<label>All fields are required</label>';
else
{
$query = "SELECT * FROM register WHERE username = :username AND password = :password";
$statement = $handle->prepare($query);
$statement->execute(
array(
':username' => $_POST["username"], //Inserted colon here
':password' => $_POST["password"] //Inserted colon here
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:FileNotExistAndWillProduce404WhichMeansSuccess.php");//Target changed
}
else
$message = 'Wrong Data';
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>log in</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<form class="w3-container w3-card-4" action="LoginTest.php" method="post"> <!-- action-target changed -->
<h2 class="w3-text-black">Log in</h2>
<?php
if($message>'') //was isset(), changed, because it contains at least an empty string
echo '<label class "text-danger">'.$message.'</label>';
?>
<p>
<label class="w3-text-black"><b>username</b></label>
<input class="w3-input w3-border" name="username" type="text" placeholder="username"></p>
<p>
<label class="w3-text-black"><b>Password</b></label>
<input class="w3-input w3-border" name="password" type="text" placeholder="********"></p>
<p>
<input type="submit" name="login" class="w3-btn w3-black">Log in</input>
</p>
</form></body></html>

PHP/HTML help, not logging in

The database is set up correctly but I the error handler when I dont enter a username or password is not working. I always get Invalid username and/or password
The following code doesn't go the the "loginhandler.php" link
Any ideas to why?
No matter the input the code executes`
<!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>
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<?php
$okay = FALSE;
$username = ($_POST['username']);
$password = ($_POST['password']);
$onError = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['username'])) {
$onError = 'Please Enter your Username';
$okay = FALSE;
}
if (empty($_POST['password'])) {
$onError = 'Please Enter your password';
$okay = FALSE;
}
if($okay == FALSE)
{
$dbc = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('db_name', $dbc);
$query = "SELECT * FROM signup WHERE username = '" . $username . "' AND password='" . $password . "'";
if ($result = mysql_query($query, $dbc)) {// Run the query.
while ($row = mysql_fetch_array($result)) {
$okay = true;
}
} else {
}
}
if ($okay) {
// session_start();
$_SESSION['username'] = $username;
header('Loction: loginhandler.php');
exit() ;
} else {
$onError = "Invalid username and/or password";
}
}
?>
<!-- Begin Page Content -->
<div id="container">
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<div class="error"><?php echo $onError; ?></div>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
<p>Click here to Signup.</p>;
</div><!--/ lower-->
</form>
</div><!--/ container-->
<!-- End Page Content -->
</body>
</html>`
$onError = "Invalid username and/or password";
First, you are using session. add session_start() at the top of the page.
header('Location: loginhandler.php'); you wrote Location wrong.
if($okay == FALSE) Should be if($okay == TRUE)
And you alweyes getting the invalid message because you have "$onError = "Invalid username and/or password";" at the bottom of the code outside any PHP tags.

Creating a very simple 1 username/password login in php

I want to make a single login for just 1 user without storing in a database but I can't seem to get this to work.
My code: login.php
<html>
<head>
<title>Login</title>
</head>
<h3>Add entry</h3>
<p> Add another Article</p>
<form action="trylog.php" method = "post">
<label for="username">Username</label> <input type="username" id="usename" name="username"><br /><br />
<label for="password">Password:</label> <input type="text" id="password" name="password"><br /><br />
<button type = "submit">Login</button>
</form>
</html>
trylog.php
<html>
<title>Login</title>
<body>
<?php
$usr = "admin";
$psw = "password";
$username = '$_POST[username]';
$password = '$_POST[password]';
//$usr == $username && $psw == $password
session_start();
if ($_SESSION['login']==true || ($_POST['username']=="admin" && $_POST['password']=="password")) {
echo "password accepted";
$_SESSION['login']=true;
}else {
echo "incorrect login";
}
?>
<form name="input" action="adminportal.php" method="get">
<input type="submit" value="Home">
</form>
</body>
</html>
Your code could look more like:
<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
$validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
if(!$validUser) $errorMsg = "Invalid username or password.";
else $_SESSION["login"] = true;
}
if($validUser) {
header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Login</title>
</head>
<body>
<form name="input" action="" method="post">
<label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
<label for="password">Password:</label><input type="password" value="" id="password" name="password" />
<div class="error"><?= $errorMsg ?></div>
<input type="submit" value="Home" name="sub" />
</form>
</body>
</html>
Now, when the page is redirected based on the header('LOCATION:wherever.php), put session_start() at the top of the page and test to make sure $_SESSION['login'] === true. Remember that == would be true if $_SESSION['login'] == 1 as well.
Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.
Here is a simple php script for login and a page that can only be accessed by logged in users.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php ( only logged in users can access it )
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
This is admin page view able only by logged in users.
</body>
</html>
Firstly, you need to put session_start(); before any output to the browser, normally at the top of the page. Have a look at the manual.
Second, this won't affect your results, but these lines aren't being used anywhere and should be removed:
$usr = "admin";
$psw = "password";
$username = '$_POST[username]';
$password = '$_POST[password]';
...and the last two lines there wouldn't work, you need to put the quotes inside the square brackets:
$username = $_POST['username'];
If you put session_start() at the top of your page (i.e. before the <html> tag etc), this should work fine.
Your code could look more like:
<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
}
if($username !== 'admin')$userError = 'Invalid Username';
if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<style type='text.css'>
#import common.css;
</style>
</head>
<body>
<form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
<label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
<div class='error'><?php echo $userError;?></div>
<label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
<div class='error'><?php echo $passError;?></div>
<input type='submit' value='Home' name='sub' />
</form>
<script type='text/javascript' src='common.js'></script>
</body>
</html>
<?php
session_start();
mysql_connect('localhost','root','');
mysql_select_db('database name goes here');
$error_msg=NULL;
//log out code
if(isset($_REQUEST['logout'])){
unset($_SESSION['user']);
unset($_SESSION['username']);
unset($_SESSION['id']);
unset($_SESSION['role']);
session_destroy();
}
//
if(!empty($_POST['submit'])){
if(empty($_POST['username']))
$error_msg='please enter username';
if(empty($_POST['password']))
$error_msg='please enter password';
if(empty($error_msg)){
$sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
$sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
$records=mysql_query($sql) or die(mysql_error());
if($record_new=mysql_fetch_array($records)){
$_SESSION['user']=$record_new;
$_SESSION['id']=$record_new['id'];
$_SESSION['username']=$record_new['username'];
$_SESSION['role']=$record_new['role'];
header('location:index.php');
$error_msg='welcome';
exit();
}else{
$error_msg='invalid details';
}
}
}
?>
// replace the location with whatever page u want the user to visit when he/she log in

Categories