PHP program is negating a function? - php

So basically what I have set up here is a very simple and generic log in. I have the entire code copy and pasted because maybe its important somehow. However-
$user = mysql_real_escape_string($_POST['User']);
$pass = mysql_real_escape_string(md5($_POST['Pass']));
$conn = mysql_connect("localhost", "root") or die(mysql_error());
(mysql_select_db('fireworks', $conn));
$ask = "SELECT * FROM name WHERE (User = '" . $user . "') and (Pass = '" . $pass . "');";
$result = mysql_query($ask);
The segment of code below is completely ignored! When I press log in (From the index page) It is suppose to run a series of checks. If the user decides to not put anything inside the user and password text boxes then it is suppose to return the string show below:
if (strlen($user) < 1){
if (strlen($pass) < 1){
print "<p class = 'Back'>Epic Fail</p>";
print "<p>You forgot to put in your Username or Password.</p>";
}
}
(^Up until here) But it doesn't. Instead its just a blank page. But everything else works fine. If I type in a fake user then it returns "YOU FAIL!" If I type a valid user it returns "WELCOME BACK."
if (strlen($user) >= 1){
if (mysql_num_rows($result) >= 1) {
while ($row = mysql_fetch_array($result))
{
print "<p class='Back'>Welcome back</p><p>" . $row['User'] . "</p>";
}
}else{
print "YOU FAIL!!!";
}
}
Any suggestions? EXTRA NOTES: The database is called fireworks the table is called name there are three columns in the name table. nameID, User, and Pass. (Idk how this is useful but sometimes it is.)

Your code:
if (strlen($user) < 1){
if (strlen($pass) < 1){
print "<p>You forgot to put in your Username or Password.</p>";
}
}
In actual fact, this won't check for $user or $pass being blank; it will only give the error message if both of them are blank.
Each test is okay on its own, but the way it's written, the test for $pass will only be run if the $user test has already given a true result.
What you need to to is write them together with an or condition, like so:
if (strlen($user) < 1 or strlen($pass) < 1){
....
}
Hope that helps.

try this:
if (strlen($user) < 1 || strlen($pass) < 1){ .... }

You're nesting the ifs, so the "Epic Fail" is only displayed when both the user name and password aren't entered.
You might want to change it to this:
if (strlen($user) < 1 || strlen($pass) < 1)
{
print "<p class = 'Back'>Notice</p>";
print "<p>You forgot to put in your Username or Password.</p>";
}

In the documentation of mysql_real_escape_string it says that it will attempt to connect to database for the character set. If you did not connect to database at all before the check it might very well be the case. You can check if error reporting to see if it returned E_WARNING level error.
Another thing is that you should avoid database calls when it is not needed. If thats the whole part of the important code, you should call both checks before you try to escape them and continue with database stuff. Also, empty() function might help you as well.
if(!empty($_POST['User']) || trim(strlen($_POST['User'])) < 1) {
// database stuff
}

Related

