I have the following code, where the var $username doesn't echo, when you type in a value.
//TODO: SET AUTH TOKEN as random hash, save in session
$auth_token = rand();
if (isset($_POST['action']) && $_POST['action'] == 'Login')
{
$errors = array(); //USED TO BUILD UP ARRAY OF ERRORS WHICH ARE THEN ECHOED
$username = $_POST['username'];
if ($username = '')
{
$errors['username'] = 'Username is required';
}
echo $username; // var_dump($username) returns string 0
}
require_once 'login_form.html.php';
?>
login_form is this:
<form method="POST" action="">
<input type="hidden" name="auth_token" value="<?php echo $auth_token ?>">
Username: <input type="text" name="username">
Password: <input type="password" name="password1">
<input type="submit" name="action" value="Login">
</form>
The auth token part isn't important, it just when I type in a value in username textbox and press the login button, the username wont echo, var_dump returns string (0) and print_r is just blank.
silly mistake
if ($username = '') <-- this is an assignment
Should be this
if ($username == '') <-- this is comparison
if ($username = '')
You're missing a =, so you're assigning an empty string to $username. Change it to
if ($username == '')
^-- note the 2 equal signs.
This line is an assignment, not a comparison:
if ($username = '')
You want:
if ($username == '')
//TODO: SET AUTH TOKEN as random hash
$auth_token = rand();
if (isset($_POST['action']) && $_POST['action'] == 'Login')
{
$errors = array(); //USED TO BUILD UP ARRAY OF ERRORS WHICH ARE THEN ECHOED
$username = $_POST['username'];
if ($username == '') // **You are assiging not comparing**
{
$errors['username'] = 'Username is required';
}
echo $username; // var_dump($username) returns string 0
}
require_once 'login_form.html.php';
?>
In your login form: (the action attribute..)
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="auth_token" value="<?php echo $auth_token ?>">
Username: <input type="text" name="username">
Password: <input type="password" name="password1">
<input type="submit" name="action" value="Login">
</form>
Related
I am making the login page in php.
However, no If worth of blank check of html form is operated (line4)
After entering in the html of the form, even if you press the login does not have moved if statement.
Since the cause is not know, I want you to tell me
if (isset($_POST["login"])) {//PUSH login button
//form blank check
if ($_POST["email"] = '') {
$error['email'] = "blank";
} else if ($_POST["pass"] = '') {
$error['pass'] = "blank";
}
}
if(!empty($_POST['email'])){
//email & password verification
if($_POST['email'] != '' && $_POST['pass'] != ''){
$email = $_POST['email'];
$pass = SHA1($_POST['pass']);
$query = "select * from human";
$result = mysqli_query($dbc,$query);
$data = mysqli_fetch_array($result);
if($data['email'] == $email) { //form email & password
if($data['pass'] === $pass) {
setcookie('email', $email, time()+(60*60*24*3));
setcookie('pass', $pass, time()+(60*60*24*3));
setcookie('name', $date['name'], time()+(60*60*24*3));
exit();
}else{
$error['match'] = "anmatch"; //Mismatch Error
}
}
}
<!DOCTYPE html>
<form action="" method="post">
<dl>
<dt>email</dt>
<dd>
<input type="text" name="email" size="35" maxlength="255"
value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php if($error['email'] == 'blank'): ?>
<p><font color="red">* Input email</font></p>
<?php endif; ?>
</dd>
<dt>password</dt>
<dd>
<input type="password" name="pass" size="35" maxlength="255"
value="<?php echo htmlspecialchars($_POST['pass']); ?>">
<?php if($error['pass'] == 'blank'): ?>
<p><font color="red">* Input password</font></p>
<?php endif; ?>
</dd>
</dl>
<input type="submit" id="login" name="login" value="sigh in">
</form>
Firstly as mentioned in the comments, you are assigning a value in your if statements. Also as a second point I'd guess because your condition is a nested else if the first assignment is always true so the second condition will never be tested.
//form blank check
if ($_POST["email"] = '') {
$error['email'] = "blank";
} else if ($_POST["pass"] = '') {
$error['pass'] = "blank";
}
The second condition statement will only evaluate when the first is false
You should try checking each variable independently nand make sure you use ==
//form blank check
if ($_POST["email"] == '') {
$error['email'] = "blank";
}
if ($_POST["pass"] == '') {
$error['pass'] = "blank";
}
My website has a login form present in every pages (on a top-menu) so even when a user is on the Register page the login form is still available in this top-menu.
My problem is that in this specific case, when a user fills the register form and submits it, it returns the error that all fields are required to be filled. I found out that this is because my login form uses the same input names that my register form uses ( $username and $password ).
So even if the register form is filled, if i leave the login form empty it will return me this error, however if i fill the login form with anything and then submit the properly filled register, there won't be any conflicts.
Here are my login form, register form, and part of my php code that process the register data
login form :
<form method="post" action="/ftp/index.php?login=1">
<div id="header_username">
<input type="text" name="username" id="txt_username" placeholder="username" required="" value="" />
<span class="username_icon"><i class="fa fa-user"></i></span>
</div>
<div id="header_password">
<input type="password" name="password" id="txt_password" placeholder="password" required="" />
<span class="password_icon"><i class="fa fa-lock"></i></span>
</div>
<div id="forgotten_pwd">
<span> Forgotten Password ?</span>
</div>
<div id="submit_button">
<input type="hidden" name="redirect" value="<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>" />
<button type="submit" name="submit" id="sub_login"><i id="submit"class="fa fa-long-arrow-right"></i></button>
</div>
<div id="button-border"></div>
<div class="feedback">login successful <br />redirecting...</div>
</form>
register form :
<form action="<?php echo $_SERVER['PHP_SELF'].'?signup=1'; ?>" method="post">
<div class="line"><label for="username"><?php echo lang::get("Username")?> *: </label><input type="text" name="username" id="username" value="<?php if (isset($_POST['username'])) echo $_POST['username']?>"/></div>
<div class="line"><label for="email"><?php echo lang::get("Email")?> *: </label><input type="text" name="email" id="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']?>"/></div>
<div class="line"><label for="password"><?php echo lang::get("Password")?> *: </label><input type="password" name="password" id="password"/></div>
<div class="line"><label for="password2"><?php echo lang::get("Confirm password:")?> </label><input type="password" name="password2" id="password2"/></div>
<?php
$rand_int1 = substr(mt_rand(),0,2);
$rand_int2 = substr(mt_rand(),0,1);
$rand_int3 = substr(mt_rand(),0,1);
$captcha_answer = $rand_int1 + $rand_int2 - $rand_int3;
$_SESSION['captcha_answer'] = $captcha_answer;
?>
<div class="line"><label for="captcha"><?php echo $rand_int1.' + '.$rand_int2.' - '.$rand_int3.' = ?';?> *: </label><input type="text" name="captcha" id="captcha" autocomplete="off"/></div>
<div class="line submit" style="text-align:right"><input type="submit" class="button" value="<?php echo lang::get("Sign up")?>" /></div>
</form>
<?php endif;?>
</div>
php code that processes the data :
if (!empty($_POST)){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$captcha = $_POST['captcha'];
// requiered fields & validation
if ( !isset($username)
|| $username == ''
|| !ctype_alnum($username)
|| gator::getUser($username)
|| gator::getUser($email, 'email')
|| !isset($password)
|| !isset($password2)
|| !isset($_POST['captcha'])
|| $password == ''
|| $password != $password2
|| filter_var($email, FILTER_VALIDATE_EMAIL) == false
|| (int)$captcha != (int)$_SESSION['captcha_answer'])
{
if ($username && !ctype_alnum($username)) $_POST['username'] = '';
if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) $_POST['email'] = '';
$errors = lang::get("All fields requiered!");
}
if ($errors == false){
$reloadaction = 'thanks';
My question is the following :
Even though i know an alternative solution would be to rename the inputs of my register form for instance, is there a "cleaner" solution for this ? Is there instead anything i can add to my php code that process the data to make it ignore the login form's inputs when i submit the register form ? How do big websites deal with this type of conflicts ?
Thanks a lot for trying to help me out with this !
-Apatik
edit : my full register code :
* Sign up init
*/
public function initSignup() {
// try to activate account?
if (gatorconf::get('signup_use_activation') && isset($_GET['activate'])){
$key = $_GET['activate'];
$user = gator::getUser($key, 'akey');
if ($user){
gator::updateUser($user['username'], array('akey' => '', 'permissions' => gatorconf::get('default_permissions_after_activation')));
$user['permissions'] = gatorconf::get('default_permissions_after_activation');
$this->loginUser($user);
}
header('Location: '.gatorconf::get('base_url'));
die;
}
$errors = null;
if (!empty($_POST)){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$captcha = $_POST['captcha'];
// requiered fields & validation
if ( !isset($username)
|| $username == ''
|| !ctype_alnum($username)
|| gator::getUser($username)
|| gator::getUser($email, 'email')
|| !isset($password)
|| !isset($password2)
|| !isset($_POST['captcha'])
|| $password == ''
|| $password != $password2
|| filter_var($email, FILTER_VALIDATE_EMAIL) == false
|| (int)$captcha != (int)$_SESSION['captcha_answer'])
{
if ($username && !ctype_alnum($username)) $_POST['username'] = '';
if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) $_POST['email'] = '';
$errors = lang::get("All fields requiered!");
}
if ($errors == false){
$reloadaction = 'thanks';
$activationkey = '';
if (gatorconf::get('signup_use_activation')){
$activationkey = sha1(mt_rand(10000,99999).time());
$url = gatorconf::get('base_url').'/?signup=1&activate='.$activationkey;
$subject = gatorconf::get('account_email_subject');
$body = gatorconf::get('account_email_text'). "\n\n" .$url;
$this->sendEmail($email, $subject, $body);
$reloadaction = 'goactivate';
}
// homedir will be created based on username
$homedir = gatorconf::get('repository').'/users'.DS.$username;
// if dir does not exist - try to create one
if ($homedir != '' && !is_dir($homedir)){
if (!mkdir($homedir, 0755, true)) {
echo "ERROR: User's homedir cannot be created. Check permissions. DIR = ".$homedir; die;
}
}
// add new user
gator::addUser($username, array(
'password' => $password,
'permissions' => gatorconf::get('default_permissions_after_signup'),
'homedir' => $homedir,
'email' => $email,
'akey' => $activationkey));
// thanks on success or go activate!
header('Location: '.gatorconf::get('base_url').'/?signup=1&'.$reloadaction);
die;
}
}
if (isset($_GET['thanks'])){
// thanks on success or go activate!
header('Location: '.gatorconf::get('base_url'));
die;
}elseif (isset($_GET['goactivate'])){
gator::display("header.php");
gator::display("signup.php", array('goactivate' => 1));
}else{
gator::display("header.php");
gator::display("signup.php", array('errors' => $errors));
}
gator::display("../../../style/include/footer.php");
}
/**
*
Yes, give name to your submit button and just check this:
if (isset($_POST('submit_login'))) {
// login related check
}
if (isset($_POST('submit_registration'))) {
// registration related check
}
Add a hidden field to the registration form such as <input type='hidden' name='action' value='register' /> and then check for that in your $_POST check code.
if ($_POST['action'] == 'register'){
// Process registration code
} else {
// Process login code
}
if ($_POST){
if ($_POST['action'] == 'action1'){
// do action 1 code
}
else if ($_POST['action'] == 'action2'){
// do action 2 code
}
else {
// do nothing
}
Thanks a lot for every answers, which were helpful.
I found that what was wrong was the submit button of my register not having a name (as you can see in my post). I added name="register" to it and then changed in my code if (!empty($_POST)){ for if (!empty($_POST['register'])){
Seems all good now.
Just do a little modification on your code for the signup page.
First give each submit button a name and than above the login php code
write
if(isset($_POST['submit_login'])&&!isset($_POST['submit_signup']))
where submit_login and submit_signup are the names of buttons
I think it should work..
best of luck
I looked trough your pages and fixed my undefined index on username and password but now I get undefined variable. I had more code but decided to simplify it for the sake of testing and just echo it to see if anything changes and it doesn't.
<?php
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
}
echo $uname;
echo $password;
?>
I get this:
Notice: Undefined variable: uname in C:\xampp\htdocs\8\login.php on line 7
Notice: Undefined variable: pass in C:\xampp\htdocs\8\login.php on
line 8
I do not really understand what's wrong here. If needed here is my form page html.
<form id="login" method="post" action="login.php">
<div id="loginon">
<label for="username" style="color:#0F0; font-family:Arial, Helvetica, sans-serif;" >Username: </label>
<input type="text" id="username" name="username" />
<br />
<br />
<label for="password" style="color:#0F0; size:auto; font-family:Arial, Helvetica, sans-serif;">Password: </label>
<input type="password" id="password" name="password" />
<br />
<br />
<input type="image" src="http://www.clker.com/cliparts/2/G/4/v/K/E/submit-hi.png" border="0" width="180px" height="80px" alt="Submit" />
</div>
</form>
</body>
EDIT:
The further problem is connected to this so I think I am allowed to post it here.
if($username == "pikachu" || "cloud") {
$ucheck = "dobar";
} else {
$ucheck = "los";
}
if ($password == "123123" || "132132") {
$pcheck = "topar";
} else {
$pcheck = "losh";
}
if($ucheck == "dobar" && $pcheck == "topar") {
echo "Najjaci si!";
}
elseif ($ucheck == "dobar" && $pcheck == "losh") {
echo "Wimp.";
} elseif ($ucheck == "los" && $pcheck == "topar") {
echo "Fish.";
}
The problem is that it always echoes out "Najjaci si" no matter what I type in the previous form. Any ideas?
Since you have the variable decleration inside a logic (If), there is a chance that the variables are not set at all.
Try this
<?php
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
echo $uname;
echo $pass;
} else {
echo "No submit detected!";
}
?>
It also doesen't look like if you have an actual element named submit.
Try adding this:
<input type="submit" name="submit" value="Send my form" />
Now, your form contains an element named "submit" which will be send as a post parameter when the form is submitted.
I myself, in need of a framework, like doing like this:
$username = ( isset($_POST["username"]) && $_POST["username"] != "" ? $_POST["username"] : false );
$password = ( isset($_POST["password"]) && $_POST["password"] != "" ? $_POST["password"] : false );
if( !$username === false && !$password === false )
{
echo $username . " <br /> " . $password;
} else {
echo "No! :) ";
}
isset will check that variable is set or not and pass value in 0 or 1. So over here you need to do as
$uname = isset($_POST['username']) ? $_POST['username'] : '';
$pass = isset($_POST['password']) ? $_POST['password'] : '';
Notice: Undefined variable: pass in C:\xampp\htdocs\8\login.php on line 8
Its because you were echoing $password instead of $pass
Edited
Do it as
$uname = '';
$pass = '';
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
}
echo $uname;
echo $pass;
Try this
In form
<form id="login" method="post" action="login.php">
<div id="loginon">
<label for="username" style="color:#0F0; font-family:Arial, Helvetica, sans-serif;" >Username: </label>
<input type="text" id="username" name="username" />
<br />
<br />
<label for="password" style="color:#0F0; size:auto; font-family:Arial, Helvetica, sans-serif;">Password: </label>
<input type="password" id="password" name="password" />
<br />
<br />
<input type="submit" name="submit"/>
</div>
</form>
</body>
In login.php
<?php
if (isset($_POST['submit']))
{
$uname = $_POST['username'];
$pass = $_POST['password'];
}
echo $uname;
echo $pass;
?>
I have a url which has some get variables in it like:
domain.com/recover?email=my#email.com&token=abc123
inside the recover controller i load a form with POST method
so when i submit the form i load again the recover controller but my GET variables disappear and return to
domain.com/recover
so how can i make sure the GET variables retain in the URL after submitting the form?
HTML:
<?php echo form_open('recover'); ?>
<label for="password1" class="fl" style="width:160px;">Your new Password</label>
<input type="text" value="" id="password1" name="password1" style="width:308px;margin-top:0;margin-left:10px;" />
<label for="password2" class="fl" style="width:160px;">Retype your new Password</label>
<input type="text" value="" id="password2" name="password2" style="width:308px;margin-top:0;margin-left:10px;" />
<input type="submit" value="Recover password" class="button_ui" name="submit" />
<?php echo form_close(); ?>
Controller:
$data = array(
'errors' => '',
'show_password_form' => false
);
$get_email = $this->input->get("email") ? trim($this->input->get("email")) : "";
$get_token = $this->input->get("token") ? trim($this->input->get("token")) : "";
if ($get_email != "" && $get_token != ""){
$this->load->model("recover_model");
$data["show_password_form"] = true;
//check new passwords and update
$submit = $this->input->post("submit_change") ? trim($this->input->post("submit_change")) : "";
if ($submit){
$password1 = $this->input->post("password1") ? trim($this->input->post("password1")) : "";
$password2 = $this->input->post("password2") ? trim($this->input->post("password2")) : "";
//if password1 is valid
if ($this->recover_model->valid_password($password1)){
//if password2 is valid
if ($this->recover_model->valid_password($password2)){
//if both are equal
if ($password1 == $password2){
//update password
}else{
$data["errors"] = 'Your passwords do not match.';
}
}else{
$data["errors"] = 'Your password must be at least 6 characters.';
}
}else{
$data["errors"] = 'Your password must be at least 6 characters.';
}
}
}
$this->load->view("account/recover/recover", $data);
Change this line: <?php echo form_open("recover"); ?>
To
<?php echo form_open('recover', $_GET); ?>
it will create all get values as hidden input. When you submit form, they will send with method that you defined for form.
Or you can just write manually:
<?php echo '<form method="post" accept-charset="utf-8" action="'.base_url().'recover?email='.$_GET['email].'&abc='.$_GET['token'].'" />'; ?>
Manually render the form tag in php or the html and add some javascript
<script type="text/javascript">
document.write("<form method=\"POST\" action=\"");
document.write(window.location.href);
document.write("\">");
</script>
Much better js is available for writing this...
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>" />
Username:<input type = "text" name ="user"> <br />
Password:<input type = "password" name = "pass"><br />
<input type = "submit" value ="View Logs!"><br />
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
//Problem here, I need to only allow the user to see logs
// after he or she has entered the correct info.
//Currently code just shows all, when the user hits View Logs
// without any credentials
if (($user == "php") && ($pass == "student"))
echo "Enjoy the Logs!";
else echo "<b>Access Denied!</b>";
?>
The problem is that your form is posting directly to log.txt and not processing any of your PHP after the form submission. You'll need to change the action to post to the PHP file itself and then use http_redirect to redirect the user to log.txt after checking the password.
Having said that it's still not going to be very secure though as anyone could get to log.txt by using a direct URL, so you'll need to do some kind of authorisation there. The best thing to do is probably to store log.txt somewhere that's not accessible by through HTTP and then load and display the file using readfile in place of your echo:
<form action="" method="post">
Username:<input type="text" name="user"/> <br />
Password:<input type="password" name="pass"/><br />
<input type="submit" value="View Logs!"/><br />
</form>
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if (($user == "php") && ($pass == "student")) {
echo '<pre>';
readfile('log.txt');
echo '</pre>';
}
else {
echo "<b>Access Denied!</b>";
}
?>
<?
if (
isset( $_POST['user'] )
&& isset( $_POST['pass'] )
) {
$user = $_POST['user'];
$pass = $_POST['pass'];
if (
($user == 'php')
&& ($pass == 'student')
) {
echo "Enjoy the Logs!";
readfile('log.txt');
}
else {
echo '<b>Access Denied!</b>';
}
} else {
?>
<form method="post">
Username:<input type="text" name="user"> <br />
Password:<input type="password" name="pass"><br />
<input type="submit" value="View Logs!"><br />
<?
}