Possible stupid error! IF statement not running? - php

A little context, the registration part works fine, however I want to now add a login system. I want to test to see if the username exists but this isn't working.
Can anyone spot the error here?
Feel free to check it on a server over here - it's a WIP so there's still lots to do. The username "Lewis" is currently entered into the database for testing purposes.
As you can see, after the form has been filled etc. none of the echo statements run, in fact, even if an echo is put directly below the first 'IF' statement, it still doesn't print, so what is the problem? I've also tried changing the IF to:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
Still no luck.
PHP:
//error_reporting(E_ALL);
//ini_set('display_errors', TRUE);
require 'vdb_includes/db.php';
require 'functions.php';
if(!empty($_POST['username']) && !empty($_POST['pw'])){
$verifyUsername = $_POST['username'];
$verifyPassword = $_POST['pw'];
$usernameCheck = mysqli_query($con, "SELECT * FROM users WHERE username='".$verifyUsername."'");
if($usernameCheck->num_rows){
echo "Username exists";
} else {
echo "Non existant";
}
}
HTML:
<form id="login_form" action="http://valhq.com/login" method="POST">
<div class="login_form_content">
<div class="login_form_input">
<input type="text" class="login_input_style" placeholder="Username" id="username" name="username" maxlength="20">
</div>
<div class="login_form_input">
<input type="password" class="login_input_style" placeholder="Password" id="pw" name="pw" maxlength="56">
</div>
<input type="submit" id="submit" name="submit" class="login_submit" value="Login">
<div class="login_notMember">
Don't have an account? Sign up.
</div>
</div>
</form>

You have a 301 redirect to add a slash at the end of your url when it's missing. You haven't got a slash at the end of your form action and because of that the form post gets redirected to the url with the slash. Solution: add a slash at the end of the form action and it will work.

Related

