Issue with HTML and PHP - php

Im a beginner and I am facing this issue. I know this is simple, but am not able to debug this:
<!DOCTYPE html>
<html>
<body>
<form action="process.php" method="POST">
Username: <input type="text" name="user"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The PHP processing it is as follows. But I always get "NOT VALID" even though the credentials are right.
<?php
$name= $_POST['user'];
$password = $_POST['password'];
if($name=="admin"){
if($password=="admin123")
echo "VALID";
}
else
echo "NOT VALID";
?>

Use && Condition rather then two if condition. Try this one.
Use Logical Operators. Check more operators Demo Logical Operator
<?php
$name= $_POST['user'];
$password = $_POST['password'];
if($name=="admin" && $password=="admin123"){
echo "VALID";
header('Location: http://www.google.com/');exit;
}
else
{
echo "NOT VALID";
}
?>

You could use trim() function on your POST data.
$name = trim($_POST['user']);
$password = trim($_POST['password']);
if ($name == "admin" && $password == "admin123") {
echo "VALID";
} else {
echo "NOT VALID";
}

I have tried code like this
$name = "admin";
$password = "admin123";
if($name=="admin"){
if($password=="admin123")
echo "VALID";
}
else
echo "NOT VALID";
and it's show me VALID it'mean you enterd value is wrong,may be it consume space
Correct way to do is always check "variable isset" or not
<?php
$name= trim($_POST['user']);
$password = trim($_POST['password']);
if((isset($name) && $name == "admin") &&
(isset($password ) && $password=="admin123")){
echo "VALID";
}else{
echo "NOT VALID";
}
?>

You can try with strcmp(string1,string2) function.I thing here problem with

Related

