Styling text by outputted document.write - javascript

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>

Related

How to change Login to Logout button on wordpress using $_SESSION?

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();
}

Changing site title server-side

How can I change a web page title for everyone on that site and not to be changed with refreshing, using javascript or PHP?
I've tried HTML DOM title but it gets back to its first title after refreshing.
I've tried giving variable in PHP and changing it by after a button pressed but the title didn't change!
These were my codes:
<?php
$title = "Chat";
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="chat_messages"></div>
<form enctype="multipart/form-data" method="post">
<input onClick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
<?php
if(isset($_POST['send'])){
$title = "new message";
}
?>
</body>
</html>
Any idea what should I do?
Glad to help.
Of course the title won't change, because php reads your code from 1st line to the end, and you have already added $title = "Chat";
what to do is to change the code like this:
<?php
if(isset($_POST['send'])) $title = "new message";
else $title = "Chat";
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="chat_messages"></div>
<form enctype="multipart/form-data" method="post">
<input onClick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
</body>
</html>
This will change the title.
Also, if you want to change the title without refreshing the page, you need JS.
Just use
document.title = '***'; //use your title to replace "***"!
Have a good day~
There are some mistakes in your code like you have used onClick instead you should use onclick
you have not putted a semicolon ; while you are typing
You have not assigned action to your form
Action will be echo htmlspecialchars($_SERVER['PHP_SELF'])
And we will use if else
This will work
<?php
if (isset($_POST['send'])) {
$title = "new message";
} else {
$title = "Chat";
}
?>
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<div id="chat_messages"></div>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" enctype="multipart/form-data" method="post">
<input onclick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
</body>
</html>
I hope this will Help you

How to get the value of mysql.user password

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.

Cannot Use Session Variable To Store Data

I have the a php file that contains the following
an html file which is used to collect data for a new user
php functions that validate the input data
javascript codes that alerts and prompt the user before data submission
after the validation process I want to move the input data to an insert.php to insert data into the database.
Below is the code
<?PHP
session_start();
if (!(isset($_SESSION['login_user']) && $_SESSION['login_user'] != '')) {
header ("Location: loginForm.php");
}
$hash;
$salt;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="layout.css">
<script language="javascript" type="text/javascript" src="/templates/myjavascript.js"></script>
<title>Title of the document</title>
<script>
window.onload=function(){
document.getElementById("new_user_form").onsubmit=function(){
if(this.pword.value === this.pword2.value)
{ alert("Are you sure you want to create a new user")
return true;}
else{ alert("Paswords must be the same ");
return false;}
}
}
</script>
</head>
<div>
<body>
<section id="content">
<form align="center" class="form" action="create_user.php" method="post" id="new_user_form" name="new_user_form">
<ul>
<li>
<h2>Please Fill The Form</h2>
</li>
<li>
<label for="username">User Name</label>
<input name="username" id="keyword" type="text" placeholder="type first name (required)" required />
</li>
<li>
<label for="pword">Password</label>
<input name="pword" id="pword" type="password" placeholder="########" required />
</li>
<li>
<label for="pword2">Confirm Password</label>
<input name="pword2" id="pword2" type="password" placeholder="########" required />
</li>
<p>
<input type = "reset" class="reset" name="submit"/>
<input type ="submit" name="submit" value="submit" class="submit" "/>
</p>
</section>
</ul>
</form>
</body>
</div>
<?php
/* php function to check pasword policy
The password has to be alphanumeric and special characters minimum 8 and max 16
*/
function checkpwdPolicy(){
if($_POST['pword'] === $_POST['pword2']) {
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,16}$/', $_POST['pword'])) {
echo '<script> alert(" password requirement not met"); </script>';
} else{
/* we use the session varible to store the hashed password and username */
/
$_SESSION['pwd'] = password_hash($_POST['pword'], PASSWORD_DEFAULT);
$_SESSION['username'] = $_POST['username'];
header ("Location: insert_user_table.php");
}
}
else {echo "passwords do not match "; }
}
//tis is used to call the fucntion that checks the password policy
if(isset($_POST['submit']) && isset($_POST['username']) && isset($_POST['pword']) && isset($_POST['pword2']) )
{checkpwdPolicy();}
?>
</html>
How ever when I run the cod I get the following error displayed.
Below is the error.
The question is how to move the data to the file that will do the insertion of data into database.
if you put any thing or show anything before session start command as well as before header("location: url"). it will not work.
simply
put "session_start();" top of the page.
dont show or use echo before header("Location: url");
another answer: header location not working in my php code
change your
<?PHP
to
<?php
remove spaces before it if any
session_start();
//remove this line
if (!(isset($_SESSION['login_user']) && $_SESSION['login_user'] != '')) {
//remove this line
header ("Location: loginForm.php");
//remove this line
}
remove spaces in between the above code.
or try this in place of your header
<script type="text/javascript">
window.location.assign('loginForm.php');
</script>
you need to start session at the beginning to avoid this warning message.
session_start();

Login form using PHP and JQuery to validate login information from MySQL database

I have a login form that uses JQuery and PHP to validate a username and password. I am trying to switch over from extension mysql to mysqli for better practice and am having a lot of trouble. I think the error exists in the JQuery somewhere because I've tested the login.php validation and it works fine.
So here is my code:
index.php:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true'){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
},
beforeSend:function(){
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){ ?>
<a href='logout_script_2.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<form action="login_script_2.php" method="POST">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
<div class="err" id="add_err"><br></div>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$con = mysqli_connect("localhost","root","PW","db") or die("Connection error: " . mysqli_error($con));
if(isset($_POST['submit'])){
$username = $_POST['name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
if($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
echo 'Access granted';
exit();
}
}
else {
echo "*Wrong username or password";
}
$stmt->close();
}
else {
}
$con->close();
?>
logout.php
<?php
session_start();
unset($_SESSION['user_name']);
header('Location: index.php');
?>
All the attempts to run the code give me the error in the JQuery validation "*Wrong username or password". Thanks in advanced!
When logging in using ajax, you are not posting submit, so this line
if(isset($_POST['submit'])){
is never true so your code never executes.
Either change it to
if(isset($_POST['name'])){
or add it to your ajax posted data
data: "submit=true&name="+username+"&pwd="+password,
AJAX is a partial submission. Make sure you're firing it without using a submit button, or return false; inside your click function, at the bottom. I would use <input type='button' id='login_a' />, if it's not a link. Additionally, you are not setting your submit button, like #Sean said, because it's AJAX.

Categories