Injecting HTML produced by PHP - php

This may be a simple question for some of you but i've been investigating it for the last hour and couldn't find the answer. I have a simple login form/script that has the following structure;
<?php
PHP code here to check for token (if true) and then check the db for username and password
if the token is false display error message
?>
<HTML>
HTML logon form here that sets the token
</HTML>
Now if there is an issue with the logon, i.e the password is incorrect the php will output the error message, trouble is that it will echo the output at the top of the form. I'd like to be able to insert it at another point of the form. i have a vague idea that i could inject it into the html with something like {logon_error} but i don't know what method thats called or how to use it.

You can store the error message in a php variable , for e.g. $error_msg = "Error! ... ";
And display that wherever you want in the html page like this:
<html>
...
<body>
...
<span><?= $error_msg; ?>
</body>
</html>

Store the error message in a variable, and use it afterwards.
Here's a working example to help you understand:
<?php
if (isset($_POST['FormSubmit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === 'admin' && $password === 'hunter2') {
# success
} else {
$error = 'Invalid credentials';
}
}
?>
<html>
<div id="errorContainer">
<?php echo (isset($error)) ? $error : ''; ?>
</div>
<form action="" method="post">
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" name="FormSubmit" value="Submit!" />
</form>
</html>
If you have multiple checks, and want different error messages to be output, then you could store the error messages in an array instead. Your validation code should look like:
if (condition) {
$error[] = '...'
}
elseif (condition) {
$error[] = '...'
}
else (condition) {
$error[] = '...'
}
And then, to output it in your HTML, you can use a foreach construct with the alternate syntax:
<div id="errorContainer">
<?php foreach($errors as $error): ?>
<p class="error-content">
<?php echo $error; ?>
</p>
<?php endforeach; ?>
</div>
Note that this is a very basic example and is just for demonstration purposes. You should never trust user input. Your original form should contain all the necessary validation and should not be just a couple of if statements.

You would have to store the message in the session or take a look at https://github.com/plasticbrain/PHP-Flash-Messages
the main idea is $error_mesage = 'your error mesage here';
loadView('your-view')->with($error_message);
It's really simple, if you give more information about what kind of framework you are working with we may be able to assist you further.

You can do like this:
PHP:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{$userErr = "Username is required";}
}
HTML:
<span class="error">* <?php echo $userErr;?></span>
You can do whatever you like using <?php echo ""; ?> in php to call it on your html.

Related

PHP Server Side Form Validation.Empty Form fields are inserted into database

I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}

Login form php without database - reloading

Is there any solution like unset $msg or something, that, when I reload the page, the $msg stops?
here is my code:
index.php:
<form class="ligar" action="log.php" method="post">
<p class="lig"><input name="username" type="text" placeholder="Username"></p>
<p class="lig"><input name="password" type="password" placeholder="Password"></p>
<p class="lig"><input name="Entrar" type="submit" value="log"></p>
<p class="error"><?php if(isset($_GET['msg']))
echo $_GET['msg'];
?>
</p>
</form>
log.php:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if ($username =='john' AND $password=='abc') {
header("Location:/detalhes.php");
} elseif ($username!='john' OR $password!='abc'){
$msg = "Wrong, try again.";
header("Location:http://localhost/index.php?msg=$msg");
}
?>
Something like this should do the job: (untested)
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username =='john' AND $password=='abc') {
header("Location:/detalhes.php");
} elseif ($username!='john' OR $password!='abc'){
$_SESSION['msg'] = "Wrong, try again.";
header("Location:http://localhost/index.php");
}
?>
log.php
<?
session_start();
<?php if(isset($_SESSION['msg']))
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
If I understand correctly, if first time you enter the wrong credentials, the log.php code redirects the page to
http://localhost/index.php?msg=Wrong,%20try%20again.
So if you reload the page via browser, obviosly the uri remains the same, so you still get the error message in the $_GET['msg'] variable.
EDIT I don't think there's a solution to that using only HTML+PHP.
You can convert the form post to an AJAX request and show/hide the error code via javascript, so you don'
t need to change the uri.
The web is full of easy examples on how to implement an AJAX login form.
EDIT Well, as #Stefano L said, you can use session cookies so you don't need to use any javascript at all.

php page accessible only by passing through another php page

