PHP Select Value & Redirect With If Statement - php

I'm trying to create a php scipt that checks if members are verified as they land on a page. If they are not they get redierected to login with an error message & instructions. So on the page I have this code:
<?php
if (loggedin()) {
$check_active = "SELECT active FROM members WHERE username == '$username'";
$active = mysql_query($check_active);
if ($active < 1) {
header("Location: login.php?verify=true");
} else {
exit();
}
}
?>
It is redirecting the user back to the login page but it doing it whether they are active or not. The values for active members are 0(not verified) & 1(verified). Is htere something wrong in the script I'm using?
Thank You

You'll need to handle the $active result and put it into a PHP variable/array. $active as it is in your code is simply a resource (see here) Try this:
$active = mysql_query($check_active); // run query and return resource
$row = mysql_fetch_assoc($active); // put resource data into php array
if ($row['active'] < 1) {
header("Location: login.php?verify=true");
} else {
exit();
}

Please don't use old mysql, use mysqli_ or read topic on http://php.net/manual/en/function.mysql-query.php.
Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

You aren't fetching the data correctly after the query.
Right after you do the the mysql_query function. Try this:
$output = mysql_fetch_assoc($active);
$active_result = $ouput['active'];
Don't know if it might work.
And add a little more security for SQL injection there.
And use MySQLi instead since you aren't keen on preventing SQL injection yourself.

Related

multiple mysqli delete codes on one PHP page

I am still learing PHP and MySQLI and was wondering if it is possible to host multiple MySQLI delete queries on a single php page and have the url act on the corresponding query without confusion. I have this code here, I have search the web for an answer for 3 days but nothing I found seemed to be what I was looking for. Any help or properly described examples based on my code would be greatly appreciated.
my Code is:
<?php
session_start();
include ('dbconnect.php');
$userr = $_SESSION['usr_id'];
$uid=$_GET['pid'];
$pid=$_GET['phid'];
$user_id=$_GET['user'];
$fileID=$_GET['file'];
if($userr==$uid && $pid==$fileID){
echo "ERROR No. 9B2AP";
}else{
mysqli_query($con,"delete from images where userID='$uid' AND PhotoID='$pid'") or die (mysqli_error());
header ("location: /viewImage.php?pid=$uid");
}
if($userr==$user_id && $fileID==$pid){
echo "ERROR No. 39V41";
}else{
mysqli_query($con,"delete from music where userID='$user_id' AND Record_ID='$fileID'") or die (mysqli_error());
header ("location: /users/music-gallery/$user_id");
}
?>
No matter how many times I rewrite this code, when i delete an image or song using the code on this page, It redirects me only to the /users/music-gallery/ instead of the proper associated page. How might I get this fixed? Like I said, I am fairy new to PHP and MySQLI and any suggestions I believe should be described in details so I might be able to understand and comprehend how I made the mistake and I to fix and prevent it from happening again in later code. Please and Thank-you.
-M.S
For security reasons don't do this:
// Consider escaping the incoming data for better security
$uid=$_GET['pid'];
$pid=$_GET['phid'];
// ...
Since you are using MySQLi you can use this to escape your data:
$uid = mysqli_real_escape_string($con, $_GET['pid']);
You can use FILTERS to check input data type:
// If you are expecting an `INT` from $_GET['pid']
if (filter_var($_GET['pid'], FILTER_VALIDATE_INT))
{
echo 'pid is an int';
}
else
{
echo 'pid is not an int';
}
more on filters here.
The best of all, use prepared mysqli statements with stmt:
// prepare the statement
$stmt = $con->prepare("delete from images where userID=? AND PhotoID=?");
// bind variables to the '?' and set types --> `i` = integer
$stmt->bind_param("ii", $_GET['pid'], $_GET['phid']);
// execute query
$stmt->execute();
// Do the same for the next query
more on prepared statements here.
To solve your problem:
To exit a program right after a header you need to use exit(); after each header like this:
header ("location: /viewImage.php?pid=$uid");
exit();
For instance:
header ("location: /viewImage.php?pid=$uid");
// this line of code gets exucuted
// this too
// ...
header ("location: /viewImage.php?pid=$uid");
exit();
// Nothing gets executed as program terminates and redirects

