So, firstly, I see you're using mysql_connect
, which is a deprecated function because it's not secure at all, and it's replaced by mysqli_connect
http://php.net/manual/en/book.mysqli.php for documentation. For even better security, and to protect against sql injection, you should use PDO, or prepared statements. In this example though, I have stuck to using mysqli
because it's less of a learning curve.
Secondly, $_SESSION
will only work if you first initialise the session using session_start()
. This will have to be done on every page that you wish to read or write session data from.
<?php
//Since this page writes to a session, initialise it here
session_start();
//The values to connect to the database with
$host = "localhost";
$user = "usern";
$password = "gtest123";
$db = "test";
//Create a new mysqli connection to the database
$conn = mysqli_connect($host, $user, $password, $db);
//This is the error message that's displayed on unsuccessful login
$error = "Login info are wrong!`enter code here`";
//This is the error message if the username is not specified
$errorNoUsername = "You have not specified a username";
/**
* Now that we're using mysqli_connect(), we don't need this code.
* mysql_connect($host,$user,$password);
* mysql_select_db($db);
**/
//See if the user has submitted the form with the username parameter
if(isset($_POST['username'])){
//If they have, shortname the variable for username and password
$userUsername = $_POST['username'];
$userPassword = $_POST['password'];
//Build your select query. In production, you should use PDO or Prepared Statements to protect against injection
//I've removed your LIMIT 1 from the query, because I see you're checking for a distinct match later on with mysqli_num_rows==1
$sql = "SELECT * FROM utenti WHERE username='".$userUsername."' AND Password = '".$userPassword."'";
//run the query on the connection created earlier
$result = mysqli_query($conn, $sql);
//Check if there's a distinct match
if(mysqli_num_rows($result)==1){
//There is, good, initialise session with the user data
$_SESSION['username'] = $userUsername;
//Reload to your index.php page
header("location:index.php");
} else {
//Display the error message
echo $error;
}
} else {
echo $errorNoUsername;
}
?>
So now that we've done that, assuming a successful login, we have redirected the user back to index.php
, since we are reading from session data, we need to initialise the session again, using session_start();
, which you've already done, but your key $_SESSION['']
doesn't exist, so there is an error. Here, I have corrected.
<?php
session_start();
echo "Welcome, " . $_SESSION['username']; //Added keyname
?>
<html>
all the html code
</html>