php file that runs and then directs to another file - php

I am trying to create a home page. Once the user comes to the site and inputs username and password the data will get posted to a checklogin.php file where it will verify the data the user entered. Is there a way that after it checks the data and it is all good then it redirects the user to another page that is the home page? I want to do this so that my entire checklogin script is not on the home page. then also if the user is in a different part of the site, and they click home, the check login script will run again and it will fail. I understand i can use session variables to see if they have already logged in and then somehow bypass the checklogin script on the home page if they have already logged in, but is this the correct way to do this?
<?php
include'vive_fns.php';
$v_username = trim($_POST['viveuser']);
$v_password = trim($_POST['vivepass']);
if(!isset($_POST['viveuser'])|| empty($v_username)){
echo"Please enter a username"; //should change to redirect
die();
}
elseif(!isset ($v_username) || empty($v_username)) {
echo "Please enter a password"; //should change to redirect
die();
}
//if all data is entered we want to check the password
$mysqli = connect_db();
//set database query
$sql1 = "SELECT password FROM vive_user WHERE username = "."'$v_username'";
//check to make sure a result is returned
if(!$result1 = $mysqli->query($sql1)){
echo 'Could not query database. Please try again later.';//should change to redirect
die();
}
else {
$data = $result1->fetch_array(MYSQLI_NUM);
$db_pass = $data[0];
}
if($db_pass !== $v_password){
$title = 'Incorrect Login Info';
//do_html_header($title); this sets the page title
echo"Incorrect Password";//should change to redirect
die();
}
//if everything checks out need to establish user info
$title = 'Home';
do_html_header($title);
//echo"Logged In";
session_start();
$_SESSION['valid_user']=$v_username;
// at this point i want to redirect
header("Location: home.php");
exit();

check this out i think it would help you to under stand the logic here is first login page where user can put login info
<form action="reg_auth.php" method="post" accept-charset="utf-8">
<div id="inrlog" style="display:none;">
<div class="form-group required">
<label for="UserFirstname">Email</label>
<input name="firstname" class="form-control" maxlength="255" type="text" id="UserFirstname" required="required"/>
</div>
<div class="form-group required">
<label for="UserLastname">Password</label>
<input name="lastname" class="form-control" maxlength="255" type="password" id="UserLastname" required="required"/>
</div>
</div>
</div>
<div class="modal-footer">
<p style="text-align:left;"></p><div class="submit"><input class="btn btn-primary" title="Login" name="login" type="submit" value="Login"/></div><div style="display:none;"></div></form>
here is authenticate page code where user info get authenticate
<?php
if($_POST['login']){
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$m = mysql_fetch_assoc(mysql_query("select * from `register` where `email`='$email' and `pwd`='$pwd'"));
if(!empty($m['email'])){
if($m['status'] == 1){
$_SESSION['login'] = $m['id'];
$_SESSION['displayaname'] = $m['fname'].' '.$m['lname'];
header("Location: myaccount.php");
}else{
header("Location: reg_auth.php?msg=4");
}
exit();
}else{
unset($_SESSION['login']);
unset($_SESSION['displayaname']);
header("Location: reg_auth.php?msg=3");
exit();
}
}
if($_GET['msg'] == 2){
$msg = "Email Already Exists! Please Try Some Different Email.";
}
if($_GET['msg'] == 3){
$msg = "Invalid Username or Password! Please Try Again.";
}
?>

header("Location:http://localhost/form2.php");
exit();
Just change the url as you want.

Yes,
You need to use Session to store the information related to user once the user is successfully authenticated with the username and password field.
once the user is authenticated you can redirect to successful page, i mean allow them to access pages.
if user is not authenticated redirect them to login page again.
if session is expire redirect them to login page again.
Thanks
Amit

Yes this sounds correct.
So you'll have a script on your homepage with login&passw, posting infos to your checklogin.php.
There, you check if datas are correct, if they are correct you use sessions to set him as logged in.
After, you redirect him on to homepage with header() function.
Note that header() function will not work if set after html content but in your case, no html in checklogin.php right ? ;)

Related