PHP code allows logging in without correct password

I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php

PHP MYSQL Warning: mysql_query() expects parameter 1 to be string, resource given in

<?php
include 'connect.php';
include 'header.php';
$page = "signup.php";
// receive the invite code:
$code = $_POST['code'];
$sql = "SELECT codes FROM invites WHERE codes='$code'";
// check the table for matching codes
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) {
// end any previously defined sessions.
session_start();session_unset();session_destroy();
// start a new session
session_start();
// define the session variable.
// this allows us to check if it's set later and is required for
// the script to run properly.
$code = $_POST["code"];
mysql_query("DELETE FROM invites WHERE codes='$code'");
header('Location: '.$page);
exit;
} else {
echo "Invite invalid. Please try again later.";
echo $code;
}
include 'footer.php';
?>
I am trying to implement an invite system to a webpage I am working on. However when trying to evaluate if there is a row containing the invite code I keep either getting nothing or this warning. The warning in this case but if I change the if state to ==1, it allows everyone regardless of code and ==0 does throws different errors.
if (mysql_query($result)) {
Try mysql_num_rows there.
There are a few things wrong here.
1) SQL Injection vulnerabilities, don't ever pass a superglobal $_POST or $_GET or any other user-supplied variable directly inside your query!
Use at minimum mysql_real_escape_string() to the variable before letting it into the query, or better look into parametrized queries, it's the best way to avoid SQL vulnerabilities
2)
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) ....
This doesn't check if request returns 1 or 0 rows, you should use mysql_num_rows() here instead
if(mysql_num_rows() == 1) //or whatever you need to check
3)
session_start();session_unset();session_destroy();
// start a new session
session_start();
session_start() should be called before anything in your page. Don't know why this redundancy of calling, unsetting, destroying, recalling it here. If you want another id, just use session_regenerate_id();
And as already said by other, use some error reporting in your query, something like
$result = mysql_query($sql) or die(mysql_error())
to actually see what's failed, where and why.
Problem is your query. First of all check your statement and use this :
$result = mysql_query($sql) or die(mysql_error());
instead of this
$result = mysql_query($sql);
So, you can see are there any error at your SQL query .

how to get the session id

please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.

Log.php returning 'Invalid User' from MySQL database

I am hosting a website from a local computer (using MAMP Pro on a Mac), and need to switch the hosting to another local Mac. I have copied across all of the files for my website, and the MySQL tables, and checked that the server and MySQL are running OK. Everything seems to be fine, except that the login system is returning "Invalid User" when I try to log in, even though I am entering the correct user info (I have tried a few users just to be sure).
The log.php that handles the login looks like this:
<?
session_name("MyLogin");
session_start();
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","root","password"); // your MySQL connection data
$db = mysql_select_db("nick"); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM USERS WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/may.php"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
I have temporarily removed the password in the above code.
I wonder what steps I can take to troubleshoot this issue, and would be grateful for any help.
Thanks,
Nick
A few common techniques when I encounter this issue.
Output the generated SQL and test it by hand - echo $query;
See if mysql_error() outputs anything after you run your queries.
Use var_dump() and print_r() on your data objects to ensure they are as expected.
Comment out your redirects and exit() lines so you can determine where the script is breaking.
Fix or comment back with anything determined by the above.
Your code does a query to find a user with the given username, and then checks if the number of rows with that username is exactly 1.
The only way you could see the 'Invalid User' error is if there are 0 users with that username or more than 1 user with that username.
Have a look at the contents of the table and check which of these is the case (I recommend http://sequelpro.com for viewing database contents on a Mac). You can also use sequel pro to test your queries.

Categories