Need advice / guidance on makin registration form

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color:red;}
</style>
</head>
<body>
<?php
$username = $password = $email = "";
$usernameerr = $passworderr = $emailerr = "";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
if (empty($_POST["username"])) {
$usernameerr = "Please fill username";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-Z]*$/",$username)) {
$usernameerr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailerr = "Please fill e-mail";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$emailerr = "not a valid e-mail";
}
}
if (empty($_POST["password"])) {
$passworderr = "Cannot be blank";
} else {
$password = test_input($_POST["password"]);
if(!preg_match("/^[a-zA-Z]*$/",$password)) {
$pasworderr = "Must be Letters";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con = mysqli_connect('localhost','root','','my_db');
if (mysqli_connect_errno()) {
echo "Fail to connect :".mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$sql = "INSERT INTO register(Username, Password, Email)
VALUES ('$username','$password','$email')";
if (!mysqli_query($con,$sql)) {
die ('Error: '.mysqli_error($con));
}
echo "Registration successful";
mysqli_close($con);
?>
<h2>Register</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username :<input type="text" name="username" value="<?php echo $username;?>">
<span class="error">*<?php echo $usernameerr;?></span>
<br><br>
Password :<input type="text" name="password" value="<?php echo $password;?>">
<span class="error">*<?php echo $passworderr;?></span>
<br><br>
E-mail :<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailerr;?></span>
<br><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Hi, I am a newbie, and I need advice on making registration form. So here is the code for my registration form, the validation code works and it submit data to mysql database too. But, the problem is, it will submit data to database every time it loads (even if it is blank). What line of codes should I add to prevent the form submitting data when it is not filled completely / filled with the right format.
Thx in advance.
You have to check if there's any data in the fields.
Just add this line before your sql executes, after $email = mysqli_real_escape_string($con, $_POST["email"]); :
if ($username != "" && $password != "" && $email != "")
{
//your sql and rest of the script goes here
}
else
{
//don't save the data if it's not completed well
//do whatever you want in that case no valid data was completed
}
Notes: I answered only to your question but be careful, you have some implementation mistakes. You should just use a flag that by default is 1 and, if an error is found in any of your validation functions, the falg should be set to 0 and you should check the value of the flag before the sql instead of checking the content of the $_POST variables again.
Edit: BETTER SOLUTION FOR YOUR CODE
Add this block before the sql:
if ($usernameerr == "" && $passworderr == "" && $emailerr == "")
{
//no errors, all fine we can add to the database
}
else
{
//we have errors, do something but don't add the data
}
Please outsource your DB-Connection and your DB-Insert in some seperate files and speak to them per ajax-request..
your db-insert-query should be taken place after you validation and at the end of the
if ($_SERVER["REQUEST_METHOD"]=="POST") {
block
You did not close the $_SERVER["REQUEST_METHOD"]=="POST" block properly.
Also inside the if ($_SERVER["REQUEST_METHOD"]=="POST") { block you can add another
if condition as if(!empty($_POST["username"] && !empty($_POST["email"] && !empty($_POST["password"]) {....}

Registration form not echoing

I am very new to PHP and I cannot get this if statement to echo when you click submit. My editor isn't showing any errors with the code and it seems to work fine, except for it not echoing the errors.
<html>
<LINK rel='stylesheet' href='style.css' type='text/css'>
<?php
$submit = $_POST['submit'];
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = md5(strip_tags($_POST['repeatpassword']));
$date = date('Y-m-d');
echo $date;
if ($sumbit)
{
if ($username&&$password&&$repeatpassword)
{
$password = md5($password);
$repeatpassword = md5($repeatpassword);
if ($password==$repeatpassword)
{
if(strlen($username)>25)
{
echo 'Length of username must be less than 25 charcters';
}
else
{
if (strlen($password)>25||strlen($password)<6)
{
echo 'Your password must be 6 to 25 characters long';
}
else
{
echo 'Success!';
}
}
}
else
{
echo 'Passwords do not match';
}
}
else
echo 'Fill in all the fields';
}
?>
<form action='register.php' method='POST'>
<table>
<tr>
<td>Username</td><br />
</tr>
<tr>
<td><input type='text' name='username'></td><br />
</tr>
<tr>
<td>Password</td><br />
</tr>
<tr>
<td><input type='password' name='password'></td><br />
</tr>
<tr>
<td>Repeat Password</td><br />
</tr>
<tr>
<td><input type='password' name='repeatpassword'></td><br />
</tr>
</table>
<p>
<input type='submit' name='submit' value='Register'>
</form>
</html>
There is a typo
its
if ($sumbit)
should be
if ($submit)
Add this at the beginning of your code:
ini_set("display_errors", true);
error_reporting(E_ALL);
You have to enable error reporting, its turned off by default afaik. Anyways:
if ($sumbit)
I suppose you want to check if its set. The function in php for that is called isset(), so your code would be:
if(isset($submit)) {}
Try this one, it may help you.
if (isset($_POST['submit']))
{
$submit = $_POST['submit'];
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = md5(strip_tags($_POST['repeatpassword']));
$date = date('Y-m-d');
echo $date;
if ((isset($username))&&(isset($password))&&(isset($repeatpassword)))
{
$password = md5($password);
$repeatpassword = md5($repeatpassword);
if ($password==$repeatpassword)
{
if(strlen($username)>25)
{
echo 'Length of username must be less than 25 charcters';
}
else
{
if (strlen($password)>25||strlen($password)<6)
{
echo 'Your password must be 6 to 25 characters long';
}
else
{
echo 'Success!';
}
}
}
else
{
echo 'Passwords do not match';
}
}
else
echo 'Fill in all the fields';
}
AND For Form use :
<form action='' method='POST'>
<input type='submit' name='submit' value='Register'>
</form>
try this
if(isset($_POST['submit']))
{
if (isset($_POST['username'], $_POST['password'], $_POST['repeatpassword']))
{
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = md5(strip_tags($_POST['repeatpassword']));
instead of
if ($sumbit)
{
if ($username&&$password&&$repeatpassword)
{
your are using sumbit and use submit
if ( !empty($submit) ){
{
there is a md5 of repeatpassword being done twice and md5 of password being done once. so the if condition fails
if ($password==$repeatpassword)
Before if submit condition
$password = strip_tags($_POST['password']);
$repeatpassword = md5(strip_tags($_POST['repeatpassword']));
Inside if submit condition
$password = md5($password);
$repeatpassword = md5($repeatpassword);

php: form still submits on invalidated form

i got a problem on my validation script using php; when the user only fills out username form and emptied the password it still logs the user in it should show the user that the password field is blank error. i'm kinda new to php and i'm hoping you can help me. thanks!
here's my code for checking login
<?php
$usernameErr = $passwordErr = "";
$username = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST['username']))
{$usernameErr = "Username is required.";}
else
{$username =($_POST['username']);}
if (empty($_POST['password']))
{$passwordErr = "Password is required.";}
else
{$password =($_POST['password']);}
}
?>
<body>
<div id="header" align="center">
<h1>PT. Sumber Urip Alfindo</h1>
</div>
<br/>
<div id="content" align="center">
<form id="login" name="login" method="post" action="checklogin.php">
<table>
<tr>
<td>Username</td>
<td></td>
<td><input name="username" type="text" id="username"><span class="error"><?php echo $usernameErr;?></span></td>
</tr>
<tr>
<td>Password</td>
<td></td>
<td><input name="password" type="password" id="password"><span class="error"><?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="submit" value="Login"></td>
</tr>
</table>
</form>
<?php
$sql="SELECT * FROM $tbl_name WHERE usrname='$username'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1 && $username="admin")
{
header("location:mainadmin.php");
}
else if($count==1)
{
header("location:main.php");
}
else
{
echo "Wrong username or password";
}
?>
Before anyone moans, I'm not replacing mysql with mysqli/PDO to answer the question. Yes it's wrong that it's used but it's not related to the question.
Correct model: if (there is not an error) { log the person in } else { do something else}.
Your model: check for errors. log the user in anyway.
This is what you're doing now
// checking stuff
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST['username']))
{$usernameErr = "Username is required.";}
// blah blah check check check
}
// don't bother considering the error, just log them in anyway
$sql="SELECT * FROM $tbl_name WHERE usrname='$username'";
// etc
But what you need to do is this:
// check for errors and store them
$errors=array(); // create an empty array to store errors
if (empty($_POST['username'])){
$errors['usernameErr'] = "Username is required."; // add an error
}else{
$username =($_POST['username']);
}
if (empty($_POST['password'])){
$errors['passwordErr'] = "Password is required."; // add an error
}else{
$password =($_POST['password']);
}
// etc etc
// check if there were any errors anywhere along the way
// and if not, proceed with login
if (!count($errors)) { // check there are no errors
$sql="SELECT * FROM $tbl_name WHERE usrname='$username'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
// etc etc
}else{
// if there were errors do something else
echo implode("<br />", $errors); // output the errors however you like
}
Try this for a start
<?php
/* validate form first */
if (!empty($_POST['username']))
{ $username = $_POST['username'];
}
else{ echo "Username is required."; }
if (!empty($_POST['password']))
{ $password = $_POST['password'];
}
else{ echo "password is required."; }
/* Do the queries second i.e */
SELECT * FROM Persons WHERE username='' AND password ='';
?>
hi,You should describe your question clearly,I have read your code and checked it ,when i not fills out password,it was really display Password is required.
general validation method is as follows:
if(empty($_POST['username'])){
$usererror = '...';
return false;
}else{
$username = $_POST['username'];
}
if(empty($_POST['password'])){
$passerror = '...';
return false;
}else{
$password = $_POST['password'];
}
The best way to handle error validation is to use same variable, especially if you have many input form data
$username = $_POST['username'];
$password = $_POST['password'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($username == '') {
$error_msg[]= 'Username is required';
} else if ($password == '') {
$error_msg[]= 'Password is required';
}
}
if (!empty($error_msg)) {
$ERROR_MSG = implode($error_msg);
exit;
}

php form validation and header location

I have a form submitting to intself. If the post variables are set, then I want them to be redirected to employee_profile.php. Currently the header location does not work even when the post variables are set. Any ideas?
<?php
$email_error = $password_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$email_error = "Missing Email";
} else {
$email = $_POST["email"];
}
if (empty($_POST["password"])) {
$password_error = "Missing Password";
} else {
$email = $_POST["email"];
$password = $_POST["password"];
header ('Location: employee_profile.php');
}
}
?>
The form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
Email: <input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $email_error;?></span><br />
Password: <input type="password" name="password">
<span class="error"><?php echo $password_error;?></span><br />
<input type="submit" value="Submit">
</form>
The PHP header (using HTTP/1.1) redirect requires an absolute URL.
Try the following:
<?php
// from PHP documentation, see http://php.net/manual/de/function.header.php
$host = $_SERVER['HTTP_HOST'];
// or:
// $host = $_SERVER['SERVER_NAME'];
$email_error = $password_error = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["email"])) {
$email_error = "Missing Email";
} else {
$email = $_POST["email"];
}
if(empty($_POST["password"])) {
$password_error = "Missing Password";
} else {
$password = $_POST["password"];
}
// some additional fixes: finally check if both is valid
if($email_error == $password_error) {
header("Location: http://$host/employee_profile.php");
}
}
?>
you can try some thing like this. currently in your script even when the email is not set but password is set, header function is called.
$email = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : "Missing Email";
$password = (isset($_POST['password']) && !empty($_POST['password'])) ? $_POST['password'] : "Missing Password";
if($email != "Missing Email" && $password != "Missing Password"){
header ('Location: employee_profile.php');
}
(warning: here any values passed as email and password will get the user to employee_profile)
also see if you are printing some thing or some htmls before calling header.
is it throwing any error, if so can you also print the error here?

php die() doesn't work (simply code)

I am learning how to use "setcookie", however, I couldn't get following line to work,
I have pasted all my codes here, if someone could give me a hand please?
Have no idea the reason.
Many thanks.
else{ die ("hahahahahahahahahahahahahaha"); }
HTML code
<form method="POST" action="">
<div class="error"><?php echo $error;?></div>
<p></p>
<label>Username: </label><br>
<input type="text" name="username"><br>
<label>Password: </label><br>
<input type="password" name="password"><br>
<input type="checkbox" name="rememberme"> Remember me<br>
<input type="submit" name="submit" value="Login">
PHP CODE
<?
if(isset($_POST['submit'])){
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = isset($_POST['rememberme']);
echo $rememberme;
if($username&&$password){
$login = mysql_query("SELECT * FROM form WHERE username='$username'");
while ($row = mysql_fetch_assoc($login))
{
$db_password = $row['password'];
if (md5($password)== $db_password)
{
$logstatus = TRUE;
}
else{
$logstatus = FALSE;
}
if ($logstatus == TRUE)
{
if ($rememberme == "1")
setcookie("username", $username, time()+600);
else if ($rememberme == "")
$_SESSION['username'] = $username;
echo " I am here";
}
else{
die ("hahahahahahahahahahahahahaha"); //unable to get here
}
}
}
else{
echo "enter username / password";
}
}
?>
Try this code, I haven't tested it but is should works :)
session_start();//dont forget this :P
if(isset($_POST['submit'])){
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = isset($_POST['rememberme']);
echo $rememberme;
if($username&&$password){
$login = mysql_query("SELECT * FROM form WHERE username='$username' AND password='".md5($password)."'");
if (mysql_num_rows($login))//if this returns 1 you are logged in
{
if ($rememberme == "1")
setcookie("username", $username, time()+600);
else
$_SESSION['username'] = $username;
echo " I am here";
}else{
die ("Incorrect Username/Password"); //unable to get here
}
}
}
else{
echo "enter username / password";
}
}
The while loop is causing the issue, simply remove it.
Well I didn't tested the code but trying following might help.
Add line:
$logstatus = TRUE;
before while.
Justification:
Scope of variable finishes as soon as block finishes. defining logstatus outside while will make sure its scope do not end where it is required.

Categories