I am makeing a sensitive page that no other user could access without being admin. But when i try to visit that page without being admin it works !
All users are not admin, So they should not be able to access it.
But the page loads fine for them (non admins).
PHP code:
function isAdmin(){
$admin = mysql_query("SELECT `admin` FROM `users` WHERE `username` = '".$_SESSION['username']."'");
if(!($admin)){
echo 'You are not authorised';
return false;
}else{
return true;
}
}
The code on sensitive page:
if(isAdmin()){
$name = $_POST['name'];
$description = $_POST['description'];
$image = $_POST['image'];
$amount = $_POST['amount'];
$sql = "INSERT INTO `store`(`name`, `description`, `price`, `image`) VALUES ('$name','$description','$amount','$image')";
mysql_query($sql);
echo 'Done!';
}
When i post data to this page , it loads and echoes Done! but it should not because:
Current User is not an admin
So, isAdmin() return false
then if(isAdmin()) receives false
So the if statement should not execute.
Yes, I have all these:
Mysql connection
PHP server with correct php.ini
Correct configuration my my users table
The column admin in my Mysql users table is int
You are basing your if condition on whether your query is syntactically correct or not. Since your query is valid, its always going to return something other than false.
use mysqli_num_rows instead.
if(msyql_num_rows($admin)<1)){
echo 'You are not authorised';
return false;
}else{
return true;
}
}
Take count instead of resource value. check below code
function isAdmin(){
$admin = mysql_query("SELECT `admin` FROM `users` WHERE `username` = '".$_SESSION['username']."'");
$count = mysql_num_rows($admin);
if(!($count)){
echo 'You are not authorised';
return false;
}else{
return true;
}
}
Related
I am building a log in system and every other part works perfectly fine except for the portion that cross references the entered password with the password in the database. So when I checked to see if the passwords match I realized that the password from the database is coming back as null. May I ask what is happening?? (There is no issue with the "uidExists" method, it seems to just be in the "loginUser" method).
This is based of of this video https://www.youtube.com/watch?v=gCo6JqGMi30
I believe its around the hour and 40 minute mark he gets to the loginUser function.
function loginUser($conn,$username,$pwd){
$uidExists = uidExists($conn,$username,$username);
if($uidExists === false){
header("location: ../login.php?error=wrongslogin");
exit();
}
else{
echo $pwd;
if(is_null($uidExists["userPwd"])){
echo "Empty bruv";
}
else{
echo $uidExists["userPwd"];
}
}
function uidExists($conn,$username,$email){
$sql = "SELECT * FROM users WHERE userUid = ? OR userEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt,"ss",$username,$email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
if(mysqli_fetch_assoc($resultData)){
return $row;
}
else{
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
This doesn't look right:
$uidExists = uidExists($conn,$username,$username);
Should this be:
$uidExists = uidExists($conn,$username,$userPwd);
If user is logged in then if his mobile number is verified then he will allow to move index.php else he will move to mobileverify.php. So i write a function and call this function in index page if unverified user tries to move in index.php function will redirect him mobileverify.php but function is not working please see the code below and tell me where i am wrong
function mobile_verify(){
if(isset($_SESSION['user_id'])){
$login = $_SESSION['user_id'];
$query =mysql_query("SELECT * FROM `users` WHERE `user_id`='$login'");
$row = mysql_num_rows($query);
$verify = $row['verify'];
if($verify === ""){
header('Location: mobileverify.php');
exit();
}
}
}
mysql_num_rows($query);
returns the number of rows in the result set not the values.
try
$row = mysql_fetch_array($result);
you are basically fetching the no of rows meeting your WHERE clause.
IT DOES NOT RETURN THE DATA ITSELF
you could use
$row = mysql_fetch_array($query);
and then check
$verify = $row['verify'];
if(!$verify){
header('Location: mobileverify.php');
}else{
header('Location: index.php');
}
end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}
I want to update the lastlogin column value .i wrote the code like this ,but column is nt updated .i wrote the some code in main.js for inserting query.here i didnt wrote any code for updating the lastlogin column value in main.js.
for updating the lastlogin column i wrote the updatelogin function in the dbfunc.php as below.
function updatelogin($lastlogin)
{
alert("hi");
$query="UPDATE users set last_login='$lastlogin' where email='".$email."'";
$queryresult= mysql_query($query);
$count=mysql_num_rows($queryresult);
if($count>0)
{
return 1;
}
else
{
return 0;
}
}
function register($details_arr)
{
$emailcheck=db_func::checkemail($details_arr['email']);
if($emailcheck == 0){
//print_r($details_arr);
$regemail=$details_arr['email'];
$regpwd=$details_arr['password'];
$zip=$details_arr['zip'];
$secqun=$details_arr['secqun'];
$answer=$details_arr['answer'];
$now=date("Y-m-d H:i:s",time());
$lastlogin=date("Y-m-d H:i:s",time());
$query= "INSERT INTO users (email,md5pwd,zip,squestion,sanswer,member_since,last_login,last_ip) VALUES('".$regemail."','".$regpwd."','".$zip."','".$secqun."','".$answer."','".$now."','".$lastlogin."','".$_SERVER['REMOTE_ADDR']."')";
$queryresult=mysql_query($query);
echo mysql_error();
if($queryresult)
{
non_db_func::loginuser($email);
db_func::updatelogin($details_arr['lastlogin']);
return 1;
}
else
return 0;
}
else{
return 2;
}
can any one tell me ,why lastlogin column isnt updated in my db
The problem is that in function updatelogin($lastlogin) you have not defined what $email will hold.
IF you echo your query after your query update statement (after $query = UPDATE .....)
echo $query
you will see what your problem is.
Update 1
I think you should have something like this before $query statement
$email=$details_arr['email'];
OR
pass $email value in function as updatelogin($lastlogin, $email)
Either you have a mysql error you don't see or the email address you are trying to find does not exist.
You have to pass $email in function updatelogin
Because $email will not be accessible inside updatelogin
And other thing you used $email instead of $regemail in your update query.
Can you Please Replcae your functions with below one and try again !
function updatelogin($lastlogin,$email)
{
$query="UPDATE users set last_login='".$lastlogin."' where email='".$email."'";
$queryresult= mysql_query($query);
$count=mysql_num_rows($queryresult);
if($count>0)
{
return 1;
}
else
{
return 0;
}
}
function register($details_arr)
{
$emailcheck=db_func::checkemail($details_arr['email']);
if($emailcheck == 0){
//print_r($details_arr);
$regemail=$details_arr['email'];
$regpwd=$details_arr['password'];
$zip=$details_arr['zip'];
$secqun=$details_arr['secqun'];
$answer=$details_arr['answer'];
$now=date("Y-m-d H:i:s",time());
$lastlogin=date("Y-m-d H:i:s",time());
$query= "INSERT INTO users (email,md5pwd,zip,squestion,sanswer,member_since,last_login,last_ip) VALUES('".$regemail."','".$regpwd."','".$zip."','".$secqun."','".$answer."','".$now."','".$lastlogin."','".$_SERVER['REMOTE_ADDR']."')";
$queryresult=mysql_query($query) or die(mysql_error());
if($queryresult)
{
non_db_func::loginuser($email);
db_func::updatelogin($lastlogin,$regemail);
return 1;
}
else
{
return 0;
}
}else{
return 2;
}
}
There is an error in your code, first. alert('hi) is a javascript function. try print_r('hi) in the future, second. Your mysql is incorrectly formatted.
$query="UPDATE users set last_login='$lastlogin' where email='".$email."'";
You have escaped $email but not $lastlogin. Try this:
$query="UPDATE users set last_login='".$lastlogin."' where email='".$email."'";
Also as mentioned you need to pass $email into your function to use in mysql
I have this class am using to perform queries - insert, delete, drop create etc, but this time i created a method to update a table when the update have been submitted and to my surprise and hours of headache it is return success but not actually updating the record in the database am so confused, I have been debugging for hours to no avail
so i decided to share my worries to see if i can receive help as am actually 2 weeks old In OOP PHP
so here my class
class queryClass extends MYSQL{ //MYSQL is for connecting to database
//table fields
var $user_table = ''; //table names that will be used in all names, each query method will input its own table name
//connect to database
function dbconnect(){
MYSQL::dbconnect();
}
//prevent injection
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via qry function that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
//quote form
function quoteEditorform($formname, $formclass, $formaction, $helptext, $first, $second){
//conect to DB
$this->dbconnect();
echo"
<form name=\"$formname\" method=\"post\" id=\"$formname\" class=\"$formclass\" enctype=\"application/x-www-form-urlencoded\" action=\"$formaction\">
<h2>$helptext</h2>
<div><label for=qoute>NGWA QUOTE
<input type=button value='Quote' onclick=\"wrapInTags(this.form.message1,'quote')\">insert [quote].[/quote]tags
</label>
<textarea name=\"message1\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$first</textarea><br>
</div>
<div><label for=\"qoute\">ENGLISH MEANING
<input type=button value='Meaning' onclick=\"wrapInTags(this.form.message2,'meaning')\">
insert [meaning].[/meaning]tags
</label>
".$record['meaning']."
<textarea name=\"message2\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$second</textarea></div>
<input name=\"action\" id=\"action\" value=\"sendeditedquote\" type=\"hidden\">
<div>
<input name=\"submit\" id=\"submitV value=\"Save\" type=\"submit\"></div>
</form>
<div align=\"center\">Read Before Posting</div>
"; }
function createquotetable($tablename){
//connect to DB
$this->dbconnect();
$qry = "CREATE TABLE IF NOT EXISTS ".$tablename."(
quote_id INT(8) NOT NULL AUTO_INCREMENT,
ngwaquote TEXT NOT NULL,
meaning TEXT NOT NULL,
saved_date date,
PRIMARY KEY (quote_id)
) TYPE=INNODB
";
$result = $this->qry($qry);
return;
}
here's my quote-editor.html after including my class files
// instantiate all other needed classes
$cleaner = new cleanPost();
$connect = new MySQL();
$connect->dbconnect();// connect to a database
$bbcode = new BBCode();
$log = new logmein();
if($_REQUEST['action'] == "sendeditedquote"){
//post all the values to the database using our main class
/*topic field checking */
if($_REQUEST['message1'] == "" || $_REQUEST['topic'] > 600) {
$errmsg_arr[] = 'Sorry You Can\'t Send An Empty Qoute OR quote greater than 500 characters at a time';
$errflag = true;
}
if($_REQUEST['message2'] == "" ) {
$errmsg_arr[] = 'Sorry You Can\'t Update With An Empty Qoute';
$errflag = true;
}
//If there are input validations, redirect back
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: edit_quotes.html");
exit();
}
$log->updatequote("quotes", $_REQUEST['message1'], $_REQUEST['message2'], "quote_id", "ngwaquote", "meaning", $cleaner->clean($_GET['quote_id']));
}
ai'ght when i perform the query the success/error line returns that the update was successful but on the other page where i display all available quotes the particular quote still is NOT updated
Anyone who's experienced such please tell me what am gon' do.
BEING ASKED THE LINE FOR THE RAW QUERY
HERE IS IT-
first is the the method that cleanse ouy my post and the I use it for query using $this->qry(somequeries here)
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function using $this->qry()
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via ****qry function**** that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
If the where clause of your update statement does not match any rows, the update statement will return success.
However it will not change anything.
Note that MySQL knows when a value has not really changed so the statement
UPDATE table1 SET col1 = 0 WHERE col1 = 0
Will always return 0 for the number of affected rows.
If you want to know if anything has been changed you need to call:
$rows_updated = mysql_affected_rows($this->connection);
or
$rows_updated = mysqli_affected_rows($this->connection); //if you're using mysqli
An update statement will only indicate failure is an error has occured.
A warning about SQL-injection
I notice that you use dynamic table and column names.
If those values are in any way alterable by a user or pass through superglobals that can be affected by another php session that can be affected by a user, you have an SQL-injection hole.
Here's how to secure yourself against that: How to prevent SQL injection with dynamic tablenames?
I think i have found the answer to my problem
In the place i had the $this->quote_id i later figured out that the page editor url was editor.html?quote_id=1
then when I submitted it will now process the form on a flat url === editor.html so my mistake was that I didn't request for the QUOTE ID when i was still on the editing url editor.html?quote_id=1 instead requesting for it when it was not possible ie in editor.html so it was meant to return empty quote id which i used to update thereby resulting in update success but not really updating anything
so
all I did was add an input tag hidden to get the quote_id being edited and then post it along with the rest of the form
So simple but took me me hours of rereading and re coding, wonderful,
small things cause much frustration
Thanks all
if the fields you are updating is not the same has the fields in the database, it will not update. although it return success simple means that it sees the table and connect to the database