Compatibility issues in website functionality - php

I have a basic login system, It all works perfectly when I test it on a Mac, but when any of my windows users try and login, they either get redirected to another part of the login system thats not even linked in any way to where they came from, or they just get a white screen.
My PHP is.
auth.php
<?php session_start(); /* Starts the session */
/* Check Login form submitted */
if(isset($_POST['Submit'])){
/* Define username and associated password array */
$logins = array('ozzie' => 'savox555','devjacob' => '59NassauRoad','builer' => 'xntbuilderd');
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected */
$_SESSION['UserData']['Username']=$logins[$Username];
header("location:/upload/index.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>Invalid Login Details</span>";
}
}
?>
My form is:
Login
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<body class="align">
<div class="site__container">
<div class="grid__container">
<form action="http://xeonnetwork.net/upload/dev/auth.php" method="post" class="form form--login">
<h2>Awww snap! Please login!</h2>
<div class="form__field">
<label class="fontawesome-user" for="login__username"><span class="hidden">Username</span></label>
<input name="Username" type="text" class="form__input" placeholder="Username" required>
</div>
<div class="form__field">
<label class="fontawesome-lock" for="login__password"><span class="hidden">Password</span></label>
<input name="Password" type="password" class="form__input" placeholder="Password" required>
</div>
<div class="form__field">
<input name="Submit" type="submit" value="Sign In">
</div>
</form>
</div>
</div>
</body>

Related

The script doesn't checking if the credentials are right and doesn't redirect to profile page

The scenario:
User logging using username & password.
The background getting the credentials and the script will check the the username & password equal to the username & password that are stored in the variables "$username,$pass".
If the username & password doesn't match it won't redirect you to profile.php, if it's matching you will be redirected to profile.php.
The Problems:
When I enter the username & password it's just going to check.php which is the script that will check if the credentials are right or not , so it doesn't redirect me to profile.php
Instead of redirecting to http://localhost/loginpage/profile.php
it's going to http://localhost/loginpage/checking.php, with a plank page
enter image description here
I'm not sure if the checking function it's right or not , or if it's really checking
Index.php
<!DOCTYPE html>
<html>
<head>
<title>Professor Albus Dumbledore Secret Door</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form class="login-form" action="checking.php" method="POST">
<p class="login-text">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-lock fa-stack-1x"></i>
</span>
</p>
<input type="text" class="login-username" autofocus="true" required="true" placeholder="Username" name="username" />
<input type="password" class="login-password" required="true" placeholder="Password" name="password" />
<input type="submit" name="login" value="Login" class="login-submit" />
</form>
forgot password?
<div class="underlay-photo"></div>
<div class="underlay-black"></div>
</body>
</html>
checking.php script:
<?php
$username = "admin";
$pass = "12345";
#$error = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
# code...
if ($_POST["username"] == $username && $_POST["password"] == $pass) {
# code...
header("Location: /profile.php");
echo "Logged in";
}
}
?>
Additional Information :
I'm using apache2 server on Ubuntu

data in $_POST across multiple pages

