i have a problem in my code. I have an ajax validation that calls a php file (where the data is validated).
The php returns echos like "invalidData" and in the javascript i check if (data=="invalidData") {//something}
The problem are the includes. Incredible thing.
<?php
include("includes/f_banco.php");
conecta ();
function get_post_var($var) {
$val = $_POST[$var];
if (get_magic_quotes_gpc())
$val = stripslashes($val);
return $val;
}
$name = get_post_var('name');
function validateName($name){
if(strlen($name) < 4 || (empty($name))) {
echo "invalidData";
return false;
}
else {
$name = mysql_real_escape_string($name);
$check = mysql_query("SELECT username FROM users WHERE username ='".$name."'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 == 0 && $name != "") {
echo "validData";
return true;
} else {
echo "invalidData";
return false;
}
}
}
error_reporting(E_ALL);
validateName($name);
?>
in the code above i only can check if the name is empty if i don't put the includes in the file. If i put the result is again and again different than invalidData.
The connection to the database is not made too or if is made the return is not the correct. Important: the include file is correct, i test in another example and the database is correct too.
thanks
Edit: **LAST VERSION**
<?php
error_reporting(-1);
require 'includes/f_banco1.php';
$name = $_POST["carlos"];
function validateName($name){
if(strlen($name) < 4 || (empty($name))) {
echo "nomeInvalido";
return false;
}
else {
$name = mysql_real_escape_string($name);
$check = mysql_query("SELECT username FROM users WHERE username ='".$name."'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 == 0 && $name != "") {
echo "nomeValido";
return true;
} else {
echo "nomeInvalido";
return false;
}
}
}
validateName($name);
echo "this must appear";
?>
output:
Notice: Undefined index: carlos in C:\Users\fel\VertrigoServ\www\login\validation.php on line 8
nomeInvalidothis must appear
Probably PHP debug 101... just do a
<?php
error_reporting(-1);
...
?>
And inspect the error...
Try updating your query to be the following:
SELECT `username` FROM users WHERE `username` ='".$name."'
And, another question... If you already know what the username is, then why are you running a query to find the username? I assume you're just checking to see if the username exists.
Related
This is my php file in which I am trying to check if the email already exists or not.
<?php
include_once("connection.php");
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$pass=$_REQUEST['pass'];
$mobno=$_REQUEST['mobno'];
$checkemail="SELECT * FROM dhruv_users WHERE email= '$_REQUEST[email]'";
$checkmob="SELECT * FROM dhruv_users WHERE mobno= '$_REQUEST[mobno]'";
$rsemail = mysqli_query($conn,$checkemail);
$rsmob = mysqli_query($conn,$checkno);
$dataemail = mysqli_num_rows($rsemail);
$datamob = mysqli_num_rows($rsmob);
if($dataemail >= 1) {
echo "exists";
}
else if($datamob >= 1)
{
echo "exists";
}
else{
$select=mysqli_query($conn,"select max(id) as id from dhruv_users");
if($data=mysqli_fetch_array($select))
{
$id=$data['id'];
$id++;
}
else
{
$id=1;
}
$query=mysqli_query($conn,"insert into dhruv_users VALUES ('$id','$name','$email','$mobno','$pass')");
if($query)
{
echo "success";
}
else{
echo "unsuces";
}
}
?>
There is no error but data gets entered successfuly without checking mob no if it exists or not.
Entering same mob no again and again shows success message instead of exist message.
Why dont you use mysqli_num_rows instead of mysqli_fetch_array with MYSQLI_NUM .
Try the following
$rs = mysqli_query($conn,$check);
$dataa = mysqli_num_rows($rs);
if($dataa > 1) {
echo "User Already in Exists<br/>";
}
You need to count the result which you getting from DB.
There is a logical error in code. Please have a look on code below:-
Your code
if($dataa[0] > 1) {
echo "User Already in Exists<br/>";
}
Replace above with:
if(count($dataa) > 1) {
echo "User Already in Exists<br/>";
}
You need to write your query with proper quotes. It's unable to recognize the email index of $_REQUEST. Also, use mysqli_num_rows function.
Refer to the code below for best possible practice:
$check = "SELECT * FROM dhruv_user WHERE email= '" . $_REQUEST['email'] . "'";
$rs = mysqli_query($conn,$check);
if ($rs) {
$rowcount = mysqli_num_rows($rs);
if ($rowcount) {
echo "User already exists<br/>";
}
}
The Script Always Returns Failure(Regardless Of Correct/Incorrect User Information. Nothing Is Wrong with any other files. The Config File works and is just a starter of the sql connection and selects the database.
#include('../settings/config.php');
if (!#include('../settings/config.php')) {
die("<center>Login Failed</center>");
}
//======================================================================
// POST Check(Isset submit comes from html form)
//======================================================================
if(isset($_POST['submit'])) {
// Sanitize All POST Fields
$_POST = array_map('trim', $_POST);
$_POST = array_map('strip_tags',$_POST);
$login_form_user = $_POST['login_user'];
$login_form_pass = $_POST['login_pass'];
// Testing Only
echo("
<center>
Your Username is: $login_form_user!
<br>
Your Password is: $login_form_pass!
</center>
");
//======================================================================
// Input/Database Check
//======================================================================
$user_fetch = <<<LOGIN
SELECT `id` FROM `users`
WHERE `username`='$login_form_user'
AND `password`='$login_form_pass'
LIMIT 1
LOGIN;
$user_result = $sql_connection->query($user_fetch);
if(!$user_result) {
die("<center>Cannot Execute SQL Login Query</center>");
}
if ($sql_connection->num_rows == 1) {
echo("<center>User $login_form_user Exists</center>");
}
if($row = $user_result->fetch_assoc()) {
if(($row['username'] === $login_form_user) && ($row['password'] === $login_form_pass)) {
// Login Is Successful
echo("<center>Login Successful</center>");
} else {
echo("<center>Login Failed</center>");
}
}
} else {
// No Direct File Access Allowed
unset($_POST);
die('No Direct File Access Allowed!');
}
?>
Change:
if(($row['username'] === $login_form_pass)...
To:
if(($row['username'] === $login_form_user)...
You have typo error in this line please change it
if(($row['username'] === $login_form_pass) && ($row['password'] === $login_form_pass))
$row['username'] === $login_form_user// you are comparing it with $login_form_pass
I am trying to create a login page and I am having some troubles. I cannot get this code not to return false even though I know I have the right password in my .txt document (It's just hashed though).
Here's my PHP file that I can not stop getting not to return False:
<?php
$file1 = 'userlist.txt';
$file2 = 'passlist.txt';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = trim($_POST["usermail"]);
$pass = trim($_POST["password"]);
}
$hashedPass = "";
$arr1 = file($file1);
$arr2 = file($file2);
$userKey = array_search($user, $arr1);
if ($userKey != false) {
reset($arr2);
for ($x = 0; $x <= $userKey; $x++) {
next($arr2);
if ($x == $userKey) {
$hashedPass = current($arr2);
}
}
echo $hashedPass;
}
if (password_verify($pass, $hashedPass)) {
header("Location: worked.html"); //change this to direct user to market
}
else {
/*header("Location: index.html"); //change this to direct user back to login page with error prompt*/
print $pass;
print $hashedPass;
echo '<br>Invalid pass.';
return false;
}
?>
Also, if you can think of anything I should have in my code, please let me know. Thanks so much.
Edit: Updated what I have for my code right now. Still returning False.
Since unHash is a function, it is not getting executed (it is not called from what I can see), so $hashedPass is not getting set. In the future, try adding some debug statements (e.g. just print out $pass and $hashedPass before the return false;).
A shot in the dark: You have turned off error messages and only get a blank page instead of a redirect when entring a right login combination?
If that is the case, you might use the following code:
<?php
$file1 = 'userlist.txt';
$file2 = 'passlist.txt';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = trim($_POST["usermail"]);
$pass = trim($_POST["password"]);
}
$hashedPass = "";
$arr1 = file($file1);
$arr2 = file($file2);
$userKey = array_search($user, $arr1);
if ($userKey != false) {
reset($arr2);
for ($x = 0; $x <= $userKey; $x++) {
next($arr2);
if ($x == $userKey) {
$hashedPass = current($arr2);
}
}
// echo $hashedPass;
}
if (password_verify($pass, $hashedPass)) {
header("Location: worked.html"); //change this to direct user to market
}
else {
/*header("Location: index.html"); //change this to direct user back to login page with error prompt*/
print $pass;
print $hashedPass;
echo '<br>Invalid pass.';
return false;
}
?>
The reason your code fails is the echo statement, which is executed before the header-redirect. It´s not allowed to have any output before an header-redirect. (more about this behaviour: How to fix "Headers already sent" error in PHP)
Hello i have a weird scope problem
require 'connect.php';
$name = $_GET['R'];
echo $name;
if(isset($_POST['prev_password']) && isset($_POST['new_password']) && isset($_POST['rep_password'])) {
echo $name;
if(!empty($_POST['prev_password']) && !empty($_POST['new_password']) && !empty($_POST['rep_password'])) {
$user_password = $_POST['prev_password'];
$user_new_password = $_POST['new_password'];
$user_rep_password = $_POST['rep_password'];
if($user_new_password == $user_rep_password) {
$mysql_query = sprintf("SELECT username, password FROM users WHERE username='$name'", $name);
$query_run = mysql_query($mysql_query, $mysql_link) or die('COULD NOT PERFORM QUERY');
while($row = mysql_fetch_array($query_run)) {
$qUser_name = $row['username'];
$qUser_pass = $row['password'];
}
if($qUser_name == $name) {
echo 'Match';
if($qUser_pass == $user_password) {
$mysql_query = sprintf("UPDATE users SET password='$user_new_password' WHERE username='$name'", $name);
$query_run = mysql_query($mysql_query, $mysql_link) or die('COULD NOT PERFORM QUERY');
echo header('Location: main.php?C=1');
}else {
header('Location: main.php?C=4');
}
}
}else {
header('Location: main.php?C=3');
}
}else {
header('Location: main.php?C=2');
}
}
anyway, the problem is with the first variable $name, when i 'echo' $name its ok, displays the content correctly, but inside the (if sss) ITS EMPTY, idk why, i've tried using global, the GLOBALS array, and its still empty, ... so .. the query its executed with an empty parameter.
please help, if someone can see what could be possible wrong.
PD: this is a Changepassword.php the $_GET['R'] is getting from the user Main.php site, AND I KNOW, im not Hashing password,, that is not really the problem here
Im getting this error in a basic register script:
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/func/user.func.php on line 23
The part of the register.php that's giving me the error is:
<?php
include('init.php'); // user.func.php is included in this file
include('template/header.php');
?>
<h3>Register</h3>
<?php
// Typical $_POST stuff here, down the line the next line is where the error happenes. Also, $register_email below is equal to $_POST['register_email'];
if(user_exists($register_email)) { ***THIS FUNCTION IS WHERE THE PROBLEM IS. THE ACTUAL FUNCTION IS DEFINED BELOW***
$errors[] = 'That email has already been registered';
}
The function from user.func.php that's giving me the error is:
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
return (mysql_result($query, 0) == 1) ? true : false; // ***THIS LINE RIGHT HERE***
}
Any ideas on what might be causing this error. It's an annoying error. Not the first time I've gotten that one.
UPDATE
Thanks for the answers, I've tried each one and I'm getting the exact same error. Here's the full register.php so far:
<?php
include('init.php');
include('template/header.php');
?>
<h3>Register</h3>
<?php
if(isset($_POST['register_email'], $_POST['register_name'], $_POST['register_password'])) {
$register_email = $_POST['register_email'];
$register_name = $_POST['register_name'];
$register_password = $_POST['register_password'];
$errors = array();
if(empty($register_email) || empty($register_name) || empty($register_password)) {
$errors[] = 'All fields required';
} else {
echo 'OK';
}
if(filter_var($register_email, FILTER_VALIDATE_EMAIL) == false) {
$errors[] = 'Email address is not valid';
}
if(strlen($register_email) > 255 || strlen($register_name) > 35 || strlen($register_password) > 35) {
$errors[] = 'Ayo, quit tampering with the html';
}
if(user_exists($register_email)) {
$errors[] = 'That email has already been registered';
}
}
if(!empty($errors)) {
foreach($errors as $error) {
echo $error.'<br />';
}
} else {
}
?>
Now, I must say first that I'm not a mysql specialist and I normally use a DB class (so should you.) But if you are saying that return (mysql_result($query, 0) == 1) ? true : false; line is giving you an error. It means that the line above is not working. Meaning that it is not returning a resource.
You should first debug your function..
function user_exists ($email) {
$email = mysql_real_escape_string($email);
if (!mysql_select_db("users")) {
echo 'Could not select "users" DB.<br />Error: ' . mysql_error();
}
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'");
echo 'The count is currently: '$query['count'];
// return (mysql_result($query, 0) == 1) ? true : false;
}
If it says that it couldn't select the users DB. Then the problem is in your connections. As I said, I'm no pro. But you should probably connect it like this:
$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
Now you can try this:
function user_exists ($email) {
global $conn;
$email = mysql_real_escape_string($email);
if (!mysql_ping($conn)) {
echo 'Could not ping the mysql. Connection is lost probably :(';
}
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
echo 'The count is currently: ' . mysql_result($query, 0);
// return (mysql_result($query, 0) == 1) ? true : false;
}
If the code is been debugged and connection is AWESOME! Then:
function user_exists ($email) {
global $conn;
if ($email) {
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
if (mysql_result($query, 0)) {
return true;
}
}
return false;
}
Or:
function user_exists ($email) {
global $conn;
if ($email) {
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
if ($result = mysql_fetch_array($query)) {
if ($result['count'] == 0) {
return true;
}
}
}
return false;
}
If you look in the manual, mysql_query() can return a ressource (thats what you expect) OR FALSE if an error occur.
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
Change to:
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT email FROM users WHERE email = '$email'");
if (false === $query) return false;
return (mysql_num_rows($query) == 1);
}
use
function user_exists($email) {
if(isset($email){
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
$result = mysql_result($query,0);
if($result ===false) {
//error occur with the sql statement
//handel the error
}
else
return ($result == 1) ? true : false; // ***THIS LINE RIGHT HERE***
}
}
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
//return (mysql_result($query, 0) == 1) ? true : false; // ***THIS LINE RIGHT HERE***
if( $query ) return ( mysql_result($query, 0) != "" ) ? true : false;
}