PHP if else condition on validation [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to create an activation page that will GET the API & ACT codes from the url.
Then I am trying to query the DB on those codes to check if they're valid.
If they are not valid, I would like to echo an error stating echo "<strong><font color=red>Your Activation Code has Expired, or Your Activation Code is not Valid!</font></strong>";
If it is valid, then I would like to update with the 2nd SQL Query - "UPDATE users SET status='1', date_activated='$Activation_Date', Activation='' WHERE Activation='$Activation' AND API='$API' AND status='0'"
If there is NO API&ACT code in the URL, I would like to echo "CONTENT"
<?
require 'admin/config.php';
require 'Connection.php';
error_reporting(E_ALL);
$API = $_REQUEST['api'];
$Activation = $_REQUEST['act'];
$sql= mysql_query("SELECT * WHERE Activation='$Activation'");
if ($sql = 0) { echo"ERROR";}
else {
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE Activation='$Activation' AND API='$API' AND status='0'");
if($sql == 0){
echo "<strong><font color=red>Your Activation Code has Expired, or Your Activation Code is not Valid!</font></strong>";
} elseif ($sql > 0) {
echo "content";
}
}
?>
What you need to check for, is if a row exists.
To check if it exists and base yourself on the following model:
$sql = mysql_query("SELECT * WHERE Activation='$Activation'");
if(mysql_num_rows($sql) > 0){
//do something here or show error because relation already exists
}
else{
//relation already do not exists. so you can insert the record here
}
Then, to check if your UPDATE was truly successful, use mysql_affected_rows():
Sidenote: This function may require that you pass a db connection variable to it.
$sql = mysql_query("UPDATE users .... ");
if(mysql_affected_rows() > 0){
// do something
}
else {
// do something else
}
Check for errors against your PHP and MySQL:
Add error reporting to the top of your file(s) right after your opening PHP tag
for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything.
Also add or die(mysql_error()) to mysql_query().
If you get errors about deprecation notices, then you will need to switch over to either mysqli_ or PDO.
You can consult one of my answers here https://stackoverflow.com/a/22253579/1415724 to check if a row exists.
It uses a few methods, including a prepared statement which is something you should be using because you are open to an SQL injection.
Sidenote: The connection API that you are using is unknown. Make sure that you are using the same one as your query being mysql_. If it's mysqli_ or PDO, those different APIs do not intermix. You must use the same one from connecting to querying.
Also, just a quick note about if ($sql = 0). The single equal sign "assigns" instead of "comparing" such as == or ===.
You stated in comments:
"IF the Activation code is active (the md5 has will be there)"
I hope you're not using that for password storage. If so, don't. That function is no longer safe to use to store passwords with.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Seeing <? make sure that short tags are enabled. If not, change that to <?php.
HTML stickler.
<font color=red> the <font> tag is deprecated/obsole and isn't supported by HTML5.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font
It's best to use inline CSS if you are sending anything via Email.
I.e.: <p style="color:red;">Hello world</p>
Here are a few references:
http://www.tizag.com/cssT/inline.php
Inline <style> tags vs. inline css properties
http://webdesign.about.com/od/beginningcss/qt/tipcssinlinesty.htm
Remarks
Checking mandatory parameters:You can test if parameters are set like this:
isset(variable_name).
In the SELECT query there is missing the FROM clause which states the table to select from.I assume it is "user" like in the UPDATE query.
After a SELECT query, the cursor should be freed again, when it is no longer in use: mysql_free_result($sql);
(Error) Tests
The result of a query is ===false if the query could not be executed corectly.
After having SELECTed records, the function mysql_num_rows() shows the number or records retrieved.
After having UPDATed a table, the function mysql_affected_rows() gives the number of affected records.
Code snippet
// Get parameters and check if mandatory parameters are set
$API = isset($_REQUEST['api']) ? $_REQUEST['api'] : false;
$Activation = isset($_REQUEST['act']) ? $_REQUEST['act'] : false;
if ( ($API===false) || ($Activation===false)) {
$which = ($API === false ) ? '"api"' : '';
$which .= ($Activation === false) ? ((empty($which) ? '' : ', ') . '"act"') : '';
echo "ERROR: Parameter(s) missing: $which";
return;
}
// Select activation record
$sql= mysql_query("SELECT * FROM users WHERE Activation='$Activation'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
return;
} else {
$nrows = mysql_num_rows();
mysql_free_result($sql);
if ($nrows < 1) {
// No matching record found
echo "ERROR: No activation record found";
return;
} else {
// Update users record
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE Activation='$Activation' AND API='$API' AND status='0'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
} elseif(mysql_affected_rows() < 1) {
// No matching record found for updating
echo '<span style="color:red; font-weight:bold;">Your Activation Code has Expired, or Your Activation Code is not Valid!</span>';
} else {
echo "content";
}
}
}
Here is what I ended up with.
This is a Tweak from #hherger's answer....
// Report all errors
error_reporting(E_ALL);
// Get parameters and check if mandatory parameters are set // Get parameters and check if mandatory parameters are set
$API = isset($_REQUEST['api']) ? $_REQUEST['api'] : false;
$Activation = isset($_REQUEST['act']) ? $_REQUEST['act'] : false;
if ( ($API===false) || ($Activation===false)) {
}
// Select activation record
$sql= mysql_query("SELECT * FROM users WHERE Activation='$Activation'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
return;
} else {
$nrows = mysql_num_rows($sql);
mysql_free_result($sql);
if ($nrows < 1) {
// No matching record found
echo "REDIRECT USER TO HOME PAGE";
return;
} else {
// Update users record
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE pinAPP_Activation='$Activation' AND API='$API' AND status='0'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
} elseif(mysql_affected_rows() < 1) {
// No matching record found for updating
echo '<span style="color:red; font-weight:bold;">Your Activation Code has Expired, or Your Activation Code is not Valid!</span>';
} else {
echo "ECHO SUCCESS DISPLAY!";
}
}
}