Redirect not working with header("Location:

I've searched but can't seem to figure this one out. I have a config.php which searches for an active session and if found passes the user through, if not it fowards to the login.php page. The config.php also grabs the orginal URL and posts to login.php so we can redirect them to the page they were going to originally.
From there it should be pretty simple, authenticate and then use the redirect variable to forward browser to original page. But it's not working like that. It forwards me back to the login.php and says "Object Moved". Its redirects if I put header("location: /index.php"); but not if I use the variable in the login.php like below.
Any help would be appreciated!
PHP (config.php):
<?php
session_start();
// put somewhere in a config file
define('SESSION_EXPIRE',3600); // in seconds
// check passage of time, force log-out session expire time
if(isset($_SESSION['last_activity']) && (time() - strtotime($_SESSION['last_activity']) > SESSION_EXPIRE)) {
// destroy session
session_unset();
session_destroy();
}
// if user is logged in and unexpired, update activity
if(isset($_SESSION['user'])) {
// user is logged in
$_SESSION['last_activity'] = date('Y-m-d H:i:s');
}
// if user doesn't have session forward them to login page and post requested URL
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header ("Location: ../login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
}
?>
PHP (login.php):
<?php
include("authenticate.php");
// check to see if user is logging out
if(isset($_GET['out'])) {
// destroy session
session_unset();
$_SESSION = array();
unset($_SESSION['user'],$_SESSION['access']);
session_destroy();
}
// get orginal URL from config.php
$url = $_GET['location'];
// check to see if login form has been submitted
if(isset($_POST['userLogin'])){
// run information through authenticator
if(authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
header("location:".$url);
die();
} else {
// authentication failed
$error = 1;
}
}
// output logout success
if (isset($_GET['out'])) echo "Logout successful";
?>
HTML:
<div class="panel-body">
<form action="login.php" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="userLogin" type="Username" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="userPassword" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<input class="btn btn-lg btn-success btn-block" type="submit" name="submit" value="Login" />
</fieldset>
</form>
</div>
I am not sure if I understand your exact problem but if you are trying to redirect to $location and it is not going to the proper page or throwing an error then you may need to urldecode it before passing the variable.
in your config you encode the URI:
// if user doesn't have session forward them to login page and post requested URL
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header ("Location: ../login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
}
So in your Login decode it:
$url = urldecode($_GET['location']);
As mGamerz said make sure that your header has a capitol L and a space after the colon
header("Location: ".$url);
You need to remove login.php from here: action="login.php" You're losing the $url variable because it's not being included in the GET after the page posts back to itself.

Bug using PHP Sessions (Two Log On screens)

In the application I'm developing I'm having a bug where I direct my browser to my app's index.php, and is then properly redirected to login.php if there is no current session. My problem is that after I type in my correct details on login.php and click submit, I am linked to another login.php screen (instead of returning to index.php with an active session) and required to put in my details again. The first screen has the same CSS formatting as index.php, while the second screen doesn't.
After entering my details on the second screen and clicking login, the sessions seem to function normally. Also, many times I will be presented with one logon screen, ill login and the user's correct Home screen data will be displayed (which requires successful queries from the login data), but if I navigate away from index.php to another screen that requires an active session, it will present the unformatted login.php screen.
If I logout, navigate to a different non-restricted page, and attempt to log back in again within the same browser session, the logon functions correctly with only one screen.
Here are snippets from the relevant files:
index.php
<?php
include_once 'db_functions.php';
require_once 'access.php';
if (isset($_POST['action'])) {
if (userIsLoggedIn()) {
header('Location: http://www.myapp.com/index.php'); //prevents users from having to confirm form resubmission if they refresh the page
}
}
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
login.php:
login.php
<body>
<h1>Log In</h1>
<?php
if (isset($loginError)) {
echo $loginError;
}
?>
<form action="" method="post">
<div>
<label for="email">Email: <input type="text" name="email" id="email" /> </label>
</div>
<div>
<label for="password">Password: <input type="password" name="password" id="password" /></label>
</div>
<div>
<input type="hidden" name="action" value="login" />
<input type="submit" value="Log in" />
</div>
</form>
</body>
access.php:
<?php
function userIsLoggedIn() {
if (isset($_POST['action']) and $_POST['action'] == 'login') {
if (!isset($_POST['action']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '') {
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$email = $_POST['email'];
$password = $_POST['password'];
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
return TRUE;
}
else {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout') {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn'])) {
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password']);
}
}
function databaseContainsAuthor($email, $password) {
include_once './db_functions.php';
$db = new DB_Functions();
$result = $db->accountExists($email, $password);
return $result;
}
?>
Any help would be greatly appreciated!
UPDATE:
Error logs are showing multiple occurances of this error:
PHP Notice: A session had already been started - ignoring session_start() in /home3/monitot5/public_html/app/access.php on line 17
Access.php line 17:
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
What you should do is to use
session_start();
at the beginning of access.php file and don't use this function any more.
You should also completely change login of your access.php file. The first thing you should always do in this file is checking if there's a valid session for this user. Now you check it at the end of file and probably earlier you clear it because you unset session if there are no $_POST data.
In addition you shouldn't also use password in your session. It's rather very insecure. You should simple store login for your system when user filled in form valid username/email and password and unset it if user has logged out.
Sorry, but I won't write the whole code for you. You should simple look at some examples of code in Google to check how to handle user login/logout in PHP.

Redirecting to a new page after successful login

I'm sure this question has been asked before but I have searched thoroughly for an answer but to no avail. (The only answers I've seen involve ajax) But I'm using just javascript, PHP and HTML.
I have a login.php page and I have already created a HTML page which is to be the landing page right after a user is successfully logged in. How do I go about this?
The following is my code for the login page and the landing page after the login is called transfer.html:
LOGIN.PHP
<div id="content">
<h3>Login to Internet Banking</h3>
<form id="login" action="" method="post">
<p>
<label for="userid">UserID:</label>
<input type="text" name="UserID" id="UserID"/>
</p>
<p>
<label for="PIN">PIN:</label>
<input type="password" name="PIN" id="PIN" />
</p>
<p>
<input type="submit" name="btnSend" value="Login" class="submit_button" />
</p>
</form>
<td> </td>
<p>
Not yet registered?
Click here to register
</p>
<div id="wrap">
<!-- start PHP code -->
<?php
mysql_connect("localhost", "root", "") or die(mysql_error()); // Connect to database server(localhost) with UserID and PIN.
mysql_select_db("registrations") or die(mysql_error()); // Select registration database.
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['PIN']) && !empty($_POST['PIN'])){
$UserID = mysql_escape_string($_POST['name']);
$PIN = mysql_escape_string(md5($_POST['PIN']));
$search = mysql_query("SELECT UserID, PIN, active FROM users WHERE UserID='".$UserID."' AND PIN='".$PIN."' AND active='1'") or die(mysql_error());
$match = mysql_num_rows($search);
if($match > 0){
$msg = 'Login Complete! Thanks';
}else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
}
?>
<!-- stop PHP Code -->
<?php
if(isset($msg)){ // Check if $msg is not empty
echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and add a div around it with the class statusmsg
} ?>
</div>
</div>
First of all, move all your PHP code to the top. Without it, my code below wont work.
To do the redirect, use:
header('Location: http://www.example.com/');
Also, please consider my advice. Since it's not the first question today and all your questions are related to basics, you should consider reading some good PHP book to understand how things work.
Here you can find useful links to free books:
https://stackoverflow.com/tags/php/info
Javascript redirection generated with php code:
if($match > 0){
$msg = 'Login Complete! Thanks';
echo "<script> window.location.assign('index.php'); </script>";
}
else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
Php redirection only:
<?php
header("Location: index.php");
exit;
?>
Try header("Location:home.php"); instead of showing $msg = 'Login Complete! Thanks';
Hope it'll help you.
You need to set the location header as follows:
header('Location: http://www.example.com/');
Replacing http://www.example.com of course with the url of your landing page.
Add this where you have finished logging the user in.
Note: When redirecting the user will be immediately redirected so you're message probably won't display.
Additionally, you need to move your PHP code to the top of the file for this solution to work.
On another side note, please see my comment above regarding the use of the deprecated mysql statements and consider using the newer, safer and improved mysqli or PDO statements.
May be use like this
if($match > 0){
$msg = 'Login Complete! Thanks';
echo "<a href='".$link_address."'>link</a>";
}
else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
You could also provide a link to the page after login and have it auto redirect using javascript after 10 seconds.
Just add the following code after the final message you give using PHP code
Print'window.location.assign("index.php")

