I have created a login page.In whicn iam unable to link it with the next page after clicking submit button.I want to validate and redirect to the next page.ie home.php.Kindly help me find out what am i missing.
signin.php
<!DOCTYPE html>
<html>
<head>
<script>
function val()
{
var a=document.signin.user.value;
var b=document.signin.password.value;
if ( a == "admin" && b == "rec"){
alert ("Login success");
window.location = "home.php";
return false;
}
else{
alert("login failed")
}
}
</script>
<meta charset="UTF-8">
<title>LIBRARY </title>
</head>
<body>
<div class="body"></div>
<div class="grad"></div>
<div class="header">
<div>REC<span>LIBRARY</span></div>
</div>
<br>
<br>
<br>
<div class="login">
<form name="signin" method="post" onsubmit="val();">
<input type="text" placeholder="username" name="user"><br>
<input type="password" placeholder="password" name="password"><br>
<input type="submit" id="mybutton" value="login"></form>
</div>
</body>
</html>
The problem is the onsubmit event is not having false returned to it, so it posts the form normally, after your JavaScript has finished. Even in the case of successful login and the redirect is executed, the form will still submit and it will override the redirect.
Firstly, Move your return false; to the end of the function, so that it always executes.
Secondly, change your onsubmit="val();" to onsubmit="return val();". This means the onsubmit event will always be returned false and will not try to post the form.
Side note: this is by no means a secure system. Any visitor can simply observe the HTML source to find the password, or just navigate directly to home.php. For a secure system, you will need to do the authentication on the server side (in the PHP).
You could use preventDefault() Event method without using onsubmit=val() like below.
document.getElementById("signin").addEventListener("submit", function(e){
e.preventDefault()
// actual code to validate
});
or
can try some dirty work on server side directly to hide the validation part
<?php
ob_start();
session_start();
loginForm();
$userinfo = array(
'admin'=>'0b2c082c00e002a2f571cbe340644239'
);
if(isset($_POST['username'])){
if($userinfo[$_POST['username']] == md5($_POST['password'])){
$_SESSION['username'] = $_POST['username'];
header('Location: home.php');
exit();
}else{
?>
<script type="text/javascript">
alert("Oops.... User name or Pasword is worng, Please try again");
</script>
<?php
}
}
function loginForm()
{
?>
<form name="login" action="" method="post">
Username: <input type="text" name="username"> <br><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="login">
</form>
<?php
}
?>
Related
I follow up a tutorial to learn more about php, in it's source code there is something which seems works at that time but not anymore. here is the code , please let me know what should i change in the code in order to make login process work (currently after entering a valid user name and pass and clicking login it freezes and show first page and not go to home.php
here is template/header.php:
<div class="container">
<!--Head wrap starts-->
<div id="head_wrap">
<!--Header starts-->
<div id="header">
<img src="images/logo.png" style="float:left;"/>
<form method="post" action="" id="form1">
<strong>Email:</strong>
<input type="email" id="email" name="email" placeholder="Email" required="required" />
<strong>Password:</strong>
<input type="password" id="pass" name="pass" placeholder="****" required="required"/>
<button type="submit" id="login">Login</button>
</form>
</div>
<!--Header ends-->
</div>
here is login.php
<?php
session_start();
include("includes/connection.php");
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con,$_POST['email']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$get_user = "select * from users where user_email='$email' AND user_pass='$pass'";
$run_user = mysqli_query($con,$get_user);
$check = mysqli_num_rows($run_user);
if($check==1){
$email = mysqli_real_escape_string($con,$_POST['email']);
$_SESSION['user_email']=$email;
echo "<script>window.open('home.php','_self')</script>";
}
else {
echo "<script>alert('Passowrd or email is not correct!')</script>";
}
}
?>
please note i have tried
echo "<script> window.location.href = 'home.php';</script>";
instead of
echo "<script>window.open('home.php','_self')</script>";
and still doesn't work, since it's tutorial and i have search through stackoverflow can't find any answer i appreciate your help.
This is your HTML code but with a submit button. You say all files are located in the same folder so this should work. I did not make any changes to login.php but it should run when the page is submitted.
<div class="container">
<!--Head wrap starts-->
<div id="head_wrap">
<!--Header starts-->
<div id="header">
<img src="images/logo.png" style="float:left;"/>
<form method="post" action="login.php" id="form1">
<strong>Email:</strong>
<input type="email" id="email" name="email" placeholder="Email" required="required" />
<strong>Password:</strong>
<input type="password" id="pass" name="pass" placeholder="****" required="required"/>
<input type="submit" id="login" name="login" value="Login">
</form>
</div>
<!--Header ends-->
</div>
</div>
Edit: I can't debug your entire project but after looking over some things I see you are not using the 'name' attribute. When a page is submitted a name/value pair is sent in the $_POST array. If you have no 'name' attribute nothing is sent. Start by adding the 'name' attribute. I have modified the above HTML code to show you how.
You have to use header(...) function but don't forget that your page keep to run at the end. Don't forget to use with die to stop your script. ;)
die(header("Location: home.php"))
or after 5 seconds :
header("refresh: 5; url=home.php");
if($check==1){
$email = mysqli_real_escape_string($con,$_POST['email']);
$_SESSION['user_email']=$email;
return 1;
}
else {
return 0;
}
and javascript check status 1 and 0 then window.location.href and window.open use
Check in your file..
1) header() must be called before any actual output is sent, either by
normal HTML tags, blank lines in a file, or from PHP
2) Combine all your PHP codes and make sure you don't have any spaces
at the beginning of the file.
3) after header('location: home.php'); add exit();
4) after sesssion_start() add ob_start();
I am trying to validate if the correct form is being sent with isset(), but this validation is not TRUE when a javascript delay is being applied. How come? What is the best way to check if the correct form was submitted via the POST method? See my code below. Maybe a hidden field would do the trick, but I actually really would like to know why the below code is not going through.
<script type="text/javascript">
window.addEventListener('load', function onload(){
var ccform = document.getElementById('cc_form');
if(ccform){
ccform.addEventListener('submit', function before_submit(e){
setTimeout(function wait(){
// After waiting, submit the form.
ccform.submit();
}, 2000);
// Block the form from submitting.
e.preventDefault();
});
}
});
</script>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cc_form_submit'])) {
//Send the form
//Not working
echo 'ready to send!';
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Send the form
//Working
echo 'ready to send without ISSET!';
}
?>
<form action="" method="post" class="cc_form" id="cc_form">
<button class="cc_form_submit" type="submit" name="cc_form_submit">Send!</button>
</form>
In your example, there are so many possible solutions:
Solution 1:
You can use a hidden value inside your form and then check this value in isset() method like:
<form method="post">
<input type="hidden" name="form1" />
<button>Submit</button>
</form>
<form method="post">
<input type="hidden" name="form2" />
<button>Submit</button>
</form>
<?php
if(isset($_POST['form1'])){
// do somthing
}
if(isset($_POST['form2'])){
// do somthing
}
?>
Solution 2:
You can use input type submit instead of <button> like:
<form method="post">
<input type="submit" name="form1">
</form>
<form method="post">
<input type="submit" name="form2">
</form>
<?php
if(isset($_POST['form1'])){
// do somthing
}
if(isset($_POST['form2'])){
// do somthing
}
?>
Solution 3:
You can use different action for multiple <form> like:
<form method="post" action="form1.php">
</form>
<form method="post" action="form2.php">
</form>
Edit:
As per your comment
don't know why if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cc_form_submit'])) { is not working.
Its not working because, you are using name= attribute with <button>, in this case solution 2 will work for you.
My window.location does not redirect the page to the required location. The same code with window.open works. The else statement also executes when the user name and password are incorrect. When the correct username and password is entered, it just refreshes the same page.
<div class="login" style="position:relative;top:200px;">
<form name="login" method="post">
<p align="middle">Please login to continue </p><p align="middle"><input type="text" name="login" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle"><input type="submit" onclick ="return check(this.form)" value="Login" name="commit"></p>
</form>
<script language="javascript">
function check(form) {
if(form.login.value == "admin" && form.pwd.value == "sysadmin") {
window.location('alumni.html');
}
else {
alert("Ten thousand thundering typhoons! What is the blasted password?");
}
}
</script>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
You can also try with
window.location = 'http://www.yoururl.com/alumni.html';
or directly
window.location = 'alumni.html';
There is a good question about redirect in javascript here: How do I redirect with Javascript?
[EDIT #1]
Although I think that is not the main problem. I believe you can not validate the way you are doing it. In the form there is an attribute called action as explained in http://www.w3schools.com/tags/att_form_action.asp
Then in the page you load, you validate the parameters and decide if its right or not, where you redirect to one page if its right, or to another if it's wrong.
Or you can also load the page and if validation is right, stay in the page and if it's wrong redirect to the login page.
That's one way to do it, probably there is another one better.
[EDIT #2]
What I would personally do is to process the form in a PHP page, it's much easier and simpler. Could be like:
in the HTML:
<div class="login" style="position:relative;top:200px;">
<form name="login" action="myPhpPage.php" method="post">
<p align="middle">Please login to continue </p>
<p align="middle"><input type="text" name="login" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle">
<input type="submit" onclick ="" value="Login" name="commit"></p>
</form>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
In the PHP page:
$name = $_POST['login']; // it's $_post because you are sending the form with method = post
$pass = $_POST['pwd'];
if($name == "admin" && $pass == "sysadmin"){
//go to one page or stay here
} else{
// redirect to another page
}
window.location is a read only property:
The Window.location read-only property returns a Location object with information about the current location of the document.
MDN on window.location
try this: window.location.replace("http://stackoverflow.com");
Here's a working code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Login Redirection Test</title>
<script>
function validateForm() {
var un = document.forms["login"]["user"].value;
var pw = document.forms["login"]["pwd"].value;
if (un == "admin" && pw=="sysadmin") {
window.location.assign="https://stackoverflow.com";
return false;
}else {
alert("Ten thousand thundering typhoons! What is the blasted password?");
}
}
</script>
</head>
<body>
<div class="login" style="position:relative;top:200px;">
<form name="login" onsubmit="return validateForm()" method="post">
<p align="middle">Please login to continue </p><p align="middle"><input type="text" name="user" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle"><input type="submit" onclick ="return check(this.form)" value="Login" name="commit"></p>
</form>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
</body>
</html>
Window.location is not a function, it is a property that is just read. However,
window.location.assign
might work better.
I have read other answers for the same question but I am having problems and would be grateful for some advice.
I have javaScript in my html file, and an Onclick() statement on the submit button to clear the form but now the email confirmation message does not come up and the message is no longer sent. If I put the onClick(); in the body of the form, every field is cleared just by clicking on a form field. I really want to be able to submit a message, then have the form cleared on successful send.
<script type ="text/javascript">
function clearform () {
document.getElementById("name").value="";
document.getElementById("email").value="";
document.getElementById("subject").value="";
document.getElementById("message").value="";
}
</script>
<div class="row">
<div class="col-sm-6">
<h2>Send us a message</h2>
<!-- action="replace it with active link."-->
<form action="contact.php" method="post" name="contact-form" id="contact-form" >
<label for="name">Your Name <span>*</span></label>
<input type="text" name="name" id="name" value="" required />
<label for="email">Your E-Mail <span>*</span></label>
<input type="text" name="email" id="email" value="" required />
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" value="" />
<label for="message">Your Message</label>
<textarea name="message" id="message"></textarea>
<div class="row">
<div class="col-sm-6">
<input type="submit" name="sendmessage" id="sendmessage" value="Submit" onclick="clearform();" />
</div>
<div class="col-sm-6 dynamic"></div>
</div>
</form>
I then have the following in the PHP file:
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
//$this->response_html = '<p>Thank You!</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!</span>";
header("Location: contact.php");// redirect back to your contact form
exit;
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
?>
No ajax form post
If you are not using ajax to submit the form (you don't seem to be using it), there is no need for javascript to clear the form, the form will be reloaded on submit and it will be empty.
However, you have a problem with your location redirect: You are outputting html before that so the redirect will probably fail.
You should not output anything before you redirect and you could add a query variable to the url so that you can show your success message when the form loads:
if($this->response_status)
{
$this->sendEmail();
}
header("Location: contact.php");// redirect back to your contact form
exit;
Using ajax to post the form
If you are using ajax (the setting of your response variables seems to indicate that you want to do that), you should put the clearform () call in the success function of your ajax call and remove the header() redirect in php. Instead you probably want to return / output the results:
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
exit;
You've got to make sure the event continues to propagate and the form is submitted:
function clearform () {
document.getElementById("name").value="";
document.getElementById("email").value="";
document.getElementById("subject").value="";
document.getElementById("message").value="";
return true;
}
This code:
<?php
if(isset($_GET['submit']))
{
?>
<head>
<script type="text/javascript">
document.getElementById('up').submit(); // SUBMIT FORM
</script>
</head>
<?php
}
?>
form:
<form name="up" id="up" action="" method="post">
<textarea name="text" rows="40" cols="100"></textarea>
<input type="submit" name="ingameban" value="Save in-game banlist (Upload to server and make new bans take effect)" style="height: 64px; width: 550px;" />
</form>
Keeps looping all the time, the same result as smashing the reload button.
It has to submit the form when the url states ?submit=submit
What to do to fix this?
Thanks
Your approach is right, but the problem is that submit=submit in the URL is copied to the new URL used to submit the form. Because in your form you have:
<form name="up" id="up" action="" method="post">
Since action is empty, the exact same URL is used, so submit=submit stays in the URL. Instead, provide the proper URL in action. Then submit=submit won't be copied to the new URL:
<form name="up" id="up" action="/my-url" method="post">
How about setting an input hidden field, which you mark as true when you submit.
Check this field before submitting again.
Try this:
<?php
if(isset($_GET['submit']))
{
if(isset($_GET['submitted']) && $_GET['submitted'] == 'false') {
?>
<head>
<script type="text/javascript">
document.getElementById('submitted').value = 'true';
document.getElementById('up').submit(); // SUBMIT FORM
</script>
</head>
}
<?php
}
?>
<body>
<form method="get" id="up">
<input type="hidden" id="submitted" name="submitted" value="false" />
...
</form>