How can i check if a single mysql field is empty in php

After getting the user-info from my sql database I would like to check if some of the fields are empty and continue the script based on that. A simplified piece of code would look like this:
$userData = mysql_query("SELECT * FROM user WHERE user='".$user."' LIMIT 1");
if(mysql_num_rows($data) == 1){
$u_info = mysql_fetch_assoc($data);
if(empty($u_info['u_mobile'])){
echo 2;
exit();
} else {
echo 1;
exit();
}
} else {
echo 3;
exit();
}
The problem is the empty statement checking the recieved field. I've tried using empty(), isset(), not_null() and array_key_exists() with no luck and can't get around to what I'm doing wrong.
I also tried if($u_info['u_mobile']) == '' || $u_info['u_mobile']) == NULL) but that doesnæt work either.
Why is this, or how can I go about getting this information?
I need to collect the user-information and send them to fill out the information I don't have...
You're setting the query result to $userData but then you're using mysql_fetch_assoc($data); -- doh. You need to pass the variable that you set the query result to:
$u_info = mysql_fetch_assoc($userData);
It's OK, it is still 10AM EST so this can happen in the morning =)
I suggest that you turn on PHP error reporting. PHP would have alerted you that the array values were trying to access do not exist, saving you a lot of wasted frustration.
$userData = mysql_query("SELECT * FROM user WHERE user='".$user."' LIMIT 1");
if(mysql_num_rows($userData ) == 1){
$u_info = mysql_fetch_assoc($userData );
if(empty($u_info['u_mobile'])){
echo 2;
exit();
} else {
echo 1;
exit();
}
} else {
echo 3;
exit();
}
Please Run code..I think it will be compile better it was minor mistake

If statement is not working correctly

This is my first topic so far in this great webpage
The problem is this:
I'm scripting an UCP (PHP & MySQL based). I want it to show the user's status like score, money, etc. (Yeah, it's for a game) but when I click on the login button nothing happens it just erases the content of the requested fields.
It was working properly before I made some changes (Checking if the username exists)
Here's the code:
if (isset($_POST['login']))
{
$hashedpass = hash('whirlpool', $password);
$query = "SELECT * FROM users WHERE Username = '$playername' AND Password = '$hashedpass'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
else
{
$name=mysql_result($result,$i,"UserName");
$money=mysql_result($result,$i,"Money");
$score=mysql_result($result,$i,"Score");
$wantedlevel=mysql_result($result,$i,"WantedLevel");
$adminlevel=mysql_result($result,$i,"AdminLevel");
echo "<b>$name</b><br>Money: $money<br>Score: $score<br>Wanted Level: $wantedlevel<br>Admin Level: $adminlevel<br><br>";
}
}
else if (isset($_POST['register']))
{
header("Location: register.html");
}
else
{
header("Location: index.html");
}
if($num != 0)
change to:
if($num == 0)
This simply won't work here nor does it make much logical sense:
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
First the logic is wrong, if $num is NOT equal to 0 then your query MUST have found at least one account. So you need to change your if statement to:
if($num == 0){ //if 0 rows were found - the account was not found thus it doesn't exist
echo "Account doesn't exist!";
}
Notice also i did not add header("location: ucp.html");. You cannot display output + relocate the user to another page. You either do one or the other, or you will get an error/warning.
Finally check your MYSQL is not causing an error by adding a check at the end with :
$result = mysql_query($query) or die(mysql_error());
Final tip, you should avoid using mysql_* and look into mysqli_* or PDO best explained here:
Why shouldn't I use mysql_* functions in PHP?

Unable to check for password and username at login

I have tried to create a PHP log in form. My code is as follows. The if-else statement is not functioning well. Please solve this.
$connect = mysql_connect("localhost", "root", ""); //connect
mysql_select_db("elective_mgmt", $connect);
$username = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * from verify_student where
username='$username' && password='$password'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (name == $username && password == $password)
echo "you are logged in";
else
echo "please recheck your password and username";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "you are logged in";
}
else
echo "please recheck your password and username";
You can also do this by counting the number of rows. In your code $row is an array so whenver you need to acces the array elements do this $row['name']
You have a problem here.
if(name==$username && password==$password)
It should be
if($row['name']==$username && $row['password']==$password)
OR
if(mysql_num_rows($result) == 1)
You should look at - Why shouldn't I use mysql_* functions in PHP?
You could remove your if/else statement since you check the inputs already with your mysql query (name && password) and replace it with a mysql_num_rows == 1 (as the others have already mentioned before).
It seems that you are new to php and creating log in forms, so let me give you a good advice:
input values for a log in form shouldn't be passed via URL, use method post instead
never save passwords unencrypted (use sha512 since md5 is considered unsafe)
never use single information to store the log in status in the session

