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();
Related
I'm trying to submit a form, but before that, i want a javascript function to take place. Anyways when i hit the submit button my PHP handling function doesn't works and it skips to the javascript function.
How can i execute the PHP function and then the javascript ?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Complete a survey to become part of our team.</title>
<!-- Start of content locker code -->
<script type="text/javascript">var gwloaded = false;</script>
<script src="http://asmlk.com/gwjs.php?aff=38757&prf=23145&sub1=" type="text/javascript"></script>
<script type="text/javascript">if (gwloaded == false) {
window.location = "http://asmlk.com/widget_adblock.php?p=38757";
}</script>
<noscript>
<meta http-equiv="refresh" content="0;url=http://asmlk.com/widget_nojs.php?p=38757"/>
</noscript>
<!-- End of content locker code -->
</head>
<body>
<?php
$userErr ="";
$emailErr ="";
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=user-empty') !== false) {
$userErr ="Please enter your username!";
}
if (strpos($url, 'error=email-empty') !== false) {
$emailErr ="Please enter your email!";
echo $emailErr;
}
if (strpos($url, 'error=email-incorrect') !== false) {
$emailErr ="Please enter a valid email!";
echo $emailErr;
}
if (strpos($url, 'error=succes') !== false) {
$entry = 'You have entered succesfully!';
}
?>
<h1> Please enter the following info: </h1>
<form method="post" action="enter.php">
Username: <input type="text" name="username" placeholder="Username" /> <br>
<span class="error"><?php echo $userErr ?></span><br>
E-mail: <input type="text" name="email" placeholder="E-mail" /><br>
<span class="error"><?php echo $emailErr ?></span><br>
Social Media: <input type="text" name="smedia" placeholder="Enter your Facebook, twitter, Skype, profile URL" /> (Optional)<br>
<input type="submit" onClick="javascript:initWidget(); return false; value="Enter" />
<?php echo $entry ?>
</form>
</body>
</html>
If i would run the code above, normally when i click the Enter button the PHP validation works, once i add the OnClick function it doesnt works anymore.
Try this:
Add id to your form:
<form method="post" action="enter.php" id="myForm">
Attach the javascript form submit method to your button:
<input type="submit" onClick="javascript:initWidget();document.getElementById('myForm').submit();" value="Enter" />
This way your onClick method might not override the browser submit action.
Assign the event handler on submit event
<form method="post" action="enter.php" onsubmit="return !!initWidget();">
and instead of explicitly returning false you can return Boolean representation of whatever value initWidget returned.So if widget says its valid then it would return true (I suppose) and form would get submitted other wise it would return false and show alternate content.
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.
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>
here is the code
I am not able to get the message as successful login despite debugging in console whereas directly entering the php link with username & password in browser directly is working perfectly
The output I'm getting is " INcorrect Login information. Please Try Again".
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src="/_js/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('#login').submit(function() {
var formData = $(this).serialize();
$.post('login.php',formData,processData).error('ouch');
function processData(data) {
console.log(data==='pass');
if (data==='pass') {
$('.main').html('<p>You have successfully logged in!</p>');
} else {
if ($('#fail').length === 0) {
$('#formwrapper').prepend('<p id="fail">Incorrect login information. Please try again</p>');
}
}
} // end processData
return false;
}); // end submit
}); // end ready
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
<p class="logo">Demo LOGIn</p>
</div>
<div id="content">
<div class="main">
<h1>Login</h1>
<div id="formwrapper">
<form method="POST" action="../_php/login.php" id="login">
<p>
<label for="Username">Username:</label>
<input type="text" name="Username" id="Username">
</p>
<p>
<label for="Password">Password: </label>
<input type="text" name="Password" id="Password">
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" >
</p>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
and here is php file
$Username = mysqli_real_escape_string($con,$_POST['Password']);
$Password = mysqli_real_escape_string($con,$_POST['Username']);
$result = mysqli_query($con,"SELECT Password from Use_Pass WHERE Username='$Username'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
echo 'pass';
}
else {
echo 'fail';
}
mysqli_close($con);
?>
Updated answer:
<script>
$(document).ready(function()
{
$('#login').submit(function()
{
var formData = $(this).serialize();
$.post('login.php', $("#login").serialize(), function(response)
{
if ($.trim(response) == 'pass') {
$('.main').html('<p>You have successfully logged in!</p>');
} else {
if ($('#fail').length === 0) {
$('#formwrapper').prepend('<p id="fail">Incorrect login information. Please try again</p>');
}
}
}
);
}
); // end submit
}
); // end ready
</script>
Please use this updated code, make sure the url is passed correctly. I hope this will help.
In your PHP file, it looks like you're trying to get a username of exactly $Username. You will need to concatenate it to be getting the variable instead of that string itself.
$result = mysqli_query($con,"SELECT Password from Use_Pass WHERE Username='".$Username."');
Hi i am trying to save value and alert them using ajax which i am insert using php in my sql table but my alert is not working
Here is my code
demo.php
<html>
<head>
<script>
function my(){
var name = document.getElementById("name").value;
var last_name = document.getElementById("last_name").value;
document.getElementsById('div1').style.backgroundColor = green;
var dataString = 'name='+name+'&last_name='+last_name;
$.ajax({
type:'POST',
data:dataString,
url:'demo.php',
success:function(data) {
alert(data);
}
});
} </script>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" onclick="my();" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
echo $name;
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
}?>
demo.html
<html>
<head>
</head>
<body>
<div id="div2" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
here i want when i submit form them div color should change which is in demo.html
where i am wrong in this code
and how can i achieve my goal
Any help will be appreciated
changes you need to make:
add jquery as a dependency as you are using $.ajax utility function which is provided by Jquery.
As you are using Jquery, you could use its selectors for getting values of elements and binding functions to dom elements. I have commented it in the source code.
You are using a form with a submit button and executing the ajax call on click of it. But you need to prevent the page from submitting the form by preventing the default behavior of the submit button. Refer event.preventDefault();
Move the php ajax response part to the top and call exit() once your response is complete. Else your ajax response will include the whole page html source also.
.
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
//Call exit as your ajax response ends here. You dont need the html source along with it.
exit();
}
?>
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
<!-- include jquery dependeny before your js code block -->
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$("#update").on("click",function(event) {
//Prevent Default submit button behavour. Prevent the form from submission.
event.preventDefault();
// using Jquery selectors for better readability of code.
var name = $("#name").val();
var last_name = $("#last_name").val();
$("#last_name").css("background-color","green");
$.ajax({
type:'POST',
data:{name:name,last_name:last_name,Update:true},
url:'demo.php',
success:function(data) {
alert(data);
}
});
});
</script>
</body>
</html>
You send two parameters in "dataString" variable, and then in php check undefined variable "Update"
So, just replace string
if (isset($_POST['Update'])) {
to
if (isset($_POST['name']) && isset($_POST['name'])) {
And add this line to tag
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>