mysql_query("INSERT INTO... is not working

I'm trying to create a registration page. The page is successfully connected to phpMyAdmin database but it does not echo anything when i click the register button.
<html>
<head>
</head>
<body>
<?php
INCLUDE "connect.php";
INCLUDE "functions.php";
INCLUDE "titlebar.php";
?>
<div id="loginform">
<h1>Register</h1>
<form name="Register" action="register.php" method="post">
<?php
if(isset($POST["submit"])){
$username = $_POST["username"];
$password = md5 ($_POST["password"]);
if(empty($username) or empty($password)){
echo "<p>Fields Empty!</p>";
} else {
mysql_query("INSERT INTO login VALUES('',$username','$password','2','')");
echo "<p>Successfully Registered!</p>";
}
}
?>
<p>
<label for="username">Username: </label>
<input type="text" name="username" id="username"/></p><p>
<label for="password">Password: </label>
<input type="password" name="password" id="password"/></p><p>
<input type="submit" name="submit" value="Register" />
</p>
</form>
</div>
</body>
The problem is with the post method.
use $_POST instead of $POST
You have mysql error
Not: $username'
but '$username'
And next time display mysql errors with mysql_error().
At the beginning, I am not sure what isset($_POST['submit'] should return, but as already mentioned in the comments you missed a single quote.
Additionaly i would use:
$password = password_hash($_POST['password'],
md5 is deprecated and thus not safe. If you write a login script you can use password_verify(plainPW, hashPW)
You also need to specify a database and login into it. I recommend to look at the W3 Schools examples they are very in-depth and have good examples.
W3 school mysqli page
also write a die() at the end of your script and do not foregt to close the connection.

Is a stale session stopping post variables being submitted

I have had this issue intermittently for some time, but I only just had it happen repeatedly enough to actually trouble shoot it. It happened repeatedly in FF but I have seen it in Chrome as well.
I have login form as below, it is very simple, email address and password and a submit button
<form method="post" action="login.php" id="valid" class="mainForm">
<fieldset>
<div class="">
<label for="req1">Email:</label>
<div class="loginInput"><input style="width: 100%;" type="text" name="email" class="validate" id="req1" /></div>
<div class="fix"></div>
</div>
<div class="">
<label for="req2">Password:</label>
<div class="loginInput"><input style="width: 100%;" type="password" name="password" class="validate" id="req2" /></div>
<div class="fix"></div>
</div>
<input name="action" type="hidden" value="log_in" />
<div class="">
<div class=""><input type="checkbox" id="check2" name="remember_me" value="1"/><label>Remember me</label></div>
<input type="submit" value="Log me in" class="submitForm" />
<div class="fix"></div>
</div>
</fieldset>
</form>
Submitting the above form wouldn't log me in, it just displayed the login form again as if nothing was submitted. So I amended the login.php file that is submitted to, and at the very top added print_r($_POST);
When I submitted the form again all it displayed was an empty array. It was like the form variables just weren't being sent. I tried several accounts, and got a blank array each time.
I then tried to enter an email address that I new wasn't in the database, and to my amazement the $_POST array populated with the fake email and password. I then tried a real account again and it was blank.
The last thing I did was to deleted the session cookie in FF for the site, and then try again. To my surprise I could then log in OK. I logged in and out a few times after that with no problem at all!
So my question is: What was that session cookie doing to prevent the post variables from being sent (if that was what was actually happening) and why did it populate the $_POST array if I entered a fake email address? The print_r($_POST) I did was the very first thing in the script, before any other processing or includes, yet it still was empty??
I guess I don't really know how browsers deal with session cookies, but this behaviour has me completely clueless.
Any advice on how to troubleshoot this, or general session advice.
EDIT - PHP Code for the login.php
<?php
print_r($_POST);
include '../inc/init.php';
$action = fRequest::get('action');
if ('log_out' == $action) {
fSession::destroy();
fAuthorization::destroyUserInfo();
fMessaging::create('success', '<center>You were successfully logged out</center>');
}
if (fAuthorization::checkAuthLevel('user') || fAuthorization::checkAuthLevel('buser')) {
fURL::redirect('index.php');
}
if ('log_in' == $action) {
# Set session variables etc...
}
The init.php include at the top sets the database connetion strings and starts the session etc... I am using FlourishLib Un-Framework set of classes which includes a session class.
Thanks
try this code please
$actions = array('log_in', 'log_out');
$action = fRequest::getValid('action', $actions);
if ($action == 'log_out') {
fSession::clear();
fAuthorization::destroyUserInfo();
fMessaging::create('success', URL_ROOT . 'index.php', 'You were successfully logged out');
fURL::redirect(URL_ROOT . 'index.php');
}
if ($action == 'log_in') {
if (fRequest::isPost()) {
try {
$valid_login = fRequest::get('username') == 'yourlogin';
$valid_pass = md5(fRequest::get('password')) == 'md5(youpassword)';
if (!$valid_login || !$valid_pass) {
throw new fValidationException('The login or password entered is invalid');
}
fAuthorization::setUserToken(fRequest::get('username'));
fURL::redirect(fAuthorization::getRequestedURL(TRUE, URL_ROOT . 'index.php'));
} catch (fExpectedException $e) {
fMessaging::create('error', fURL::get(), $e->getMessage());
}
}
include VIEWS_DIR . DS . basename(__FILE__);
}

How to validate form using another php file?

I am new to web designing. Now, I have created a form, and if the user input doesn't meet the requirements I display error message, and if it does I do some mysql commands to enter the info to the database. Now one way to do this is to code the php file into the html and use this command,<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> like described [here][1]
But I don't want to put the script in the same file. How do I do that in another php file such that if user input is invalid, it will return to the homepage with the error message updated?
Here is my code
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="register.css">
</head>
<h1>Register as A new user</h1>
<div id="signup">
<form id="registration_form" action="registration.php" method="post">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
<span class="errorMessage"></span>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
</div>
What should be in the registration.php? Like the link, I do everything, I set a flag to the error, Now if the flag is true I return the user to the homepage with the error messages, and if false, I show a message saying registration successful. How do I do the part,"return to homepage with the appended error message"?
All your validation and bulletproofing should be in the registration.php
stuff like this:
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['name'])) {
die('Must pass \'name\');
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['email'])) {
die('Must pass \'email\');
}
if(!isset($_GET['passwd'])) {
die('Must pass \'password\');
} else {
//do cool stuff here
}
Don't forget your JS validation as well for the front end. I really hope this helps and gives you a bit of direction.
put your validation codes in "validate.php" or any file name you like
then change the action to validate.php to
then in validate.php if validation matches the requirements.
header("Location: registration.php");
if not match
header("Location: back to the httml with form.php");
You can learn form validation here : http://allitstuff.com/registration-form-in-php-with-validation/

login form works if fields are empty?

i have setup an internal site for logging in a few users, users wont change and pw wil be done by authorised people only.
so i needed something VERY simple and without using a database where possible.
so i made the following script, works well except one of my testers tried to login with both fields empty... and it worked??
cant figure it out.
login
<form id="slick-login" action="_login_action.php" method="post">
<label for="username">Username</label>
<input type="text" name="username" class="placeholder" placeholder="username"/>
<label for="password">Password</label>
<input type="password" name="password" class="placeholder" placeholder="password"/>
<input type="submit" value="Login" />
_login_action.php
<?php
$usernames = array("admin", "user", "guest", "input");
$passwords = array("admin123", "user123", "guest123", "input123");
$page = "index.php";
for($i=0;$i<count($usernames);$i++){
$logindata[$usernames[$i]]=$passwords[$i];
}
if($logindata[$_POST["username"]]==$_POST["password"]){
session_start();
$_SESSION["username"]=$_POST["username"];
header('Location: '.$page);
exit;
}else{
header('Location: login.php?wrong=1');
exit;
}
?>
this is the file that i include on the pages i need protecting;
<?php
session_start();
if(!isset($_SESSION["username"])&& !empty($_SESSION['username'])){
header('Location: login.php');
exit;
}
?>
can anyone help me out please?
One more check needed:
if(!empty($_POST["username"]) && $logindata[$_POST["username"]]==$_POST["password"])

PHP login script 404 error

I used a login script tutorial here: http://www.astahost.com/info/tilltf-simple-login-script-simple-secure-login-script.html and when I clocked login, there was a 404. When i went back, I was logged in. I followed the the tutorial exactly as it said. Any idea why it is going to this weird page?
<?php
session_start();
require_once 'database.php';
if (isset($_SESSION['user'])){
echo "Welcome ".$_SESSION['user'];
?>
<form name="logout" method="post" action="logout.php">
<input type="submit" name="logout" id="logout" value="Logout">
</form>
<br /><form name="news" method="post" action="news.php">
<input type="submit" name="news" id="news" value="News">
</form>
<?php
}
elseif(isset($_SESSION['admin'])){
echo"Welcome ".$_SESSION['admin'];
echo"<br><br>You are logged in as an Admin";
?>
<form name="logout" method="post" action="logout.php">
<input type="submit" name="logout" id="logout" value="Logout">
</form>
</form>
<?php
}else{
?>
<form name="login_form" method="post" action="login2.php">
<label>
<input name="user" type="text" id="user">ID<br />
<input name="pass" type="password" id="pass">Password<br />
</label>
<input type="submit" name="login" id="login" action="index.php" value="Login">
</label>
</p>
</form>
<form name="Register" method="post" action="reg.php">
<input type="submit" name="register" id="register" value="Register">
</form><br />
<form name="news" method="post" action="news.php">
<input type="submit" name="news" id="news" value="News">
</form>
<?php
}
?>
Glancing at the code you linked to, I noticed login2.php tries to redirect to Index.php in some cases, but to index.php (lowercase i) in other cases. It should be lowercase in both places. That might be the cause of your 404.
That tutorial has a couple header redirects:
header("location:Index.php");
and
header("location:index.php");
Make sure they're not supposed to be pointing to the same file, and make sure that file exists. It's logging you in, and then trying to redirect you to a file it can't find.
Depending on your type of server, this might cause problems:
if(mysql_num_rows($queryN) == 1) {
$resultN = mysql_fetch_assoc($queryN);
$_SESSION['user'] = $_POST['user'];
header("location:Index.php");
}
Specifically because the I in Index.php is capitalized, while all other references to the file utilize a lowercase i.
Also, this code is TERRIBLY formatted... but alas that's a different problem altogether.
Looking over the code at the link you provided, I see a likely cause. At the end of the login processing script, there's a call to header() which redirects back to the index page. One of them has different casing, and many web servers are case-sensitive by default:
header("location:index.php");
header("location:Index.php");
I'm guessing the lower case index.php is the correct one, so update your code accordingly.
just an added warning: the linked example has a serious security hole along these lines
$escaped_username = mysql_real_escape_string($username);
# make a md5 password.
$md5_password = md5($_POST['pass']);
$queryN = mysql_query("select * from user where username = '".$username."' and password = '".$md5_password."' AND level='1'");
$escaped_username is generated correctly, but the sql query still uses $username. this opens up the possibility to inject sql statements. be sure to change it.

Categories