I am looking to develop a website containing stages. I want for example to pass by the stage 2 only when i click on the finish button in the page of stage 1 so the stage 2 page can't be accessible by its url or whatever only if the user pass by another page.
Is there a method to do this ??? i am a beginner in security so please try to help me, thanks in advance coders
Make use of sessions to develop this model.
index.php
<?php
#extract($_POST);
if(isset($sub))
{
session_start();
$_SESSION['authenticate']=true;
header("location:test1.php");
exit;
}
?>
<form action='' method="post">
<input type="SUBMIT" name="sub" value="Finish" />
</form>
open.php
<?php
session_start();
if(!isset($_SESSION['authenticate']))
{
echo "You are not allowed to access";
}
else { echo "You came from index.php ! so you are a valid user"; }
session_destroy(); //<-- I added this so you can test your example multiple times.
I think, this show work :)
Use can either redirect your user directly from index.php to open.php
header('Location : open.php');
Or,
in open.php, put this
if($_SERVER['HTTP_REFERER'] == 'index.php page's full link') {
//Do or Show whatever you want to show here
} else {
// Tell the user that you are not authorized
}
If that doesn't work, echo $_SERVER['HTTP_REFERER'] and see what link it gives you. And put that link where specified above.
Cool? :)
Edit (As per the comments) --
Lets say you have a form in your form in stage1.php
<form method="post" action="">
<span class="error"><?php echo $error; ?></span>
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
<input type="submit" name="submit" value="Submit">
</form>
use this php in stage1.php
if (isset($_POST['name'])||isset($_POST['email'])) {
if (!empty($_POST["name"])||!empty($_POST["email"])) {
$error = "Please fill in all the fields correctly";
}
else {
$name = $_POST['name'];
$email = $_POST['email'];
//You can also save the above Variables Globally by $GLOBALS['name'] = $_POST['name'];
//So that you can use the details when you reach the final stage
header('Location : stage2 page's link');
}
}
?>
and in Page 2 lets say you have another form, then there also check
<?php
if(!empty($name)||!empty($email)) {
//the above is check for global variables email and name are not empty - means stage 2 was filled properly
//Do things for the second page's form like you did for stage 1
} else {
header('Location : stage1 page's link');
//redirect back to stage 1.
}
?>

php log in form with messages and date and time

I am trying to create a php log in form. I want to just make a few adjustments but when i've tinkered with it, it stops working...
If you can't see from the code, I'm trying to create a (mock) log in form that asks for a username and password.
I want any blank textbox to show a red message to the right of the textbox. (i have the red error message, but I can't get it to the left of the box)
I want a sticky form that keeps either field if its filled in (again, I think I have this set up but don't think its working all the way)
I would like a person who enters the username: user and the password: abc123 to see a welcome message. If you don't use that username/password combo I want a message that says that they are not authorized. (This is what i really don't know how to do)
I want this all in a redux (also think i have that working but not 100% sure)
Any help would be greatly apprecaited!!
And here is my code:
<?php
define('TITLE', 'LOG IN');
// CSS
print '<style type="text/css" media="screen">
.error { color: red; }
</style>';
// Checking
if ( isset($_POST['submitted']) ) {
$problem = FALSE;
// Each value
if (empty($_POST['email'])) {
$problem = TRUE;
print '<p class="error">Please enter the username!</p>';
}
if (empty($_POST['password1'])) {
$problem = TRUE;
print '<p class="error">Please enter the password!</p>';
}
if (!$problem) { //No problem
// Printing the log in message
print '<p>Thank you for logging in!</p>';
$_POST = array();
} else {
print '<p class="error">No entry!</p>';
}
}
?>
<form action="login.php" method="post">
<p>"Username": <input type="text" name="username" size="20" value="<?php if (isset($_POST['username'])) { print htmlspecialchars($_POST['username']); } ?>" /></p>
<p>Password: <input type="password" name="password1" size="20" /></p>
<p><input type="submit" name="submit" value="Log in" /></p>
<input type="hidden" name="submitted" value="true" />
</form>
Ok, here is a simple login that is not meant for real world usage. Please read the comments included in the code to see what I have to say about each. Doing logins is quite tricky for a number of reasons, so this example is not meant to demonstrate a real world working codebase, but a very simple username/password check.
The security issues associated with a more sophisticated use are perhaps beyond this answer, but the below code is the way I would interpret what you have posted above, without getting to detailed (to the point of possibly making it hard to understand the simplest steps occurring).
Let me know if you have any questions. To see the form in action, check:
http://jfcoder.com/test/simplelogin.php
Also, I use PHP's HEREDOC syntax instead of quoted strings for simplicity. To read more about this sometimes handy form, see
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc.
<html>
<head>
<style type="text/css">
.error {
color: red;
}
</style>
</head>
<body>
<?php
// Note, in most cases you will set a SESSION variable
// of $_SESSION['loggedin'], which would require you to
// use session_start() before you access any session
// variables.
// Note, this defaults to false.
$loggedin = false;
// If I get an error, I will put it in this variable.
$error = '';
// If the username is provided, run the code. Otherwise,
// act as if the login form was not submitted. This makes
// a hidden `submitted` value superfluous, and guarantees
// your users at least provide a username.
if ($_POST['username']) {
// NOTE!!! In mose cases, you're querying a database
// for a username/password match. In PHP, this often
// means a MySQL query. DO NOT USE THE BELOW IF YOU
// ARE DOING SO!!! This will allow what's called a
// SQL injection. You MUST wash your data with something
// like mysql_real_escape_string() for the $_POST
// values (NEVER trust submitted data, always validate
// and escape as necessary), or use the PHP PDO library.
// In this example, though, I use a switch to check the
// values for exact matches, which means I do not need
// to escape (and mysql_real_escape_string() requires
// a database connection to use).
$username = $_POST['username'];
$password = $_POST['password'];
// Here, I check if the username and password match.
// This is, of course, hardcoded, but to match your
// attempt, I chose to keep the form, although you
// rarely see this in use in the real world.
switch ($username) {
// My one case. For each additional user, you
// would need to add a new entry with password
// check. And I set my error text according to
// the result of the code.
case 'user':
if ($password === 'abc123') {
$loggedin = true;
} else {
$error = 'Username/Password did not match.';
}
break;
default:
// Note, I don't give a descriptive error
// here. If someone reports this error, I
// know what may have gone wrong, but the
// user is not told the username does not
// exist.
$error = 'Unknown error. Try again.';
}
}
// I will only show the welcome message if the user has
// successfully logged in.
if ($loggedin === true) {
echo <<<HTML
<h1>Welcome!</h1>
<p>Thank you for logging in $username</p>
HTML;
} else {
// If an error text is set, display that error.
if ($error != '') {
$error = "<h4>Login error</h4><p class='error'>$error</p>";
}
// Here's my form, only shown if the user has not
// successfully logged in (note, this is only a one-
// time check when the POST data is submitted; I
// would need to use sessions to "remember" the requestor
// had logged in across page accesses.
echo <<<FORM
<h1>Login Form</h1>
<form action="simplelogin.php" method="POST">
$error
<p><label>Username: <input type="text" name="username"/></label></p>
<p><label>Password: <input type="password" name="password"/></label></p>
<p><input type="submit" value="Login"/> <input type="reset"/></p>
</form>
FORM;
}
?>
</body>
</html>
Here's my full code. I pretty much rewrote the whole thing, so I appologize if the coding style differs too much:
<?php
// Output our CSS code
echo '<style type="text/css" media="screen">
.error
{
color: red;
}
</style>';
// Define our variable
$problem = false;
// Check if the form has been submitted
if (isset($_POST['submitted']))
{
// If either user or password are empty, we have a problem
if (empty($_POST['username']) || empty($_POST['password']))
{
$problem = TRUE;
}
// If there is no problem, username is user, and password is abc123, we're good
if (!$problem && $_POST['username']=='user' && $_POST['password']=='abc123') {
// Print our login message
echo 'Thank you for logging in!<br />';
}
// Ok, there's either a problem or the username or password is wrong, so no entry for them
else
{
echo '<p class="error">No entry!</p>';
}
}
?>
<form action="login.php" method="post">
Username: <input type="text" name="username" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['username']))
{
echo $_POST['username'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['username']))
{
echo '<span class="error">Please enter a username!</span>';
}
?>
<br />Password: <input type="password" name="password" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['password']))
{
echo $_POST['password'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['password']))
{
echo '<span class="error">Please enter the password!</span>';
}
?>
<br /><input type="submit" value="Log in" />
<br /><input type="hidden" name="submitted" value="true" />
</form>

