I started PHP recently and I was wondering :
I have a php file which only contains a function called sqlConnect(); which checks that the user isn't yet logged into the MySQL DB, and if so, redirects the user to an html page which is a form for the user to enter the username and password for the DB. After the user has submitted the form, I want to get back to the point where I left (in the function).
One thing you should know too is that the $_SESSION is started in another file which calls this function.
Here's what I tried, yet it didn't work :
connect.php :
<?php
function sqlConnect() {
$_SESSION['CurrentPage'] = "/php/sql/connect.php";
if(!array_key_exists('mysql_username', $_SESSION) && !array_key_exists('mysql_passwd', $_SESSION)) {
echo "<script>window.location='/forms/sql_login.php';</script>";
}
$servername = "localhost";
$username = $_SESSION['mysql_username'];
$passwd = $_SESSION['mysql_passwd'];
$db_name = "ToolDB";
// create connection
$sql_connection = new mysqli($servername, $username, $passwd, $db_name);
// check that it was established
if($sql_connection->connect_error) {
$msg = $sql_connection->connect_error;
echo "<script>alert('Impossible de se connecter à la base de données MySQL : $msg.');</script>";
return NULL;
}
else {
$_SESSION['mysql_username'] = $username;
$_SESSION['mysql_passwd'] = $passwd;
return $sql_connection;
}
}
?>
sql_connection.php :
<?php session_start(); $url = $_SESSION['CurrentPage']; ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Sound Department - Program Making Tool (form)</title>
<link rel="stylesheet" type="text/css" href="/style/style.css" />
</head>
<body>
<header>
<nav>
<h2 style="margin-left: 10px; font-family: sans-serif;">Sound Department - Program Making Tool (MySQL Login Page)</h2>
</nav>
</header>
<div class="bodyElement">
<form action="<?php echo $url ?>" method="post">
<p>Nom d'utilisateur : <input type="text" name="mysql_username" /></p>
<p>Mot de passe : <input type="password" name="mysql_passwd"/></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
</div>
</body>
</html>
Does anybody know how to achieve that ?
PS : I know I shouldn't store the password in plain text, but the site is running on my local network for now and I thought I was just gonna modify my code to store the password in a more convenient way later.
ob_end_clean();
header("Location: example.com");
exit();
Put this at the end where you want the user to be redirected.
Header() doesn't let you redirect after an output is given, but
ob_end_clean()
allows you to redirect after an output.
You can use the header() function to redirect clients to another page.
<?php
header('Location: <your page>');
exit;
?>
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.
Hello Stackoverflowers
Im new to PHP and im trying to make a members area for my testpage. I have made a successful register and login page, but now when I changed the code so if I log in correctly it redirects my to a page, and if I log in with wrong information it send me to a different page. However the members area is accessible if you type the location in the address-bar. Now, here's what I need help with, When someone tries to access that location without being logged in it should say "Access denied" but when you log in, it should redirect you to the members area and all it content is shown.
Here is my code:
login.php
<?php
session_start();
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'Data';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if(isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM Project WHERE username='$username' AND password='$password' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows($res) == 1){
header("Location: loggedin.php");
exit();
} else {
echo 'Användarnamn eller lösenord stämmer ej med informationen i databasen, var snäll försök igen <br>';
echo 'Gå tillbaka Eller Registrera dig';
exit();
}
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Logga in</title>
<script src="js/prefixfree.min.js"></script>
</head>
<body>
<div class="body"></div>
<div class="grad"></div>
<div class="wrapper">
<div class="header">
<div>bababa<span>bababa</span></div>
</div>
<br>
<div class="login">
<form method="post" action="login.php">
<input type="text" placeholder="Användarnamn" name="username" required><br>
<input type="password" placeholder="Lösenord" name="password" required><br>
<input type="submit" value="Logga in">
</form>
</div>
</div>
<script src='http://codepen.io/assets/libs/fullpage/jquery.js'></script>
</body>
</html>
signup.php
<!DOCTYPE HTML>
<html lang="sv">
<head>
<link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" >
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
});
$(".email").focus(function(){
$(".email-help").slideDown(500);
}).blur(function(){
$(".email-help").slideUp(500);
});
</script>
</head>
<div class="wrapper">
<h1>Registrera er här</h1>
<p>Detta är ett test-formulär för Webbutvecklingsprojektet. Skriv ditt namn här
under och om allt funkar rätt skall systemet lagra ditt namn i en MySQL databas.</p>
<form class="form" name="form" method="post" action="add.php">
<input type="text" id="username" name="username" placeholder="Användarnamn" required>
<input type="password" id="password" name="password" placeholder="Lösenord" required>
<input type="email" id="email" name="email" placeholder="E-mail" required>
<input type="submit" class="submit" value="Registrera dig">
</form>
<h3>
Allmänt & regler:
</h3>
<ul>
<li>Maximalt 2GB Lagring</li>
<li>Du måste skriva för- och efternamn</li>
<li>Databasen lagrar bara upp till 60 användare</li>
</ul>
</div>
<p class="optimize">
</p>
</html>
And last: loggedin.php
<?php
session_start();
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'Data';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if(!isset($_SESSION['username'])) {
die("Please login");
} else {
echo 'Du är inloggad';
}
?>
FTR: I tried the if isset but even when I logged in correctly the same message shows up: Please log in, how should I fix this?
Im a newbie at this so help me a bit extra
Thank you!
You can use Cookies or SESSION to do this.
When a user is authenticated, before redirecting to homeS page you should set a session variable like this: $_SESSION['id']=$user_id;. And if you want to set COOKIES so that user can access his account directly even after closing browser, you can set it like this setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // for 1 day.
So, now at the start of every page you need to start session session_start() to get the session value you set during login.
If a user_id of any user info exists in the session it will automatically use that info to access the page.
Now considering you want that the user is automatically redirected to login page/ACCESS DENIED if he tries to access home page.. You can do this by checking if the session user_info or cookie exist or not...if it doesn't redirect him to the login page or any error page as per you need...
In your code, before header("Location: loggedin.php"); create a session $_SESSION['username'] = $username;. And keep in mind to session_start() on every page, where $_SESSION value is going to be used..
What you would do is to redirect to a login page if user is not logged in.
if(!isset($_SESSION['username'])){
header('location: login.php');
}
I tried the if isset but even when I logged in correctly the same message shows up: Please log in, how should I fix this?
OK, when you log in succesfully, just before you redirect the user to the other page:
header("Location: loggedin.php");
you've to assign a session variable to the user, like this (for example. It depends how you want to identify them).
$_SESSION['ID'] = $row['ID'];
I think this is enought
By the way, please, don't use mysql_query
Use instead: mysqli extension.
(for more information)
Hope it helps
You have started the session session_start, but you haven't actually set the $_SESSION['username']. You need to set the session variable in between these two line.
if (mysql_num_rows($res) == 1){
// set session variable here
header("Location: loggedin.php");
exit();
}
Make sure you use the session_start() on the top of every page so that your able to check if the person who is viewing the page is logged in.
Also just another tip mysql_connect has been deprecated see here, you can use mysqli or PDO which escapes things automatically for you.
So I have this form that asks for user and password:
<?php
$emmagatzemarSessions="/u/alum/u1920477/public_html/tmp";
ini_set('session.save_path',$emmagatzemarSessions);
session_start();
include 'vars.php';
?>
<html>
<h1>Identificacio</h1>
<h3>Introdueix el teu usuari i contrasenya per entrar a oracle</h3>
<hr>
<form action="menu.php" method="post">
Usuari:
<input type="text"
name="user" />
Contrasenya:
<input
type="password"
name="pass" />
<input type="submit"/>
</form>
<hr>
<?php
$_SESSION["user"] = $_POST["user"];
$_SESSION["pass"] = $_POST["pass"];
?>
</html>
However, in the next file, 'menu.php' it says I couldn't acces the database. The user and password I'm inserting are correct. Here is the code to connect that I'm using:
#!/usr/bin/php-cgi
<?php
$emmagatzemarSessions="/u/alum/u1920477/public_html/tmp";
ini_set('session.save_path',$emmagatzemarSessions);
session_start();
include 'vars.php';
$conn = oci_connect($_SESSION["user"], $_SESSION["pass"], 'oracleps');
echo("username is: " . $_SESSION["user"]);
if (!$conn) {
echo "<p>No hem pogut connectar amb la BD.</p>";
?>
<html>
<br><br><br>
<div id="tornar">
<li>Tornar a l'inici</li>
</div>
<?php
die;
}
?>
<head>
<title>Menú empresa</title>
</head>
<body>
<div id="menu">
<h1>Menú</h1>
</div>
<div id="alta">
<ul>
<li>Donar d'alta un client</li>
<li>Consultar vehicles disponibles</li>
<li>Llogar un vehicle</li>
<li>Retornar un vehicle llogat</li>
<li>Veure revisions</li>
</ul>
</div>
<br><br><br>
<div id="tornar">
<li>Tornar a l'inici</li>
</div>
</body>
</html>
I have looked for similar questions, asked my collegues who are doing the same thing but I can't find out why this isn't working!
It would be amazing if I could get some help from you guys!
Thanks a lot.
Edited with the full code of both files. Ignore the 4 first lines. I hope you guys can help me because I have no clue what I'm doing wrong!
This line of code should be at the top of every php page where you want to track session:
session_start();
You should also always check if variables are really sent from the form, like this:
if(isset($_SESSION['username']))
{
// do something
}
If you are sure that your logic for connecting to the database is ok, you should log the data you receive from the form, to check if it is correct:
error_log("username is: " . $_POST["username"]);
Start a session on every page that can only be accessed by a user and if it is not set redirect the user
session_start(); //start session
if (!isset($_SESSION['user'])) {
redirect_user();
}
function redirect_user() { //redirect user to home page
$url = BASE_URL . 'index.php'; // Define the URL.
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); #quit
}
I am a beginner to PHP and i want to make a static method that if its argument is empty it'll show the message. If not, it'll set the given message to a static variable for later use. But when i call the method to set the message, and then call it in another page to show the message. Nothing appear.
Here's my portion of code for this "session.php" :
class Session {
public static $message;
public static function notify($message = ""){
if(!empty($message)){
self::$message = $message;
} else {
return self::$message;
}
}
}
$session = new Session();
"add_user.php" :
<?php
require_once '../helper/session.php';
?>
<?php
if (isset($_POST["submit"])) {
$user->username = $_POST["username"];
$user->password = $_POST["password"];
$user->first_name = $_POST["first_name"];
$user->last_name = $_POST["last_name"];
if($result = $user->add_user()){
Session::notify("New user added");
redirect_to("../view/login.php");
} else { Session::notify("Cannot add new user"); }
}
?>
"login.php" :
<?php
require_once "../control/add_user.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="../stylesheet/login.css" />
<title>Welcome to Harmony</title>
</head>
<body>
<header>
<h2>Harmony</h2>
</header>
<section>
<div id="formStyle">
<h3>Login or Signup:</h3>
<form action="login.php" method="post">
<p><label for="username">Username: </label>
<input type="text" name="username" value="" placeholder="Username"/></p>
<p><label for="password">Password: </label>
<input type="text" name="password" value="" placeholder="Password"/></p>
<input type="submit" name="submit" value="Submit" />
<input type="button" name="sign_up" value="Sign up" onClick="parent.location='add_user.php'">
</form>
<?php echo Session::notify(); ?>
</div>
</section>
</body>
</html>
You aren't really writing to the session, now are you?
You should create two more methods for getting and setting the variables in the actual session. After the redirect, your message dissapears, because it is only saved on script execution.
function set_notification($message) {
$_SESSION['notification'] = $message; }
function get_notification() {
if(!empty($_SESSION['notification'])) {
return $_SESSION['notification']; }
Something like that :)
Of course, for sessions to work, you should do a session_start() call in the beginning of the script. read more about them here
HTTP by nature is shared-nothing, so anything you do in one request is not available to any other request. You will need to use a shared datastore to persist these messages.
A database, memcache, even a text file on the server (assuming you are operating on a single server and are not load balancing multiple) are all choices.
You can use cookies on the client side to persist a small amount of data. But keep in mind its not a secure solution (without using encryption) and you are limited in the amount of data you can store in cookies.
HTTP - and PHP - is stateless. You need to use session variables to track data across sessions
http://www.php.net/manual/en/book.session.php
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
}
?>