When I log in I am using the mysql.user but I can't log on if the user has a password. If i logged on using any user a with password the page can't logged on to the other php.
The user inputted on the log in will be use on the connection for the database.
<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<title>Log in</title>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/structure.css">
<?php include('connection.php'); ?>
</head>
<body>
<form class="box login" method="post">
<fieldset class="boxBody">
<label>Username</label>
<input type="text" tabindex="1" placeholder="Username" required name="username" id="username">
<label><label class="rLink" tabindex="5">Optional</label>Password</label>
<input type="password" tabindex="2" placeholder="Password" name="password" id="password" >
</fieldset>
<footer>
<input type="submit" class="btnLogin" value="Login" tabindex="4" name="sent">
</footer>
</form>
<?php
if (isset($_POST['sent'])) {
$servername = "localhost";
$username = ($_POST['username']);
$password = ($_POST['password']);
$message="";
// Create connection
$result = $conn->query("SELECT user FROM mysql.user where user='$username' and password='$password'");
if ($result->num_rows > 0) {
$_SESSION["uname"] = "$username";
$_SESSION["pass"] = "$password";
echo '<script type="text/javascript">alert(<?php echo "Success!";?>)</script>';
header("location: main.php");
} else {
$message = "Successfuly entered! hi! $username";
echo '<script type="text/javascript">alert(<?php echo "$message";?>)</script>';
}
}
// Check connection
?>
</body>
</html>
You'd better check for database errors that might happen here
$conn->query("SELECT user FROM mysql.user where user='$username' and password='$password'");
Check if the query executes first.
Its also better to use this one
"SELECT * FROM mysql.user WHERE user= ?"
After checking row count. You can hash current password with user's salt then check if they are equal.
For more security use prepared statements.And check if $_POST['username'] and $_POST['password'] are set too (even if your input fields are "required")
And for echoing your errors you can have a paragraph with error id
<p id="error"></p>
And echo this one
'<script>
document.getElementById("error").innerHTML = "'.$error.'"
</script>'
My first answer sorry for bad English.
Related
So I have a custom Login page on Wordpress that connects to my users database and checks if all the information is correct. This is the login.php:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['email'])){
// removes backslashes
$email = stripslashes($_REQUEST['email']);
//escapes special characters in a string
$email = mysqli_real_escape_string($conn,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password)."'";
$result = mysqli_query($conn,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<h3>Email/password is incorrect.</h3>
<br/>Click here to <a href='../login/'>Login</a></div>";
}
}else{
?>
<div class="form">
<!-- <h1>Log In</h1> -->
<form action="" method="post" name="login">
<input type="text" name="email" placeholder="Email" required />
<input type="password" name="password" placeholder="Password" required />
<br>
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='../register/'>Register Here</a></p>
</div>
<?php } ?>
</body>
</html>
What I want to do is change the LOGIN button on my Wordpress header to LOGOUT (and showing the user information if it's possible) after the user is logged, and I suppose that I can do that using the $_SESSION['email'] = $email;variable.
How can I do that?
Thanks a lot!
You can use the built-in WordPress function is_user_logged_in() or is your login using also a custom table in the database and not the WordPress user table wp_user?
<?php
if ( is_user_logged_in() ) {
echo 'Login out';
} else {
echo 'Login';
}
?>
If your login system is independent of WordPress, you need to check your login function and see what session variables it creates, you might also need to start the session your self then if it is not in the function something like this then
session_start();
if (isset($_SESSION['email'])) {
/// your login button code here
} else {
/// your logout button code here
}
A function that would add it to your wordpress menu you need to style it:
add_filter('wp_nav_menu_items', 'button_login_logout', 10, 2);
function button_login_logout() {
ob_start();
if (isset($_SESSION['email'])) :
?>
<a role="button" href="logoutlink">Log Out</a>.
<?php
else :
?>
<a role="button" href="loginlink">Log In</a>
<?php
endif;
return ob_get_clean();
}
I just uploaded my site to my domain and now when I try to login on my site I get this notification:
"Query virker ikke (Query does not work) SELECT * FROM user WHERE username = '' AND password = 'b28372e4029d6a7ddc73851afa1781153a365df4654190cf7d1bfcbe5b5df5fabd42d2a89bb1d2a7eeeac384cf1e849924e36acf1ecbe52e617a9ee1190bbccf'"
It looks as it is my hashed password there is in the way.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="https://fonts.googleapis.com/css?family=Emilys+Candy&display=swap" rel="stylesheet">
<!-- Mine style -->
<link rel="stylesheet" href="css/main-style.css">
</head>
<body class="index-body">
<?php include 'inc/db.php'?>
<?php
$output ="";
if(isset($_POST['submit'])){
$userName = mysqli_real_escape_string($conn, $_POST['username']);
$pass = mysqli_real_escape_string($conn, $_POST['password']);
$salt = "ldfjldjf34lksdf4kle" . $pass . "dkj2fldsjljf34elk";
$hashed = hash('sha512', $salt);
$sql = "SELECT * FROM user WHERE username = '$userName' AND password = '$hashed'";
$result = mysqli_query($conn, $sql) or die ("Query virker ikke " . $sql);
if(mysqli_num_rows($result) == 1){
session_start();
$_SESSION['username'] = $userName;
$_SESSION['adgang'] = 'adgang';
echo "<script>window.location.href='gamesite.php';</script>";
} else {
$output = "Wrong login";
}
}
?>
<div class="container">
<div class="row">
<img class="col-3" src="img/logo.png" alt="">
</div>
</div>
<center>
<div class="container con-index">
<h1 class="space-to-nav con-log">Login</h1>
<form method="POST">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control col-4" name="username" placeholder="Username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control col-4" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-light" name="submit">Submit</button>
<h3 class="space-to-nav"><?= $output ?></h3> <!-- = istedet for php echo -->
</form>
<p class="space-to-nav">Do not have an account? Create account here</p>
</div>
</center>
<?php include 'inc/footer.php'?>
Check out the php Version on the Server.
Hashing with a custom salt is no longer best practice in php >7
Warning The salt option has been deprecated as of PHP 7.0.0. It is now
preferred to simply use the salt that is generated by default.
try password_hash and password_verify
check out https://www.php.net/manual/en/function.password-hash.php
I have 2 files one called 'index.html' and the other called 'student.php'. The index.html code is displayed below:
<!DOCTYPE html>
<html>
<head>
<title>insert data in database using mysqli</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<Form Name ="form1" Method ="POST" ACTION = "student.php">
<!--<form action="" method="post"> -->
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="city" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
<!-- Right side div -->
</div>
</div>
</body>
</html>
student.php:
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (student_name, student_email, student_city)
VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
Once i enter the student name, email and address i click on the submit button. the following error appears on the next page: Cannot POST /http-services/emulator-webserver/ripple/userapp/x/C/xampp/htdocs/xampp/please/www/student.php. I have tested the database connection before and the application is able to connect to the database so this isn't an issue. Is there something wrong with my code?
You need to connect the html code to a PHP script by AJAX. whit JSON to transfer the data.
in this video is how to make it work.
https://www.youtube.com/watch?v=NxCeoiouaLs
I have a login php form, when the user types the incorrect credentials then it will output "Incorrect Username or Password" however this is put right at the top of the website above the navigation. Here is a screenshot : http://imgur.com/IAsaMWH
I would like to have the text placed inside the website wrapper and within a div so that i can edit it with css.
I have tried using document.getElementById('log').innerHTML however this only works when the div "log" is above the php code, however the php has to stay at the top because otherwise I get a error:
Warning: session_start(): Cannot send session cache limiter - headers
already sent
Here is my php/js
In short, all i would like to do is when the login credentials are wrong a message is shown to the user "Incorrect Username or Password" This message i need to be editable with CSS, as i need to reposition it on the page.
If anybody would please be able to edit my code and explain to me what they have done - it would be hugely appreciated.
Here is my PHP with JS:
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!="")
{
header("Location: account.php");
}
if(isset($_POST['btn-login']))
{
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res=mysql_query("SELECT * FROM users WHERE email='$email'");
$row=mysql_fetch_array($res);
if($row['password']==md5($upass))
{
$_SESSION['user'] = $row['user_id'];
header("Location: account.php");
}
else
{
?>
<script>document.write('Incorrect Username or Password');</script>
<?php
}
}
?>
Here is my HTML
<?php include"authentication/login.php";?>
<!DOCTYPE html>
<html>
<HEAD>
<title>Website | Loign</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<?php include "includes/page_sources.php"; ?>
</HEAD>
<body>
<?php include "includes/navigation.php"; ?>
<div id="wrapper">
<div id="login-form">
<form method="post">
<input type="text" name="email" placeholder="Your Email" required />
<input type="password" name="pass" placeholder="Your Password" required />
<button type="submit" name="btn-login">Log In</button>
Sign Up
</form>
</div>
</div>
<?php include "includes/footer.php"; ?>
</body>
</html>
Thank you once again for any help in advance
There's all kinds of wrong in your example. It doesn't matter where yo put your PHP code: if you want to append something to some sort of a div - then delay that until the dom loads. You'd be better off using jquery or something that had a "domReady" function available, but you can do without it as well. Instead of your document.write script you could just say:
window.onload = function() { document.getElementById('something').innerHTML = 'some html'; };
The above line would wait for the document to be loaded and it would now be able to find the div even if php code is above everything else.
It is really very easy do it in this way
PHP File:
<?php
session_start();
include_once 'dbconnect.php';
$error="no";
if(isset($_SESSION['user'])!="")
{
header("Location: account.php");
}
if(isset($_POST['btn-login']))
{
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res=mysql_query("SELECT * FROM users WHERE email='$email'");
$row=mysql_fetch_array($res);
if($row['password']==md5($upass))
{
$_SESSION['user'] = $row['user_id'];
header("Location: account.php");
}
else
{
$error="yes";
}
}
?>
HTML:
<?php include"authentication/login.php";?>
<!DOCTYPE html>
<html>
<HEAD>
<title>Website | Loign</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<?php include "includes/page_sources.php"; ?>
</HEAD>
<body>
<?php include "includes/navigation.php"; ?>
<div id="wrapper">
<div id="login-form">
<form method="post">
<?php if($error=="yes") echo 'Incorrect Username or Password';?>
<input type="text" name="email" placeholder="Your Email" required />
<input type="password" name="pass" placeholder="Your Password" required />
<button type="submit" name="btn-login">Log In</button>
Sign Up
</form>
</div>
</div>
<?php include "includes/footer.php"; ?>
</body>
</html>
The program below contains various error messages to be displayed under certain conditions. These conditions are found through PHP code, after which the necessary JQuery script is echoed in PHP to make the messages appear.
At first, all messages in the .warning class are hidden. Then, if a certain condition is met, particular ids of this class are shown. Below is the relevant code.
<?php require_once 'connection.php'; ?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Create Account</title>
<link rel="stylesheet" type="text/css" href="Styles2.css">
<script src="JQuery.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$('.warning').hide();
});
</script>
<div class="unloggedheadingbar">
</div>
<br>
<div class="createaccount">
<center><h1>Create Account</h1></center>
<center><table>
<form action="create_account.php" method="post">
<tr><td><font class="createaccountfont">Email</font></td><td><input type="text" name="Email" placeholder="someone#somewhere.com" value="<?php if(isset($_POST['Create'])){ echo $_POST['Email']; } ?>" class="createaccounttext"></td></tr>
<tr><td colspan="2"><br></td></tr>
<tr><td><font class="createaccountfont">Password</font></td><td><input type="password" name="Password" class="createaccounttext"></td></tr>
<tr><td colspan="2"><br></td></tr>
<tr><td><font class="createaccountfont">Confirm Password </font></td><td><input type="password" name="ConfirmPassword" class="createaccounttext"></td></tr>
</table></center>
<br>
<center><input type="submit" name="Create" value="Create Account" class="createButton" id="Create"></center>
</form>
<br>
<div class="warning" id="passwordMatchError">
<center><font class="warningText">Your password confirmation must match with your original password!</font></center>
</div>
<div class="warning" id="emailFormatError">
<center><font class="warningText">Your email must match the someone#something.com format.</font></center>
</div>
<div class="warning" id="emailDuplicateError">
<center><font class="warningText">An account under this email already exists.</font></center>
</div>
</div>
<?php
if(isset($_POST['Create'])){
$email = $_POST['Email'];
$password = md5($_POST['Password']);
if(strpos($email, '#') !== TRUE){
echo '<script>
$(".warning").hide();
$("#emailFormatError").show();
</script>';
}elseif($_POST['Password'] != $_POST['ConfirmPassword']){
echo '<script>
$(".warning").hide();
$("#passwordMatchError").show();
</script>';
}else{
$query = "SELECT * FROM user_table WHERE Email = '" . $email . "';";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0){
$query = "INSERT INTO user_table VALUES ('" . $email . "', '" . $password . "');";
mysqli_query($con, $query);
}else{
echo '<script>
$(".warning").hide();
$("#emailDuplicateError").show();
</script>';
}
}
}
?>
</body>
However, the objects with particular IDs are not actually shown. Does anyone know why this may be? Thank you.
jQuery actions should be placed in $( document ).ready( function () {} );, i.e.:
echo '<script>$( document ).ready( function () {
$(".warning").hide();
$("#emailFormatError").show();
} );</script>';