Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Just want to make sure that my PHP login page submitted with a new page that comes with my Login ID, for example "Welcome, XX", XX for your login username. So what should I do for my codes below (I use reCapture here):
<!DOCTYPE html>
<head>
<title>reCaptcha Log-in</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
<!-- your HTML content -->
<body>
<fieldset style="border:2px groove; border-color:blue; padding:15px 30px 15px;margin-right:5px;width:350px;height:400px">
<form method="post" action="recaptcha.php">
<p><b>User Name </b> <input type="text" name="username1" size="20px" maxlength="15"></p>
<p><b>Password </b> <input type="password" name="password1" size="20px" maxlength="15"></p>
<?php
require_once('recaptchalib.php');
$publickey = "6LfxlgcTAAAAALNywpDCYeKbH8ACc9dw6xaCZT-0"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<br/>
<div align="left"> <input type="submit" name="submit1" value=login></div>
</form>
<!-- more of your HTML content -->
</body>
</html>
<?php
session_start();
require_once("require_pro.php");
if($_SERVER["REQUEST_METHOD"]=="POST")
{
if(isset($_POST['submit1'])){
require_once('recaptchalib.php');
$privatekey = "6LfxlgcTAAAAACugkAYxfmc__38DtbI5MzDUHKx-";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ((!$resp->is_valid)&&(isset($_POST['username1']))) {
// What happens when the CAPTCHA was entered incorrectly
echo "<p>Sorry, Please enter the right reCaptcha code</p>";
$error = $resp->error;
} else {
$myusername=addslashes($_POST['username1']);
$mypassword=addslashes($_POST['password1']);
$sql=" SELECT * FROM user
WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count == 1)
{ $user1=$_POST['username1'];
echo "Login Successfully";
header("location:welcome.php?=$user1");
} else if(!empty($_POST['username1'])){
echo "<p><font color='black'>Login Information wrong, please try again</font></p>";
}
}
}
}
?>
<welcome.php> :
<!DOCTYPE html>
<html>
<head>
</head>
<body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
<!-- your HTML content -->
<body>
<fieldset style="border:2px groove; border-color:blue; padding:15px 30px 15px;margin-right:5px;width:350px;height:400px">
<?php
echo" Welcome !".??????
</body>
</html>
First, addslashes isn't the right function for preventing SQL injection. See Examples of SQL Injections through addslashes()?.
Second, mysql_* functions are deprecated and should not be used in new code. See the big red box at http://php.net/mysql_query. Use something like PDO with parameterized queries (which will also help you with SQL injection).
Third, you need to store something in the session so you know that they're logged in and which user they're logged in as. When the user successfully logs in, something like:
$_SESSION['username'] = $_POST['username1'];
Which will allow you to use it in subsequent pages.
since you are passing the username via the url,you use the $_GET[''] array but you code needs a little clean up ..you do this instead
if($count == 1)
{ $user1=$_POST['username1'];
echo "Login Successfully";
header("location:welcome.php?username=$user1");
}
to get the username,you do this
echo "Welcome $_GET['username']"; //make sure you clean up the variable
Related
This question already has answers here:
Prevent duplicate record insertion on refresh without redirecting
(2 answers)
Prevent duplicate records to a table using PHP [duplicate]
(4 answers)
Closed 5 years ago.
I am facing some problem which you can easily solve this.
Form which I make work fine in first look because it store data in database when click submit button. I it also store data after I refresh Profile page. I think it will be solve if code execute only on click submit button but not on refresh the page. But don't know how to do that.
Profile.php
<?php
include('session.php');
include('frnd.php');
if(!isset($_SESSION['login_user'])){
header("location: index.php"); // Redirecting To Home Page
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<span><?php echo $error; ?></span>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout">Log Out</b>
</div><br>
<form action="" method="post">
<input type="text" name="frndIn" required><input type="submit" name="add">
</form>
</body>
</html>
Frnd.php
<?php
$error = ''; // Variable To Store Error Message
if (isset($_POST['add'])) {
if (empty($_POST['frndIn'])) {
$error = "Please enter username of your friend";
}
else
{
$frndIn = $_POST['frndIn'];
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "msg");
$query = "INSERT INTO friend (username, friend) values (?,?)";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $login_session, $frndIn);
if ($stmt->execute())
{
echo "New record inserted successfully";
}
else
{
$error = 'Error occur';
}
mysqli_close($conn); // Closing Connection
}
}
?>
Edit: I solve this problem by using POST/Redirect/GET method. This video (https://www.youtube.com/watch?v=bIkqNHyj25w) is very helpful.
After validation and successful insertion into the database in Frnd.php you need to redirect the user/client back to your Profile.php.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So, i am learning how to write php now.I want to build a small shopping website. My index.html looks something like this:
<!DOCTYPE html>
<html>
<head>
<link href="index.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="topnav">
<a class="active" href="#index.html">Home</a>
Administrator
Register User
Register New Account
</div>
<img class="centerImage" src="eshop.jpg">
</body>
</html>
and the loginAdmin.php file looks like this:
<?php
session_start();
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";
$link = mysqli_connect(localhost,$user,$passwd);
#mysqli_select_db($link,$database) or die ("Unable to select database");
// try to create a new record from the submission
$username = mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);
if ($username && $password) {
// here we define the SQL command
$query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";
// submit the query to the database
$res=mysqli_query($query);
// make sure it worked!
if (!$res) {
echo mysql_error();
exit;
}
// find out how many records we got
$num = mysqli_numrows($res);
if ($num==0) {
echo "<h3>Invalid login</h3>\n";
exit;
} elseif ($num!=1) {
echo "<h3>Error - unexpected result!\n";
exit;
}
// valid login, set the session variable
$_SESSION['userid']=mysql_result($res,0,'userid');
echo "<h3>Welcome $username</h3>\n";
?>
<head>
<link href="login.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form">
<input type="text" placeholder="User Name:" />
<input type="password" placeholder="Password:" />
<button onclick="writeMsg()">login</button>
</form>
</div>
</div>
</body>
If the user pressed on the loginAdmin link so the php code will be executed, and i dont want that, only after the user pressed on the login button i want the php code block will be executed. How can i do that? Maybe i should seperate the files (php and html) and not user href on the php files in the index.html ? and the index.html file should be index.php?
You need to add your php code within a condition which satisfies when the form submission happens. Also you need to add name to your input fields
Your code will look like this,
<?php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])) { //Added this line
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";
$link = mysqli_connect(localhost,$user,$passwd);
#mysqli_select_db($link,$database) or die ("Unable to select database");
// try to create a new record from the submission
$username = mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);
if ($username && $password) {
// here we define the SQL command
$query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";
// submit the query to the database
$res=mysqli_query($query);
// make sure it worked!
if (!$res) {
echo mysql_error();
exit;
}
// find out how many records we got
$num = mysqli_numrows($res);
if ($num==0) {
echo "<h3>Invalid login</h3>\n";
exit;
} elseif ($num!=1) {
echo "<h3>Error - unexpected result!\n";
exit;
}
// valid login, set the session variable
$_SESSION['userid']=mysql_result($res,0,'userid');
echo "<h3>Welcome $username</h3>\n";
}
} //Added this line
?>
<head>
<link href="login.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form" method="POST"> <!-- edited this line -->
<input type="text" name="username" placeholder="User Name:" /> <!-- edited this line -->
<input type="password" name="password" placeholder="Password:" /> <!-- edited this line -->
<button onclick="writeMsg()">login</button>
</form>
</div>
</div>
</body>
I have just added name to the form fields & then kept all your PHP code within a condition
I've looked through multiple web articles and stackoverflow answers, however I cannot find the bug in my code. Maybe I've been looking at it too long.
Basically I'm just setting up a simple login for a demonstration, yes I know its inject-able and outdated, this doesn't matter. Basically I'm using a login with sessions and then redirecting the user to secure content when they're logged in. I've also created a script that checks for the session variables, to see if the user is logged in or not. Basically, I'm beating a dead horse and I don't know why this isn't working, could someone please help?
index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome, please log in</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<?PHP require_once"scripts/mysql_connect.php"; // Establish a database connection ?>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<?PHP
echo "<form method='post' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' value='Log In'>
</form>"
?>
</div>
</body>
</html>
checklogin.php:
<!doctype html>
<html>
<head>
<title>Checking login...</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<?php
require_once"scripts/mysql_connect.php";
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
$sql = "SQL";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$active = $row['active'];
$count = mysql_num_rows($result);
// If result matched, table row must be 1 row.
if($count == 1) {
$_SESSION["login"] = "OK";
$_SESSION["aEmail"] = $aEmail;
echo "<h1>Log in successfull!</h1>
<hr><br />
Your details checked out! Redirecting you now...";
// Wait 1 seconds then redirect to the secure content.
header("Location: http://www.website.com/secure_content.php");
} else {
echo "<h1>Log in unsuccessfull!</h1>
<hr><br />
Sorry. It seems your log in detials were incorrect. Please go back and try again.";
// Wait 2 seconds then redirect back to the log in page.
header("Location: http://www.website.com/index.php");
}
exit;
?>
</div>
</body>
</html>
loginstatus.php:
<?php session_start();
if(!(isset($_SESSION["login"]) && $_SESSION["login"] == "OK")) {
header("Location: http://www.website.com/index.php");
exit;
}
?>
Thanks for any help!
In checklogin.php and index.php you need to start the session. Add the following code before <!doctype html>
Add this code:
<?php session_start(); ?>
You forgot to put that line in this file because you are creating a new session during the checks in the database.
Looks like you haven't started the session in the first place. On the top of your page please write the following code:
<?php session_start(); ?>
Now, secondly, I'd suggest you to write your HTML and PHP separately instead of writing your HTML for the form within the echo.
Also, it's better if you add a name to your submit button.
Let me show a sample below.
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<form method='POST' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' name='submit' value='Log In'>
</form>
Now, in your checklogin.php. you should place an isset condition and see if you're getting any POST request.
Try this:
<?php
require_once"scripts/mysql_connect.php";
if (isset($_POST['submit']) { // Add this condition
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
/* Other code */
if($count == 1) {
/* Other code */
} else {
/* Other code */
}
}
Hope this helps.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I know that this is well known problem but I've tried all solutions with no avail :(
Here is my code:
<?php
ob_start();
if (!empty($_POST)) { // if submit
$username = $_POST['username'];
$userpass = $_POST['userpass'];
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('ita4') or die($connection_error);
function login($username, $userpass) {
$sqlQuery = "SELECT COUNT(userid) FROM users WHERE name='$username' AND password='$userpass' AND admin='t'";
$runQuery = mysql_query($sqlQuery);
return (mysql_result($runQuery, 0) == 1) ? TRUE : FALSE;
}
if(login($username, $userpass)) {
setcookie("username", $username, time()+60*60*24*30);
$_COOKIE['username'] = $username;
echo "Me:".$_COOKIE['username'];
//echo "<script> location.replace('done.html'); </script>";
} else {
echo "<script> alert('Your input data is not found!'); </script>";
}
}
?>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv=content-type content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="upper">
Home • Login • About
</div>
<div id="container">
<div id="loginDiv">
<form action="login.php" onsubmit="return checkEmpty()" method="post" name="loginForm">
<table>
<tr>
<td style="width:100px">Name: </td>
<td>
<input name="username" id="username" type="text" style="width:250px"></td>
</tr>
<tr>
<td style="width:100px">Password: </td>
<td>
<input name="userpass" id="userpass" type="password" style="width:250px"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center"><input id="loginImg" type="image" src="images/loginButton.png"></td>
</tr>
</table>
</form>
</div>
</div>
<div id="lower">
<br><br><br><br><br>
<p style="text-align:center">COPYRIGHTS © 2013 • WWW.HISHAM.WS</p>
</div>
<script type="text/javascript">
function checkEmpty() {
var username = document.getElementById("username").value;
var userpass = document.getElementById("userpass").value;
if(username=="" || username==null) { alert("You've to enter your name!"); }
else if(userpass=="" || userpass==null) { alert("You've to enter a password!"); }
else { return true; }
return false;
}
</script>
</body>
</html>
Thanks in advance
So against my initial reaction to not help you, I decided to go ahead and build the database and table like you have. I created a new database named ita4 and added a table called users with four fields (userid, name, password, and admin). I added a user named josh with a password of josh and an admin setting of 't'. I then put your file into my local development environment and named it login.php. I then loaded up the page in my browser and entered josh for the username and josh for the password and it resulted in it displaying "Me:josh" at the top of the page and the login page still displaying below it. I get no errors.
If you aren't getting that far, then the error message may be because the database connection details are bad or your table doesn't have one of those fields. You do have a "or die(mysql_error()" after the database connect code.
The header needs to be the first thing in the document. Your code should look something like
<?php header("header information"); ?>
<html>
... Your HTML HERE ...
</html>
More information can be found in the PHP documentation here.
As far as i understand, you want to redirect the user to another page if a login occurs.
You could use javascript and/or meta redirections in order to do that.
This question might also help : How to redirect if user already logged in
You did not tell the line number that causes the notice. But I assume it is because you are doing setCookie().
You are already using ob_start() so that is good.
What I suggest is that you pay attention to that NO CHARACTERS should be at the start of the document, before the ob_start(). Look especially for any characters or even white spaces or enters (new lines), before you start <?php. Let <?php be the very first thing in your file.
I'm relatively new to PHP and have exhausted the internet trying to find an answer to this problem. I've looked at countless examples but people seem to very different login systems to mine and I have trouble deciphering it.
Here is my code so far:
index.html
<!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=iso-8859-1" />
<title>Video for Education Log In</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="logo">
videoedu.edu </div>
<div id="menu">
<ul>
<li>Create Account</li>
<li>About Us</li>
</ul>
</div>
</div>
<br><br><br><br>
<div id="page">
<div id="content">
<h2>Video for Education helps you connect and share with the videos in your life.</h2>
<h3>Upload Share Create Using video for your education purposes. Lecturers Welcome
Upload Share Create Using video for your education purposes. Lecturers Welcome
Upload Share Create Using video for your education purposes. Lecturers Welcome</h3>
<div class= "form">
<form name="login" method="post" action="checklogin.php">
Username: <input type="text" name="myusername" id="myusername" class="textb"/><br />
Password : <input type="password" name="mypassword" id="mypassword" class="textb"/><br />
<br>
<input type="submit" name="login" value="Login" id="login" class="texta" />
</form>
</div>
</div>
</div>
</div>
</body>
</html>
checklogin.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "test";
$tbl_name = "members";
mysql_connect("$host", "$username", "$password")or die("Cannot connect.");
mysql_select_db("$db_name")or die("Cannot select DB.");
$myusername=$_POST["myusername"];
$mypassword=$_POST["mypassword"];
if ($myusername&&$mypassword)
{
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else
{
echo "Wrong Username or Password";
}
}
else
echo "You have left one or more fields blank.";
?>
login_success.php
<?
session_start();
if( !isset( $_SESSION['myusername'] ) ){
header("location:account.html");
}
echo "Welcome, ".$_SESSION['myusername']." - You are now logged in.<br>";
echo "<a href=logout.php>Logout</a>"
?>
<html>
<body>
</body>
</html>
logout.php
<?php
session_start();
session_destroy();
echo "You have been logged out, <a href='index.php'>click here</a> to return."
?>
I have tried inserting this into index.html and changing the file name to index.php.
$submit = $_POST["login"];
if($submit)
{
}
...but it just constantly displays one of the errors ('Wrong username or password') down the bottom of the page at all times.
I want it so that if the user enters a wrong username or password, or leaves a required field blank, the error will pop up on the same page, instead of going to a new ugly, blank PHP page with the error message in the top left-hand corner.
In checklogin.php, instead of echoing an error, use this:
die(header("location:index.html?loginFailed=true&reason=password"));
or something similar, and in your index.html page, just have PHP generate the HTML message, something like this:
<input type="submit" name="login" value="Login" id="login" class="texta" /><br /><br />
<?php $reasons = array("password" => "Wrong Username or Password", "blank" => "You have left one or more fields blank."); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>
</form>
Also, make sure to die() or exit() when you use header to redirect the page, otherwise the rest of your script continues to run.
What you can do is, redirect back to your page if data is invalid. Put errors into session and display them on page:
e.g.:
<?php if(isset($_SESSION['Login.Error']) { echo $_SESSION['Login.Error'];
unset($_SESSION['Login.Error']); } ?>
<form ....
and your error will be visible on page.
In your PHP
$_SESSION["Login.Error"] = 'Invalid credentials';//redirect back to your login page
In checklogin.php, if the user enters a wrong username or password, use the code like this:
echo "<script language=\"JavaScript\">\n";
echo "alert('Username or Password was incorrect!');\n";
echo "window.location='login.php'";
echo "</script>";
It will pop up the error message at the same page (login page), instead of going to a blank PHP page.
You would want to make your index.html page a PHP page, and have the form submit to itself, i.e. to index.php. In this way, you your index page can do the login check for the form values and display the output of the page appropriately, or use headers to redirect if everything validates.
It's hard to tell the effect that your attempt may have had without seeing it in the full context, but the gist of the situation is you need the form to submit to itself and handle it's login processing.
It looks like you want/need to integrate it with jQuery or some other Javascript/AJAX library
to make things more presentable. jQuery has an plugin for form validation that's is very easy to integrate to your project (obviously jQuery library is minimum requirement).
jQuery site and
jQuery validation plugin.
You may also consider using a PHP Framework like CodeIgniter which is also has a very helpful form validation library. CodeIgniter is scary at the beginning (like all MVC based programming library/framework) but it's worth it. you can watch some tutorials on netTuts+ they've created a series of tutorials called CodeIgniter From Scratch, is not from the latest version but is easy to adapt.