How to stop else showing as default on basic PHP login script

I am using PHP to build a very basic login script. However, the else from the ifelse statement shows by default before the user has even clicked log in.
Before the user has even tried to login they are greeted with this:
Warning: Cannot modify header information - headers already sent by (output started at /home/madhous3/public_html/dev/admin/index.php:12) in /home/madhous3/public_html/dev/admin/login.php on line 13
Sorry, please try again.
How do I stop this? However, if the user enters the details correctly, they are directed to the right page.
Code
index.php
<?php
include("login.php");
?>
<h1>Admin Area Login</h1>
<form method="post" action="login.php">
Username<input type="text" name="username" />
Password<input type="text" name="password" />
<input type="submit" name="log_in" value="Log In" />
</form>
login.php
<?php
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
}else{
header("location:index.php");
echo "Sorry, please try again.";
}
?>
Try removing the include("login.php") from index.php.
Instead, you should redirect back to index.php from your login.php with a flag specifying that the user entered the wrong information (if they failed the login).
index.php
<?php
if(isset($_REQUEST['fail'])) {
echo 'Login failed.';
}
?>
<h1>Admin Area Login</h1>
<form method="post" action="login.php">
Username<input type="text" name="username" />
Password<input type="text" name="password" />
<input type="submit" name="log_in" value="Log In" />
</form>
login.php
<?php
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
} else {
header("location:index.php?fail=1");
}
?>
OK, so what's happening is that in index.php you're including login.php at the start. At that time it imports everything from login.php. Since you're including it, the script is going to run.
At the load of the page index.php, the script on login.php starts. It defines those variables $username_inputted & $password_inputted as null, since the POST hasn't happened yet. Then the if block checks, finds null variables, then the else block fires since the variables aren't equal to the expected login info because they're null.
Therefore the echo fires and is displayed on the screen before anything is POSTed.
Nav_nav's solution should work well, since the only time the 'bad login' echo will be displayed is if someone entered something into the input fields, I just wanted to give you a rundown of the algorithm's reason for messing up.
try this
if (!empty($_POST['username']) && !empty($_POST['password'])) {
//define input vars
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
}else{
header("location:index.php");
echo "Sorry, please try again.";
}
}
First get rid of the header('location:login.php'). You can't send a header if you've already started sending any HTML to the browser. And if it did work, you'd get an endless loop of reloads.
Then:
You could check for $_POST ['submit'] and if it doesnt exist then don't show them the try again message.

