<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query2 ="SELECT id, username, banned FROM login WHERE username ='$login_session'";
$result2 = mysql_query($query2) OR die($mysql_error());
$row = mysql_num_rows($result2);
if($row['banned'] == 1) {
die();
}
?>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "", "");
// Selecting Database
$db = mysql_select_db("", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: login.php'); // Redirecting To Home Page
}
?>
As you can see , im trying to stop people who are banned from loading profile.php
it doesnt stop the profile page from loading
thanks fred, that worked – KIXEYE
make it to an answer, ill mark as answered as soon as i can – KIXEYE
As per the OP's wish:
You're using the wrong function for $row. Either use one that will fetch a row as an array, or change if($row['banned'] == 1) to if($row == 1) to work with mysql_num_rows.
Footnotes:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Example pulled from https://stackoverflow.com/a/6620252/
$user = "bob";
$user = mysql_real_escape_string($user);
$result = mysql_query("SELECT COUNT(*) AS num_rows FROM my_table WHERE username='{$user}' LIMIT 1;");
$row = mysql_fetch_array($result);
if($row["num_rows"] > 0){
//user exists
}
Edit:
If your banned row contains 1 or 0 to check if they're banned, then add another parameter to your where clause. I.e.: WHERE username ='$login_session' AND banned !=1 if banned column is an int type. If not, wrap 1 in quotes.
This translates to WHERE username exists and is 'John' and banned does NOT equal 1. Or make it 0, it's your choice.
Then why don't you just fetch user who are not banned:
$ses_sql = mysql_query("SELECT username FROM login WHERE username='$user_check' AND banned <> 1",$connection);
$numofresult = mysql_num_rows($ses_sql);
Then check if it has a result:
if($numofresult > 0){
/* SUCCESS */
}
else {
/* BANNED */
}
To compromise SQL injections, use mysql_real_escape_string() function.
$user = mysql_real_escape_string($username,$connection);
But a better recommendation is to use mysqli_* prepared statement or PDO.
if($stmt = $connection->prepare("SELECT username FROM login WHERE username='$user_check' AND banned <> 1")){
$stmt->execute();
$stmt->store_result();
$numofresult = $stmt->num_rows;
$stmt->close();
}
mysql_num_rows() returns a number of rows, not the rows themselves.
You should use mysql_fetch_assoc() or similar function.
Related
When I change SELECT * to SELECT count(*) the script stops working altogether. How to I add a count(*) to this file and a statement if row count for $user >= 20 allow to INSERT else do nothing.
// Include needed files
include 'mysql.php';
// Connect to MySQL
connectMySQL();
//****** SECURITY CHECK *********
session_start();
if(isset($_SESSION['userid'])){
$user = mysql_real_escape_string($_SESSION['userid']);
//*******************************
// Retrieves variables through AJAX
$favid = mysql_real_escape_string($_GET['favid']);
// $favid = mysql_real_escape_string($_GET['favid']);
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
} else {
// Someone tries to directly access the file!
echo "Invalid session!";
}
Thanks!
Please do necessary steps to avoid SQL injection, also try using mysqli_* functions instead of mysql_* functions
$query = mysql_query("SELECT COUNT(*) as cnt FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$res = mysql_fetch_array($query);
// If it is not favourited, add as favourite
if($res[cnt] == 0){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($res[cnt] > 0){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
I got it resolved. The reason it wasn't working was it took both values into consideration ($user and $favid). As a result it was always either 0 or 1.
I had to create another mysql query with just one value in it ($user) and then I was able to get the row count. Thanks everyone!
try to use below query, using below query if requested user's session will be 20+ then only insert statement will execute else insert statement will be ignore.
INSERT INTO ajaxfavourites(USER,favid ,exptime)
SELECT 1 AS USER, 1 AS favid, NOW() AS exptime
FROM ajaxfavourites WHERE USER=1 HAVING COUNT(*) >=20;
So I have a log in script that creates a $_SESSION based on the username of the user logging in. On another page I wish to display content if the row for that user has a 1 in it. If it has a 0 in that row, then do not display the content. I am having issues here with no matter what I've tried, it does not display YES no matter the user I log in with.
test1 = 1
test2 = 0
<?
require_once 'dbinfo.php';
$sess = $_SESSION['authuser'];
$link = mysqli_connect($servername, $username, $password);
if (!$link) {
die('Could not connect: ' . mysqli_error($link));
}
mysqli_select_db($link, $database) or trigger_error(mysqli_error($link));
$acc = "SELECT username FROM admins WHERE username = '$sess'";
$result = mysqli_query($link, $acc) or trigger_error(mysqli_error($link));
ob_start();
while($row = $result->fetch_assoc())
{
if($row['access'] == 1)
{
echo 'YES';
}
elseif ($row['access'] == 0)
{
echo 'NO';
}
}
ob_end_flush()
?>
The solution was easy and Class pointed it out. Forgot to SELECT access... instead of username. Rookie mistake.
You have to write
session_start();
in all of your files that want to make use of $_SESSION .
And your select query will only output the username column, as you have selected only this one, try it with
SELECT * FROM admins WHERE username = '$sess'
or
SELECT username, access FROM admins WHERE username = '$sess'
instead.
What you absolutely should do is learning prepared statements, as your actual query is wide open to sql injections.
Prepared Statement example (from php.net)
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();
$stmt->bind_result($district);
$stmt->fetch();
$stmt->close();
}
$mysqli->close();
You can read more about mysqli prepared statements here
write access (column) and Try using isset() function and the operator === when you get 0 in a returned variable.
I change the simple SQL query to pdo.now when I click on the log in button I got this error:
Undefined variable: row in /var/www/login.php on line 16
Notice: Undefined variable: result in /var/www/login.php on line 17
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in /var/www/login.php on line 17 Your Login Name or Password is invalid
Code:
<?php
error_reporting(E_ALL);
ini_set('display_errors','5');
include("conn.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$u_name=addslashes($_POST['username']);
$password=addslashes($_POST['password']);
$sql="SELECT id FROM admin WHERE username='$u_name' and password='$password'";
$q = $conn->query($sql) or die("failed!");
$r = $q->fetch(PDO::FETCH_ASSOC);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
session_register("u_name");
$_SESSION['login_user']=$u_name;
header("location: main.php");
}
else
{
echo ("Your Login Name or Password is invalid");
}
}
?>
mysql_num_rows is a function, that is a part of the deprecated mysql_* extension. Just check the PDO manual here, and see how you can get the num-rows using PDO. You simply cannot use PDO and mysql(i)_* all together willy-nilly
You have many, many other issues in your code, including the query itself: SELECT id FROM will return a resultset in which each row has but a single column, called ID, but you go on to access $row['active']; in your code. That will issue a notice, because the index cannot be found.
Change the query to select all fields you actually do require SELECT id, active FROM... is the bare minimum, based on your code here.
Besides that, you're also wildly inconsistent as far as variable names go. What you call $r changes to $row the very next line... that's what's causing the undefined variable notices, of course.
You also have an injection vulnerability that is quite substantial, Here's how I'd query your data:
$stmt = $conn->prepare('SELECT id, active FROM admin where username = :user AND password = :pass');
$stmt->execute(array(
':user' => $_POST['username'],
':pass' => $_POST['password']
));
//$rowCount = $stmt->rowCount(); <-- only for update, delete or insert queries
$rowCount = 0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
++$rowCount;//count while fetching
//process row
}
//or
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowCount = count($rows);
foreach($rows as $row)
{
//process row
}
That said, you really should learn about prepared statements and hash your passwords
The $r = $q->fetch(PDO::FETCH_ASSOC); should be $row = $q->fetch(PDO::FETCH_ASSOC);
Also, the session_register() function is deprecated. You shouldn't be using that.
I've been modifying my code but I still can't log in... I have a MySQL database with a database called "users" with a table called "Users" and the following rows "UserNameID", "userName" and "password". I have created just an entry in order to test that:
+------------+----------+-----------+
| UserNameID | userName | password |
+------------+----------+-----------+
| 1 | root | pass |
+------------+----------+-----------+
Here my code:
<!DOCTYPE html>
<?php session_start(); ?>
<html>
<head>
<title>File1</title>
</head>
<body>
<?php
$DB_connection = mysqli_connect("localhost","user1","user1","users") or die("ERROR. Failed to connect to MySQL." . mysqli_error($DB_connection));
function SignIn() {
$usr = $_POST['user'];
$pw = $_POST['pwd'];
if(!empty($usr)) {
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
$result = mysqli_query($DB_connection,$query);
if($result) {
while($row = mysqli_fetch_array($result)) {
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
} else {
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY..."; } }
}
SignIn();
mysqli_close($DB_connection);
?>
</body>
</html>
When I introduce a wrong password or username, it gives me "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...". However, it throws me the same when I put the correct password and username. What is wrong in my code?
Thanks a lot!
There numerous issues here. There are scoping issues, you are using the wrong methods, it's unsafe.
First off, these 2 lines:
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
$result = mysqli_query($DB_connection,$query);
That's not how you query a database. You only need to call either mysql_query or mysqli_query depending on what API you are using. You are using MySQLi in this case, so do this:
$query = "SELECT * FROM Users where userName = '$usr' AND password = '$pw'";
$result = mysqli_query($DB_connection,$query);
Second, your SignIn function can't access the $DB_connection variable, it's out of scope. You need to pass it in:
function SignIn($DB_connection){
}
SignIn($DB_connection);
Third, this code is very unsafe! Never use $_POST directly in an SQL query like that. You should never be concatenating variables into an SQL string, you should use prepared statements.
// Don't use "SELECT *", use the fields you want
$query = mysqli_prepare($DB_connection, 'SELECT user_id FROM Users where userName = ? AND password = ?');
// This sends the values separately, so SQL injection is a thing of the past
mysqli_stmt_bind_param($query, 'ss', $usr, $pw);
// Run the query
mysqli_stmt_execute($query);
// Prepared statements require to define exactly the fields you want
mysqli_stmt_bind_result($query, $user_id);
// Get the data
while(mysqli_stmt_fetch($query)){
echo $user_id;
}
mysqli_stmt_close($query);
Lastly, storing plaintext passwords is bad practice. Use a hashing library. PHP 5.5+ has one built-in (http://php.net/password). There's also a version for lesser PHP versions (https://github.com/ircmaxell/password_compat).
P.S. As pointed out in the comments (here's a link), your session_start() is in the wrong spot. That sends a header, so it requires that there be nothing echoed out before it.
<?php session_start(); ?>
<!DOCTYPE html>
<html>
Make sure that there is no whitespace (or anything) before the session_start().
Your problem is here:
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
This should instead be
$query = "SELECT * FROM Users where userName = '$usr' AND password = '$pw'";
You're then passing the query string rather than a resource to mysqli_query.
(Also, refer to Shankar Damodaran's answer regarding the scope issue: pass $DB_connection to the SignIn function).
As a side note, you shouldn't use posted data directly into the query. You're at risk of SQL injection. Look into sanitizing the data or, preferably, prepared statements.
First of all, you are running into scope issues here.
In this line...
$result = mysqli_query($DB_connection,$query);
The variable $DB_connection is not accessible inside your SignIn() and thus your query is getting failed. Also you are mixing mysql_* (deprecated) functions with mysqli_* functions.
This simple and small code snippet for the login might help you..
$con = mysqli_connect("localhost","user1","user1","users") or die("ERROR. Failed to connect to MySQL." . mysqli_error($con));
$username = $_POST['username'];
$password = $_POST['userpassword'];
$result = mysqli_query($con,"SELECT * FROM users WHERE user_name = '$username' and user_password='$password'");
$count=mysqli_num_rows($result); // get total number of rows fetched. needs only 1 row for successful login.
if($count==1){
//Login successful
}
else{
//Login unsuccessful
}
It will fetch a row if the entered username and password are matched.It will fetch only one row as the username and password will be unique. If the count of rows fetched is '1' you can have successful login.
I have gotten a snippet of code to bring back the username and password and see if they match. i now want to set a session varaible to the 'points' value i have in the table which is in the same row as the username and pass.. what could be done?
<?php $username="asdin";
$password="1sdA2";
$database="a75sdting";
$pword = $_REQUEST['pword'];
$uname = $_REQUEST['uname'];
mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
$exsists = 0;
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
break;
}
if ($exsists){
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}
mysql_close();
?>
i want to set $_SESSION['points'] = $row[points] i guess... but i dont think that is correct
<?php
// start session (required on every page that uses sessions
session_start();
// db auth
$username="asdin";
$password="1sdA2";
$database="a75sdting";
// user auth
$pword = $_POST['pword']; // should use either $_POST or $_GET, NOT $_REQUEST
$uname = $_POST['uname']; // should use either $_POST or $_GET, NOT $_REQUEST
// open db connection
$conn = mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database,$conn) or die( "Unable to select database");
// check user
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
if(mysql_num_rows($query)){
// user exists
$row = mysql_fetch_assoc($query);
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}else{
header('Location: http://wwsdipts/login.php'); // take them back to login page if incorrect details
}
// close db connection
mysql_close($conn);
?>
I've tidied up your code a bit, please take a look at the notes. It is also worth nothing the following:
You should be using some sort of protection against SQL injections, such as mysql_real_escape_string($_POST['uname']) - the same for password
You need session_start() on all pages that use session variables
You shouldn't use $_REQUEST, use either $_POST or $_GET (read about it)
Do you actually have a table named username? You should read up a bit about DB design, a better name/use for this table would be users as the table will be holding users (a combination of unique ID, username & password.
I don't know what you mean about points, but to access any column name in the "username" table, use $row['column-name'] after it is set ($row = mysql_fetch_assoc($query);)
If you intend on using PHP a lot in the future, you should look up PDO, it's a great class for handling SQL.
you are right, but in this case your array is rows, and it should be in
$_SESSION['points'] = $rows['points']
And it should be in your while loop:
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
$_SESSION['points'] = $rows['points']
break;
}
However, it might be better to do something like this:
if(mysql_num_rows($result) == 1) {
//Login Successful
rows = mysql_fetch_assoc($result);
$_SESSION['points'] = $rows['points']
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}