How to redirect to another page using PHP [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 months ago.
I'm building a website which includes a login page. I need to redirect the user to their profile page once they've logged in successfully, but I don't know how to do that in PHP (It's my first site).
I've searched the internet and have been told that the header() function should do the trick, but it will only work if I haven't outputted any information before using it.
That's the problem. I've outputted a bunch of information (Including the HTML to build the login page itself).
So how do I redirect the user from one page to the next?
What options do I have? Also, what is the best practice in these instances?
EDIT: Here's my entire login.php page:
<?php
session_start();
echo "<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Sprout</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'>
</head>
<body>
<div class='box'>
<form action='login.php' method='post'>
Name<br /> <input type='text' name='username' class='form'/><br />
Password<br /> <input type='password' name='password' class='form'/>
<input type='submit' value='Login' class='button' />
</form>
</div>
</body>
</html>";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST["username"];
$password = $_POST["password"];
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");
$dbname = "database";
mysql_select_db($dbname);
$query = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($query) or die ("Failed Query of " . $query);
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
}
?>
You could use a function similar to:
function redirect($url) {
header('Location: '.$url);
die();
}
Worth noting, you should them with a die() or exit() function to prevent further code execution.
Note that it just makes no sense to output large chunks of HTML if you are going to redirect. Therefore you have to move the form handling code above all HTML. As a side effect it will mitigate the notorious "Headers already sent" error.
Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/
This guide includes reasons for using die() / exit() functions in your redirects, as well as when to use ob_flush() vs ob_start(), and some potential errors that the others answers have left out at this point.
You can conditionally redirect to some page within a php file....
if (ConditionToRedirect){
//You need to redirect
header("Location: http://www.yourwebsite.com/user.php");
exit();
}
else{
// do something
}
That's the problem. I've outputted a bunch of information (including the HTML to build the login page itself). So how do I redirect the user from one page to the next?
This means your application design is pretty broken. You shouldn't be doing output while your business logic is running. Go an use a template engine (like Smarty) or quickfix it by using output buffering).
Another option (not a good one though!) would be outputting JavaScript to redirect:
<script type="text/javascript">location.href = 'newurl';</script>
header won't work for all
Use below simple code
<?php
echo "<script> location.href='new_url'; </script>";
exit;
?>
Assuming you're using cookies for login, just call it after your setcookie call -- after all, you must be calling that one before any output too.
Anyway in general you could check for the presence of your form's submit button name at the beginning of the script, do your logic, and then output stuff:
if(isset($_POST['mySubmit'])) {
// the form was submitted
// ...
// perform your logic
// redirect if login was successful
header('Location: /somewhere');
}
// output your stuff here
You could use ob_start(); before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.
Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML.
The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.
If the login is valid you'll redirect using the "header" function.
Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.
<?php
ob_start();
if (FORMPOST) {
if (POSTED_DATA_VALID) {
header("Location: https://www.yoursite.com/profile/");
ob_end_flush();
exit;
}
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>
firstly create index.php page and just copy paste below code :-
<form name="frmUser" class="well login-form" id="form" method="post" action="login_check.php" onSubmit="return FormValidation()">
<legend>
<icon class="icon-circles"></icon>Restricted Area<icon class="icon-circles-reverse"></icon>
</legend>
<div class="control-group">
<label class="control-label" for="inputPassword">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-user icon-cream"></icon> </span>
<input class="input" type="text" name="username" id="username" placeholder="Username" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-password icon-cream"></icon>
</span> <input class="input" type="password" name="password" id="password" value="" placeholder="Password" />
</div>
</div>
</div>
<div class="control-group signin">
<div class="controls ">
<input type="submit" class="btn btn-block" value="Submit" />
<div class="clearfix">
<span class="icon-forgot"></span>forgot password
</div>
</div>
</div>
</form>
/*------------------after that ----------------------*/
create a login_check.php and just copy paste this below code :-
<?php
session_start();
include('conn.php');
<?php
/* Redirect browser */
header("location:index.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
<?php
if(count($_POST)>0)
{
$result = mysql_query("SELECT * FROM admin WHERE username='".$_POST["username"]."' and password = '".$_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["user_id"] = $row[user_id];
$_SESSION["username"] = $row[username];
$session_register["user_id"] = $row[user_id];
$session_register["username"] = $row[username];
}
else
{
$_SESSION['msg']="Invalid Username or Password";
header("location:index.php");
}
}
if(isset($_SESSION["user_id"]))
{
header("Location:dashboard.php");
}
?>
/*-----------------------after that ----------------------*/
create a dashboard.php and copy paste this code in starting of dashboard.php
<?php
session_start();
include('conn.php');
include('check_session.php');
?>
/*-----------------------after that-----------------*/
create a check_session.php which check your session and copy paste this code :-
<?php
if($_SESSION["user_name"])
{
?>
Welcome <?php echo $_SESSION["user_name"]; ?>. Click here to Logout.
<?php
}
else
{
header("location:index.php");
}
?>
if you have any query so let me know on my mail id farjicompany#gmail.com
Although not secure, (no offense or anything), just stick the header function after you set the session variable
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
header('Location: /profile.php');
On click BUTTON action
if(isset($_POST['save_btn']))
{
//write some of your code here, if necessary
echo'<script> window.location="B.php"; </script> ';
}
----------
<?php
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>';
$gourl='http://stackoverflow.com';
echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">';
exit;
?>
----------
Just like you used echo to print a webpage. You could use also do the same with redirecting.
print("<script type=\"text/javascript\">location.href=\"urlHere\"</script>")
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>

Categories