So I'm checking whether the person accessing the page is a user then redirecting them to the signup page if they're not.
Then I'm checking whether the user is a member ( paid subscription ) if not then redirect to the user page.
The redirecting for the non users work
But with the code below, noone can get access to the membership page because of the is_member check
<?php
error_reporting(0);
session_start();
include('connect.php');
ob_start();
if(!isset($_SESSION['username']))
{
header("**********");
}
else
{
$username =$_SESSION['username'] ;
}
$check = $mysqli->query("SELECT is_Member FROM users WHERE username = $username");
$row = mysql_fetch_assoc($check);
$isMember = $row['is_member'];
if ($isMember == 0){
header("*************");
}
is_member is either a 1 or a 0: 1 meaning they are a member
Connect file:
<?php
$servername = "*****";
$user = "*****";
$password = "*****";
$dbname = "******";
$mysqli = new mysqli($servername, $user, $password, $dbname); //used to connect to the database
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
?>
This
WHERE username = $username");
If the variable is a string (i.e.: "john", then it should be wrapped in quotes:
WHERE username = '$username'");
Then you're using a mysql_ function mysql_fetch_assoc which does not intermix with any other MySQL API than its own.
It must read as mysqli_fetch_assoc with the added i for the function.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
You should also add exit; after each header, otherwise you code may want to continue executing.
Another thing; your code is prone to an SQL injection. It's best that you use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
It appears that your check will always come up false because there is not is_member value, it is a typo. Replace this:
$isMember = $row['is_member'];
with this:
$isMember = $row['is_Member'];
Also your else statement should probably include more
Related
I'm a newbie in programming. I want to ask is there any way I can get user's data from MySQL in another page when they login in only with their username and password. What I'm facing is
I have a login page and main page
I have a user database that include user id, username, password and role_id
When the user login, I can get their username thru $SESSION, but what I really want is their role_id so I can use it as a condition to limit the user. Like Admin can get a header bar that has more button and function.
But when I tried to use sql query, it only shows table instead a single text that I can use. Any idea?
main page.php
<?php
// Initialize the session
session_start();
$user = $_SESSION['username'];
$conn = new mysqli('localhost','root','','mes');
$sql = "SELECT role_id from users where username = $user";
$result = $conn->query($sql);
echo $result;
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
// condition to limit the user
if( (isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] == true) && ($result === '202000') ){
include_once "premierHeader.php";
}
else{
include_once "header.php";
}
?>
WARNING as some people have already pointed out in the comment section, you're wide open to SQL injections (SQLI Attacks). I highly suggest you make use of parametized, prepared statements using either mysqli or PDO.
With that out of the way, I will be using mysqli prepared statements for my answer specifically.
What you need to understand is that when you get the result of your query, you will be given an object. To actually get a value, you will need to fetch(); it.
Example:
<?php
// Initialize the session
session_start();
// Username variable via session
$user = $_SESSION['username'];
// DB variables
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mes";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
// Declare the query
$sql = "SELECT role_id from users where username = ?";
// Prepare and bind
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $user);
// Execute the query
$stmt->execute();
// Bind result variable and fetch value
$stmt->bind_result($role_id);
$stmt->fetch();
// Close connection
$stmt->close();
$conn->close();
// Optionally, you can put the role id into a session variable
$_SESSION["role_id"] = $role_id;
?>
I am having an issue with connecting my PHP script to the database on my localhost server.
I have posted the code below, it is to enable user registration on the site.
The input boxes appear as they should when I run the code, but nothing updates to the database when I try and complete a sign up.
As a novice with PHP I don't know enough about it to spot any errors I might be making, or what they mean.
Any help on this subject would be appreciated as there is a lot of info about PHP online, but I would rather know what was causing this error in order to prevent it in the future.
Here are the errors appearing in the browser console:
Failed to load resource: the server responded with a status of 404 (Not Found)
ReferenceError: Can't find variable: $
And the UNIX socket code from MAMP (I don't know where this would fit in):
$user = 'root';
$password = 'root';
$db = 'inventory';
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
$link = mysql_connect(
$socket,
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
And the PHP code:
//connect to database
$db = mysql_connect("localhost", "root", "", "authentication");
if (isset($_POST['register_btn'])) {
session_start();
$username =mysql_real_escape_string($_post['username']);
$email =mysql_real_escape_string($_post['email']);
$password =mysql_real_escape_string($_post['password']);
$password2 =mysql_real_escape_string($_post['password2']);
if ($password == $password2) {
//create user
$password = md5($password); //hash password before storing for security
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
mysql_query($db, $sql);
$_SESSION['message'] = "Find a Table";
$_SESSION['username'] = $username;
header("location: HomePage.html"); //redirect to homepage
}else{
$_SESSION['message'] = "Your passwords must match to proceed";
}
}
?>
Where to start? So many problems.
First off, you are using the OLD mysql functions which have been removed entirely in recent versions of PHP. Use the mysqli functions instead. The old functions like mysql_connect and mysql_query have been deprecated. You need to look for all occurrences of mysql_ in this code and think about replacing each command with its new counterpart.
You define this code to connect:
$user = 'root';
$password = 'root';
$db = 'inventory';
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
$link = mysql_connect(
$socket,
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
and then you don't use the resulting connection -- even check if it worked. You should always check the value returned by mysqli_connect to see if it actually worked or if it returned FALSE. You reconnect again and don't bother checking to see if it worked:
//connect to database
$db = mysql_connect("localhost", "root", "", "authentication");
And in doing so, you redefine $db to something else.
Also, you run a query without checking whether it succeeded or not:
mysql_query($db, $sql);
$_SESSION['message'] = "Find a Table";
$_SESSION['username'] = $username;
header("location: HomePage.html"); //redirect to homepage
You should be checking the result of mysqli_query (not mysql_query as you have in your code) to see what it returned. It should be TRUE if the INSERT query worked.
And after you redirect, you fail to call exit, which means that all the code that follows your redirect attempt may end up actually executing anyway.
Somehow my conditional simply doesnt work. Once I click the button on my login form which is set to "post" and has the action defined as the below login script I only get directed to the script but not redirected as defined in my conditional statement. What is wrong with my code?
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$database = "project";
$connection = mysqli_connect($servername, $username, $password, $database) or exit(header("location:maintenance.php"));
function login_check() {
global $connection;
$name = $_POST['name'];
$password = $_POST['password'];
$prepared = mysqli_stmt_init($connection);
$request = mysqli_stmt_prepare($prepared, "SELECT id FROM members WHERE name = ? AND password = ?");
mysqli_stmt_bind_param($prepared, "ss", $name, $password);
$result= mysqli_stmt_bind_result($request);
$rows_counter = mysqli_num_rows($result);
mysqli_stmt_close($prepared);
if ($rows_counter > 0) {
$_SESSION['member'] = $name;
header("location:../../success.php");
}
else {
header("location:../../relogin.php");
}
}
Here is my input and approach to your code.
First of all before writing a solution and tell to much, it is always a good practice to make step by step code troubleshooting.
Before going and building a complete login system and put if statement or make prepare statement with inputs etc.
Make your solution in small working chops and put the puzzle together.
You question was focused on if statement and most of the help and answer was also focused on if statement which is nice, but the problem was not there.
I removed the if statement and a lot and just focused to see if I get some thing returned, I did not.
You $result= mysqli_stmt_bind_result($request); missed arguments, when that fixed, the next line missed also something else. I already there quit debugging.
I have rewrite your code and it works, what I did I have redefined the naming of variable so they are crystal clear to understand what is name, call it username, database username call it dbUser or dbUsername etc.
And if you want to check your code returning some thing or not, use var_dump($someVariable).
Last thing, before making a post form, you could create a dummy username and password in your database and inject that directly in your code like, just to see if every thing is working, and then move to your form:
$username = "user1";
$password = "1234";
The solution I did is just to demonstrate how to do it and not necessarily representation of the best logic, but it is up to you to find the correct logic and all depends on your strategy.
Here is my suggestion:
<?php
session_start();
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "product";
$connection = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
// Check connection
if ($connection->connect_error)
{
header("location:maintenance.php");
exit();
// or for debugging, activate following line
//die("Connection failed: " . $connection->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
//if username and password empty stop login
if (!$username || !$password)
{
//do something, die is only example
die ("Not all the fields were filled in");
} else
{
login_check($username, $password);
}
function login_check($username, $password)
{
global $connection;
//sql statements is corrected, change field name to username
$sql = "SELECT * FROM `members` WHERE `username` = ? AND `password` = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$output = $stmt->get_result();
$row = $output->fetch_array(MYSQLI_NUM);
$stmt->close();
//print what comes out in $row
//print_r($row);
//check if $row has data
if ($row)
{
echo "success do something";
$_SESSION['member'] = $username;
} else
{
echo "fail do something";
}
}
After defining the function login_check(), you should also call it (if the conditions are right):
function login_check() {
// your implementation as above
}
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
As a side note, it is good practice to also explicetely close the connection before redirecting.
Edit
as KhomeHoly comments, only call the function when necessary...
You need to call your functions if you define them. Not doing so is like building a room within a new house but forgetting the door. It's there, but nobody can use or access it.
So what you need to do is the following:
// your script as it is right now
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
With isset() you check if the certain $_POST parameters are set, but not validated. You should at least do a basic validation of the data to see if they are correct!
Something like this would work, depends on your requirements
if (isset($_POST['name']) && strlen($_POST['name') >= 4 && isset($_POST['password']) && strlen($_POST['password']) >= 4) {
login_check(); // actually call the function
}
The code above would check if those paramters are set and check if name and password are at least 4 characters long. (I wouldn't accept usernames lower than 4 chars personally, passwords should be at least 8 for me)
Now of course this misses an correct error reporting and all that stuff, but I think that should give you the basic idea based on your quesiton.
Always, always, always put exit() after header redirect call. Even in that case, it might solve your issue.
header("location:../../success.php");
exit();
Why?
I just set up the prepared query selection but it seems like it does not work.. It shows blank page instead of the content it should show..where is problem?
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $mysqli->prepare('SELECT configured FROM members WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()) {
if($row['configured'] == ""){
if (isset($_SESSION['user_id'])) {
?>
With this code I want to check if user has configured his settings and so if yes, then if he is logged in. But the page shows nothing even though I have there everything correct after that code I posted...
You're using $conn to connect with, then $mysqli in your prepare statement.
This
$stmt = $mysqli->prepare
Which should read as
$stmt = $conn->prepare
Also make sure you've started the session.
http://php.net/manual/en/function.session-start.php
Check for errors:
http://php.net/manual/en/function.error-reporting.php
and you have 3 missing closing braces in your posted code.
I see you're using $username = ""; in your DB connection and then using the same variable to bind with.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
The codes I'm working on are a bit confusing since I didn't make this one. But what I want to do is get the login information from a different database. I can't just modify the config.php of the database connection cause it will mess up the whole system.
I tried the trick to connect 2 databases by storing different variables on mysql_connect. But in this case, its a bit confusing.
Is there another way to just change the database connection only once in the logging in process?
login.php (the php file once the login info is submitted)
include("inc/config.php");
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM clients WHERE name = '$name' AND password = '$password'";
$result = mysql_db_query($database, $query, $connection);
$date_in = date("Y-m-d");
$time_in = date("H:i:s");
$client_accesslogin = $name;
if (mysql_num_rows($result) == 1)
{
session_start();
session_register('time_in');
session_register('date_in');
session_register('client_accesslogin');
session_register('remoteaddr');
$_SESSION['time_in']=$time_in;
$_SESSION['date_in']=$date_in;
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$client_accesslogin = $_SESSION['client_accesslogin'];
session_register("client_id");
session_register("client_name");
session_register("client_email");
session_register("client_company");
list($clientid, $name,$first_name,$last_name, $pass, $email, $company) = mysql_fetch_row($result);
$client_id = $clientid;
$client_name = $name;
$fname=$first_name;
$lname=$last_name;
$client_email = $email;
$client_company = $company;
$cisloggedin = 'Yes';
session_register("cisloggedin");
session_register("fname");
session_register("lname");
header("Location: menu.php");
mysql_free_result ($result);
mysql_close($connection);
}
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM admins WHERE name = '$name' AND password = '$password'";
$result = mysql_db_query($database, $query, $connection);
$date_in = date("Y-m-d");
$time_in = date("H:i:s");
$accesslogin = $name;
if (mysql_num_rows($result) == 1)
{
session_start();
session_register('time_in');
session_register('date_in');
session_register('accesslogin');
session_register('remoteaddr');
$_SESSION['time_in']=$time_in;
$_SESSION['date_in']=$date_in;
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$accesslogin = $_SESSION['accesslogin'];
session_register("client_id");
session_register("client_name");
session_register("client_email");
list($clientid, $name, $pass, $email) = mysql_fetch_row($result);
$client_id = $clientid;
$client_name = $name;
$client_name = "admin";
$client_email = $email;
$isloggedin = 'Yes';
session_register("isloggedin");
header("Location: menu.php");
mysql_free_result ($result);
mysql_close($connection);
}
else
{
mysql_free_result ($result);
mysql_close($connection);
header("Location: index.php");
exit;
}
?>
That works. But If I remove the included config.php and just add the connection:
$database = "invoices";
$user = "root";
$pass = "";
$hostname = "localhost";
It doesn't login. I don't get it. the inc/config.php has some codes with the connection but why can't i just add the connection itself without using include?
I'm doing to assume that there's a dedicated page for login processing?
In which case you can just make a new config.php and connect to that db only on the login page?
A bit of your code or structure would help.
mysql_select_db() function sets the active MySQL database.
Syntax
bool mysql_select_db ( string database_name [, resource link_identifier])
mysql_select_db() attempts to select existing database on the server associated with the specified link identifier.
Returns TRUE on success, or FALSE on failure.
We can select database in mysql server by using mysql_select_db function. mysql_select_db() selects the current active database on the server that is associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to set a link as if mysql_connect() was called without arguments.
Made a function to connect to your database, also to close your connection.
function connect(user, pass, location)
function disconnect()
then you connect to your first db, do your operations. Close it and then open a new connection to the other db and do also your operations.
If you want to maintain 2 connections at the time, you could save your instances to variables
and do:
mysqli_select_db($instance1, 'SELECT ...');
mysqli_select_db($instance2, 'SELECT ...');
Also escape your variables in your query :)