I am new to PHP and I wrote scripts for simple login. When successfully login and click the link "back to login", I was not able to have the previous login username filled. I know using $_COOKIE['username'] for the value of username works, but I am wondering why $_POST['username'] does not work? Thank you!
login.php
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="./loginProcess.php" method="post">
Username: <input type="text" name="username" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="send">
</form>
</body>
</html>
loginProcess.php
<?php
echo "welcome, ".$_POST['username'].", login success!!";
echo "<br/><a href='login.php'>Back to login</a><br>";
if(!empty($_COOKIE['lastVist'])){
echo "your last login time:".$_COOKIE['lastVist'];
setcookie("lastVist",date("Y-m-d H:i:s"),time()+24*3600*30);
}else{
echo "you first login time:";
}
setcookie("username", $_POST['username'], time()+24*3600*30);
?>
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer and unlike post as it has information for specific request sent by user.
When we use an application, we open it and do some changes, then we close it. This is much like a Session, so to preserve information we have per session global array in php $_SESSION.
A session is started with the session_start() function and values are stored in simply associative array fashion $_SESSION['key'] = $value;.
login.php
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="./loginProcess.php" method="post">
Username: <input type="text" name="username" value="<?php echo isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="send">
</form>
</body>
</html>
loginProcess.php
<?php
session_start();
echo "welcome, ".$_POST['username'].", login success!!";
echo "<br/><a href='login.php'>Back to login</a><br>";
if(isset($_SESSION['lastVisit'])){
echo "your last login time:".$_SESSION['lastVisit'];
}else{
echo "you first login time:".$_SESSION['lastVisit'];
$_SESSION['lastVisit'] = date("Y-m-d H:i:s", time());
}
$_SESSION['username'] = $_POST['username'];
?>
In principle, in loginProcess.php, if you would have used, for example, a form with a hidden input containing the username value, then this value would have been readable in the login.php - after clicking the "back to login" anchor:
Welcome <?php echo $_POST['username']; ?>, login success!!
<br>
<form id="backToLoginForm" action="login.php" method="post">
<input type="hidden" name="username" value="<?php echo $_POST['username']; ?>" />
<a href="#" onclick="javascript:document.forms['backToLoginForm'].submit();">
Back to login
</a>
</form>
But you really shouldn't do what you want to do. E.g. to go back to the login.php without logging-out first - at least. If you would do it and complete other credentials - in the login.php - as the ones used for the first login, then you would still need to logout the previous user before validating the new credentials. This would be a bad management of active session, cookies, etc.
More of it, the autocomplete of login credentials is a job for the password managers, or of the form fillers, not of your own code - unless it's part of the validation process of the currently given login credentials (see the code example below).
So, as an alternative to your approach, my suggestion would be the following login.php code. No need for a loginProcess.php page anymore:
<?php
session_start();
// Operations upon form submission.
if (isset($_POST['submit'])) {
// Validate the username.
if (!isset($_POST['username']) || empty($_POST['username'])) {
$errors[] = 'Please provide the username.';
}/* Here other password validations using elseif statement. */
// Validate the password.
if (!isset($_POST['password']) || empty($_POST['password'])) {
$errors[] = 'Please provide the password.';
} /* Here other password validations using elseif statement. */
// Get the posted data.
$username = $_POST['username'];
$password = $_POST['password'];
if (!isset($errors)) {
/*
* Check the given credentials in the db. If the user doesn't exist, add an error:
*/
// $errors[] = 'Wrong credentials. Please try again.';
/*
* ... else add only the user id - fetched from db - to session.
* Don't add other user related details to session. If, in other pages,
* you want to use other user details, fetch them there using the user id.
*/
if (!isset($errors)) {
$_SESSION['userId'] = 43;
// Redirect to the welcome page.
header('Location: welcome.php');
exit();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Login</title>
<style type="text/css">
.form-control {
margin-bottom: 10px;
}
label {
display: inline-block;
min-width: 80px;
}
.messages {
margin-bottom: 20px;
}
.error {
color: #c00;
}
button {
padding: 5px 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
</style>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
}
?>
</div>
<form action="" method="post">
<div class="form-control">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="<?php echo isset($username) ? $username : ''; ?>">
</div>
<div class="form-control">
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="<?php echo isset($password) ? $password : ''; ?>">
</div>
<button type="submit" id="submit" name="submit">
Login
</button>
</form>
</body>
</html>

Login Form header() shows blank page

I created a login form that should direct the user to the page after sending the form but it just shows me a blank page
with a link of **http://localhost/Cisu/AccHolder/holderlogin.php
Login Form
<?php
session_start();
?>
<!DOCTYPE html>
<html >
<head>
<title>Login</title>
<link type="text/css" rel="stylesheet" href="css/login.css">
</head>
<body>
<form method="" action="holderlogin.php">
<div class="container">
<div class="profile">
<button class="profile__avatar" id="toggleProfile">
<img src="images/sbma.png" alt="Avatar" />
</button>
<div class="profile__form">
<div class="profile__fields">
<div class="field">
<input type="text" id="user" name="user" class="input" required pattern=.*\S.* />
<label for="username" class="label">Username</label>
</div>
<div class="field">
<input type="password" id="pass" name="pass" class="input" required pattern=.*\S.* />
<label for="password" class="label">Password</label>
</div>
<div class="profile__footer">
<input id="Submit" name="Submit "type = "Submit" class="btn"/>
</div>
</div>
</div>
</div>
</div>
<script src="javascript/login.js"></script>
</form>
</body>
</html>
holderlogin.php
<?php
ob_start();
session_start();
include('dbconn.php');// Database connection and settings
// checking the user
if(isset($_POST['Submit'])){
$user = mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "select * from tbl_accholder where accholder_Username='$user' AND accholder_Password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user==1){
while ($row = mysqli_fetch_array($run_user)) {
$run_ID = $row['accholder_ID'];
$run_user = $row['accholder_Username'];
}
$_SESSION['accholder_Username']= $user;
$_SESSION['accholder_ID']= $run_ID;
header( 'Location: MainMenu.php');
} else
echo "please wait while redirecting...";
echo "<script> alert('Log-In Failed!'); </script>";
echo "<script> document.location.href = 'Login.php' </script>";
ob_end_flush();
}
?>
You are checking whether $_POST['Submit'] is set.
However, in your form, the name attribute is Submit with an extra space:
<input id="Submit" name="Submit "type = "Submit" class="btn"/>
This might be the cause of the problem, since you said it shows me a blank page.
also - you have no method listed for your form, but are checking the $_POST array to check for "Submit". It should be:
<form method="POST" action="holderlogin.php">
Don't know if its causing your problem, but you have a leading space before the php declaration - this can be cause problems to the php rendering if you are setting header requests later in the code - there can be no characters rendered before the header request.
<?php
also you list the action of the form as "holderlogin.php"
but list the name of the file as "Holderlogin.php" - this might just be a typo when entering the code here but worth checking.

How to change class after the user has stopped typing?

So I have this form set-up which looks exactly like this : http://i.imgur.com/z8zI2aJ.png The thing I am trying to do is change the form field's class after the user has stopped typing, as shown below after checking in my database if the username/email already exists. This should be done without reloading the page. How can I do this? Preferably with jQuery's (ajax?)
register.php
<?php
require_once 'connect.inc.php';
require_once 'core.inc.php';
?>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="styles.css" type="text/css">
<link rel="stylesheet" href="animate.min.css">
</head>
<body>
<div class="container">
<div class="middlebox">
<h1 class="logo">codeforum+</h1>
<h3 class="welcometext">Create an account on codeforum+</h3>
<h6>Please fill out all the provided fields to continue with your registration.</h6>
<h6 style="font-size:10px;">Note : You can only register once on this forum, so make it count. Any further registrations will be prohibited, because your IP address will be in our database.</h6>
<hr class="linestyle">
<form action="" method="post">
<div class="form-group">
<div id="username_form" class="input-group <?php // IF USERNAME EXISTS ADD CLASS 'has-warning' ELSE ADD 'has-success' ?>">
<span class="input-group-addon"><i class="fa fa-user fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Enter your username here..." name="username">
</div>
</div>
<div class="form-group">
<div class="input-group <?php // IF EMAIL EXISTS ADD CLASS 'has-warning' ELSE ADD 'has-success' ?> ">
<span class="input-group-addon"><i class="fa fa-envelope fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Enter your email here..." name="email">
</div>
</div>
<div class="form-group">
<div class="input-group <?php // IF PASSWORD HAS NUMBERS,LETTERS, ETC.. ADD CLASS 'has-warning' ELSE ADD 'has-success' ?> ">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Enter your password here..." name="password">
</div>
</div>
<div class="form-group">
<div class="input-group <?php // IF THIS MATCHES THE PASSWORD ADD CLASS 'has-warning' ELSE ADD 'has-success' ?> ">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input class="form-control" type="text" placeholder="Retype your password here..." name="password_retype">
</div>
</div>
<hr class="linestyle">
<p>Which comparison operator is used to compare variables/values in PHP?</p>
<div class="form-group">
<input class="form-control" type="text" placeholder="Answer the question here..." name="question">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="checkbox">I agree to the rules of this forum.
</label>
</div>
<p class="rules" style="font-size:10px;">Breaking the rules by any means will result in a permanent ban.</p>
<input class="btn btn-success fullwidth" type="submit" value="Register">
</form>
<?php
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['password_retype']) && isset($_POST['question']) && isset($_POST['checkbox'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$password_retype = $_POST['password_retype'];
$question = $_POST['question'];
$checkbox = $_POST['checkbox'];
if(!empty($username) && !empty($email) && !empty($password) && !empty($password_retype) && !empty($question) && !empty($checkbox)) {
$sql = "SELECT id FROM users WHERE username='$username'";
if($sql_run = mysql_query($sql)) {
$sql_num_rows = mysql_num_rows($sql_run);
if($sql_num_rows==1) {
// if username exists change class of the form
} else {
// if username doesnt exist - continue
$sql = "SELECT id FROM users WHERE email='$email'";
if($sql_run = mysql_query($sql)) {
$sql_num_rows = mysql_num_rows($sql_run);
if($sql_num_rows==1) {
// if email exists change class of the form
} else {
// if email doesnt exist - continue
}
} else {
// if query failed
}
}
} else {
// if query failed
}
} else {
// if fields are empty
}
}
?>
<p class="small" style="margin-top:10px;">Already have an account?</p>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
connect.php
<?php
$mysql_error = mysql_error(); // change to 404 when finished
$mysql_database = 'codeforum';
$mysql_host = '127.0.0.1';
$mysql_user = 'root';
$mysql_pass = '';
if(!mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !mysql_select_db($mysql_database)) {
die($mysql_error);
}
?>
Your question might have been easier to answer if you took more time to reduce it to a manageable scenario, but here you go anyway:
you'll need a PHP endpoint that checks for username availability.
to prevent that endpoint abuse, you'll need to require a PHP session, and store the number of attempts in the last 20 minutes or so in that. If there are too many attempts for your liking it should error out.
you'll need a JS handler for making an AJAX request to above endpoint; it will apply your className if the endpoint didn't respond with a error.
hook up your JS to fire on "change" and use a helper function to setTimeout to do the same on "keyup", so you don't hammer your PHP endpoint every time the user releases a key but rather only after a grace period, of say 100ms.
go back and implement informative messages for your error conditions, such as "name exists", and "too many attempts".

Displaying differnt border color if field is valid

So I have my form which I have supplied pictures of below. The left side picture is a normal border color but then the red outline on the right is when the form input is invalid.
How would I do this through PHP? Here's the corresponding code
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
exit($e->getMessage());
}
// Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
// Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)) {
echo "Complete all fields";
}
// Password match
if ($password != $password1) {
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
And my HTML form
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
So if the input satisfies the if statement how would I display the color?
When your form has errors, you need to re-display it. It's hard to give a recommendation without knowing your code structure, but I will assume that your HTML is rendered via a call to php. Generally, I have done something like
$error = false
//this $_GET['submit'] variable could be part of the URL of your submitted form.
//alternately, you could check the HTTP method of the page request
if ($_GET['submit']) {
//run your form logic
//if you have success, run your php query and then redirect
//to your "success" page using a 302 (using a header("Location:... sort of call)
//you would also want to call die() or something right here
}
//if you make it this far, display your page including the bits about errors
//your form's action goes right back to the same page that rendered it, but with
//some change to the url to let the script know that you want to process the form
With PHP5 and with warnings about undefined variables turned on, you would need to define all of your error message variables before checking whether or not the form is being submitted.
Asuming you are using twitter bootstrap since you have form-control all over the place, (assuming >= 3.0.0), you can use (for the graphical side of things) has-suceess, has-error, etc like shown here: http://getbootstrap.com/css/#forms-control-validation.
When you re-display the form due to bad data, pass along your error messages to whatever renders your html. An example with your thing would be (assuming your form has access to $passmatch, $emailvalid,$passlength):
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
</div>
<div class="form-group <?php if (!empty($emailvalid)) { echo 'has-error'; } ?>">
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
</div>
<div class="form-group <?php if (!empty($passmatch) || !empty($passlength)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group <?php if (!empty($passmatch)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
I would recommend using a templating engine or something to separate the view from the actual code.
As for the help text, you can use something like this after the elements with errors:
<div class="form-group <?php if (!empty($yourVariable)) { echo 'has-error'; }?>">
<input type="text" class="form-control" />
<span class="help-block"><?php echo $yourVariable; ?></span>
</div>
The fun part is, if you have no error message, the help block won't even be shown because that variable won't have anything in it.
EDIT
Example page: http://content.kevincuzner.com/register.php
Example source: https://gist.github.com/kcuzner/11323907
I would handle this on the client side with JavaScript. On submission of the form, you can check whether the input is valid or not and then just update the border color using JavaScript.
The <?php ?> you can fill in above (if you want to go this route) can just depend on some variable that checks validity:
echo "Complete all fields";
$fieldsValid = false;
border-color: <?php $fieldsValid ? 'blue' : 'red' ?>
But you need to do a full page reload for this to work. JavaScript is a better route:
document.forms[0].addEventListener("submit", function () {
var usernameInput = document.querySelector("[name=username]");
if (!usernameInput.value) {
usernameInput.style.borderColor = "red";
}
});

Categories