user invalid login

I am creating my own website just to get some experience. I've been working on it for 3 days and am at the point where I can sign up and sign in.
When signing in, if the combination of the username and password is not found in the database, my code displays an error message telling the user that either he didn't sign up yet or he is entering a wrong user email or password.
But, the message is displayed in a new page, instead of the sign in page.
I looked at some tutorials online, but didn't find a good explanation for it. Could someone please give me some advise?
I am using PHP for the database connection.
I just typed a very basic example:
<?php
//login.php
$msg = ''; //to store error messages
//check whether the user is submitting a form
if($_SERVER['REQUEST_METHOD'] == 'POST') //check if form being submitted via HTTP POST
{
//validate the POST variables submitted (ie. username and password)
//check the database for a match
if($matchfound == TRUE) //if found
{
//assign session variables and other user datas
//then redirect to the home page, since the user had successfully logged in
header('Location: index.php');
}
else
{
$msg = 'Error. No match found !'; //assign an error message
include('login_html.php'); //include the html code(ie. to display the login form and other html tags)
}
}
else //if user has not submitted the form, just display the html form
{
include('login_html.php');
}
//END of login.php
?>
login_html.php :
<html>
<body>
<?php if(!empty($msg)) echo $msg; ?> <!-- Display error message if any -->
<form action="login.php" method="post">
<input name = "username" type="text" />
<input name = "password" type="password" />
<input name = "submit" type="submit" value="Submit" />
</form>
</body>
</html>
This is not a complete code. But I just created it for you to understand how this can be done. :)
Good luck
Your opening form tag should look like this: <form action="" method="post">. The empty "action" attribute will cause the page to post back to itself. Just check the $_POST for username and password to determine whether to test for a match or just show the form.
And please be sure to hash your passwords and sanitize your inputs!
you can do it without going to a new page.
<?php session_start(); ?>
<?php
if(isset($_POST) && isset ($_POST["admin_login"])){
$user_data_row = null;
$sql="SELECT * FROM table_name WHERE <table_name.field name>='".mysql_real_escape_string($_POST['email'])."'
and <table_name.field name='".mysql_real_escape_string($_POST['password'])."'
;
$result=mysql_query($sql);
$user_data_row=mysql_fetch_assoc($result);
if(is_array($user_data_row)){
$_SESSION['user_id'] = $user_data_row['id'];
header("Location: <your page name>");
}else{
$_SESSION['message'] = "Valid email and password required";
}
}
?>
<?php if(isset($_SESSION['message'])){
echo "<li>{$message}</li>";
?>
<form action="" method="post" id="customForm">
<label>Email:</label>
<input type="text" id="email" name="email">
<label>Password:</label>
<input type="password" id="password" name="password">
<input type="submit" value="Login" id="send" name="admin_login">
</form>
may be its helps you....
Basically what you need to do, is post the form to the same page.
Once you have that, at the type just check for the $_POST: if($_SERVER['REQUEST_METHOD'] == 'POST')
If it is a post, check the username and password and either show an error or redirect to the signed in page. After this, display the login form.
So, if it's an error, they'll get the error and then the login form. If it's not posted, they'll get just the login form, and if it's a valid login, they'll get redirected to the proper page before the login form is shown.

Categories