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.
Related
I'm making a very simple login script (beginner at PHP) and here is my code. I can't figure out how to redirect after true login credentials. I know this probably is a duplicate but I can't figure this out without help on my exact script (as mentioned above I'm not that good).
update: So I have fixed name in password, form method, and the redirect . But now I'm getting to a empty page, something is wrong with my function as one comment earlier. I'm also a dummie at MySQL can someone help me further? My code is updated
Another update
Okay so i have finished all of my script, but the problem is my sql functions. So does anyone know mysqli and can translate it?
<?php $tilkobling = mysqli_connect("localhost","root","root","login_form");
if(isset($_POST["name"], $_POST["password"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$result1 = mysql_query("SELECT username, password
FROM user
WHERE username = '".$name."'
AND password = '".$password."'");
if(mysql_num_rows($result1) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>login</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>bypass to information site</h2>
<div class="login-page">
<div class="form">
<h1>Login</h1>
<form method="post" class="login-form">
<input name="name" type="text" placeholder="username"/>
<input name="password" type="password" placeholder="password"/>
<button name="submit">login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script type="text/javascript">
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
</html>
You're using mysqli connector and mysql functions so let's assume you'll use mysql for all
$tilkobling = mysql_connect("localhost","root","root");
mysql_select_db( "login_form", $tilkobling );
and you'll need to add session_start() before using/setting any session variables
session_start();
$_SESSION["logged_in"] = true;
Your header needs to be in the true portion of the if/else, which is where you set your $_SESSION variables, here you are:
if(mysql_num_rows($result1) > 0 )
{
session_start();
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
Have you Tried the HTML meta tag, this subtitutes the header() function.
Of course initially convert it into PHP code. Like this:
Echo "<meta http-equiv='refresh' content='0; URL=put your url in here to the page you like to redirect to'>" ;
This should probably operate correctly.
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
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 7 years ago.
I am learning pHp. I have made a login page.
The problem i am facing here is that, when user clicks on signin button & if record is found then he is taken to other page which displays redirect link, the user has to click on that to go to the next page.
Now what i want that when a user click on signin button, then the details should be cross checked in the database, if the record is found then user should be directly redirected to next page else error should be displayed.
This is my html page:
<!DOCTYPE html>
<html>
<head>
<title>OpenMoz</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="index.css"/>
</head>
<body style="height:650px;">
<h1 align="center" ><b><i>City Login</i></b></h1>
<div class="login">
<form action="login.php" method="post">
<input type="text" placeholder="Username" name="username" autocorrect=off autocapitalize=words required> <br>
<input type="password" placeholder="password" name="password" autocorrect=off autocapitalize=words required> <br>
<input type="submit" name="submit" value="Sign In">
</form>
<input type="submit" name="submit" value="Sign Up">
<div>
</body>
</html>
This is the login.php script to verify details :
<?php
$username = $_POST["username"];
$password = $_POST["password"];
if($username && $password)
{
$connect = mysql_connect("localhost","root","password") or die("Couldn't connect");
mysql_select_db("phplogin")or die("Couldn't connect");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword)
{
echo ("<center><a href='home.php'>Redirect</a></center>");
$_SESSION['username'] = $username;
}
else
{
echo ("Incorrect Password !");
}
}
else
die("The user doesn't exist");
}
else
echo ("Please enter username & password");
?>
I would be really thankful if my problem gets solved.
As long as you have not outputted anything to the browser, you can do a header redirect. This will achieve your aim.
Change this:
echo ("<center><a href='home.php'>Redirect</a></center>");
$_SESSION['username'] = $username;
To this:
$_SESSION['username'] = $username;
header("Location: /some-new-page.php");
exit;
Always exit; after a location redirect.
Oh yeah, and CLEAN your inputs.. ..you are wide open to SQL Injection.
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Oh yeah .. and mysql_* is deprecated. Use mysqli_*
use header("Location:home.php"); its best way to redirect page in php
header("Location:whaeverpage.php");
exit();
Do it before sending any data to the browser or you will get a header allready sen error
or by javascript :
If($connected ==='yes'){//your connection statement
?>
<script>window.location.replace("whatever_page");</script>
<?
}
WOWOW NONONO HALT! DO NOT LEARN mysql_ API FOR NEW DEVELOPMENT. It's deprecated/unsupported, ancient, error-prone. learn to use mysqli_ or better yet, PDO , and here is a great tutorial http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
also here: $query = mysql_query("SELECT * FROM users WHERE username='$username'");
code is vulnerable to SQL injection attack by hackers. must use mysql_real_escape_string.
also, you should not use * , for most cases, be specific. Also, you should not store passwords in plaintext (as your login system is doing), you should hash it..
other than that, check Chris Magg's already said what i would'ev https://stackoverflow.com/a/31355969/1067003
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
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.