$_SESSION equals value from database?

when a person logs into my site i need to check a value in a database for their roleid, and dependent on that i need to allow/deny access to a page.
I have this code but it says that the $_SESION variable 'Access' is undefined, i cant see why?
$email = mysql_real_escape_string($_POST['email']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM person WHERE email = '" . $email . "' AND password2 = '" . $password . "'");
if (mysql_num_rows($checklogin) == 1) {
$row = mysql_fetch_array($checklogin);
$roleid = $row['roleid'];
$_SESSION['Email'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['Access'] = $roleid;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='2;index.php' />";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
This is the if statement that is saying the session in undefined:
if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Email']) && $_SESSION['Access'] == '2')
EDIT
Sorry, should have mentioned, session_start() is called in my base.php file which is included in this file.
EDIT
I don't know what the problem is, i can assign the variable $email to the other session variable and display that so the user can see who they are logged in as?
Does anybody have any suggestions? Both of the other session variables work fine.
From the code you have posted, you are missing session_start()
If this is not within a framework that performs this for you, it must be called on every page that will utilize the session before any session calls are made.
I assume the error is occurring after the redirect, in your logic that is checking for it using isset() or empty(). Add session_start() to both pages before any session logic is performed.
EDIT:
Ok, you have session_start(). Can you print_r() your $_SESSION and check the output?
Also, the file you mention that runs the session start should be included in both files, as its necessary for setting and checking values from the session.
Make sure before running any empty() conditionals, you also run isset(). Empty does not check if the key is present.
EDIT AGAIN:
Is it possible your value for $y isn't coming out of the database as a single value? can you die() at that point, just printing the value of $y out to see what is output?
Just add another check to your if statement, !empty($_SESSION['Access'])
if (!empty($_SESSION['LoggedIn'])
&& !empty($_SESSION['Email'])
&& !empty($_SESSION['Access'])
&& $_SESSION['Access'] == '2')
Check the spelling of $row['roleid']. Is the field name in the database table EXACTLY like it ?
Change
SELECT * FROM person WHERE
to
SELECT roleid FROM person WHERE
see if it breaks... :-)
This might not be related to your problem but I think it's worth mentioning: Your username / password SQL statement can be dangerous. Although you escape the input variables it is usually better practice to do it this way:
$checklogin = mysql_query("SELECT * FROM person WHERE email='".$email."'");
$row = mysql_fetch_array ($checklogin, MYSQL_ASSOC);
if (mysql_num_rows ($checklogin) == 1 && $row['password'] == $password)
{
// you are logged in
}
else
{
// wrong email or password
}
Reason being is that your current statement only needs to return ANY row in your table whereas this statement needs to return one specific row in the table.

Categories