$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
$_Get methods do not work because of how the login system is built and unsecured.I need mailuid value to bring them to their own profiles page after login.
Login Form since its's post method I should be able to grab the value on other pages and this one
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
Temporary check for the mailuid value. Supposed to grab the value form the login form a spit it back out, to check to see if it is recognized
<?php
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
?>
First I would clean this up:
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
Instead it can be written more concise:
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
if( $user ){
echo "{$user} is your username";
} else {
echo "no username supplied";
}
I prefer Boolean false over NULL, null just means it doesn't exist. Boolean false lets you know you checked it and it didn't exist. Generally should should access $_POST as few times as you can. This is because you should never trust $_POST.
$_Get methods do not work because of how the login system is built and unsecured.
Post is no more secure than get, it's quite easy to post anything to the page even without visiting the site by using something like PostMan etc. Once you assign it to a local variable you know you have at least normalized the data, even if you haven't sanitized it yet.
Also don't forget to call session_start before trying to access $_SESSION. Because of the vagueness of the question, it could be that the form works fine, just the session data isn't being maintained because you haven't started the session yet.. etc....
Hope it helps.
Personally I would clean up the HTML part that makes the form as well, so instead of this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
I would do something like this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php if (!isset($_SESSION['Id'])){ ?>
<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>
<?php }else{ ?>
<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
<?php } ?>
</section>
</div>
</div>
See how much cleaner that is. Most of this is just readability issues. For example there is no need to check if isset($_SESSION['Id']) in the else if condition, because it's either set or not. This is one less place to maintain the session variable key, and it makes the code less convoluted.
As for the actual problem, as long as you are reaching the above code after submission of the form, it should work. So that leads me to believe that you have something wrong in the action.
You should get a clean page after going to includes/login.inc.php meaning there shouldn't be much in the way of HTML. One thing you can do that is real simple is just add at the top:
die(__LINE__.' of '.__FILE__);
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
//... other code
What this will do is die which kills PHP execution, but outputs the argument you passed in. In this case I'm just putting the line and file that the die is on, that way it's easier to find later. But the point is to see if you are even hitting the correct ending script or the forms action/endpoint.
I only suggest this because you are really vague in what it's current behaviour is
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
For example, this doesn't tell me if you are even hitting the right page. Now had you said something like "all it does is output no username supplied". Then I would at lest know that. As I said above it could be just an omission of sesion_start() which must be called before attempting to access any $_SESSION stuff. You should call it only once, at the top of each page that uses sessions.
Although it's not a solution, it was too much to post in a comment. I would really like to help you more, but there just isn't enough information to go on.
Related
I am hoping the community can give me a little insight into what is not working with my code, I am following a Udemy course. I have followed the accompanying video which developed an undefined variable error, which after doing some research I believe I have fixed by declaring variables as empty strings being able to be over-ridden by the form data.
The form sends data to the database if both are completed, and if one of the fields is empty then it doesn't, which is as it should be.
If one of the fields is empty it should return a statement asking the user to enter data into the respective field, but nothing is being sent.
The only difference between the tutorial and my code is I have used the materialize framework, where the tutorial used bootstrap, but I can't see that being the issue.
I have attached my code, and commented out redundant parts.
<?php
include('php/connection.php');
//validates data for create user form
if( isset( $_POST["createUserBtn"])){
$createUsername = "";
$createUserPassword = "";
function validateFormData( $formData ) {
$formData = trim( stripcslashes( htmlspecialchars( $formData)));
return $formData;
}
if( !$_POST["createUsername"]){
$createUsernameError = "Enter a username <br>";
} else {
$createUsername = validateFormData( $_POST["createUsername"]);
}
if( !$_POST["createUserPassword"]){
$createUserPasswordError = "Enter a Password <br>";
} else {
$createUserPassword = validateFormData( $_POST["createUserPassword"]);
}
if( $createUsername && $createUserPassword) {
$query = "INSERT INTO users (user_id, userName, userPassword) VALUES (NULL, '$createUsername', '$createUserPassword')";
// if( mysqli_query( $connection, $query)){
// echo "New User added";
// } else {
// echo "Error: ".$query."<br>".mysqli_error($connection);
// }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php require('static/header.php'); ?>
<?php
$createUsernameError = "";
$createUserPasswordError = "";
?>
<div class="col s8 m8 l5 valign-wrapper">
<div class="container">
<form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
<div class="row">
<div class="col s12">
<span><h4>Create your user account - create user.php</h4></span>
<div class="row form-font">
<div class="col s12">
<div class="input-field">
<a class="red-text"><?php echo $createUsernameError; ?></a>
<input placeholder="Enter your username" type="text" name="createUsername">
<label for="email">Username</label>
</div>
<div class="input-field">
<a class="red-text"><?php echo $createUserPasswordError; ?></a>
<input placeholder="Enter your password" type="password" name="createUserPassword">
<label for="password">Password</label>
</div>
<div class="row left-align">
<div class="col s2"></div>
<div class="col s8">
<button class="btn-flat waves-effect waves-custom" type="submit" name="createUserBtn"><i class="material-icons left">create</i>Create Account</button>
</div>
<div class="col s2"></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<?php require('static/footer.php'); ?>
</html>
Look carefully at your code and the places where you make use of - for example - the $createUsernameError variable.
If there's an error, you set a message in it with this line: $createUsernameError = "Enter a username <br>";. Great, just what you wanted.
However, later on in the code, you run $createUsernameError = "";, which resets it to empty again. And that happens in all circumstances, whether an error was identified or not. And it happens before you try to echo that variable onto the page.
So basically you're setting the value and then immediately blanking it again before you output it. You need to make sure it's only set blank in situations where there's no error. It's the same problem for the password error message.
An easy way to do that would simply be to set the value blank before you run the error checks. Then it'll stay blank if there's no error, but it won't overwrite any error messages which do get set.
So just move these lines:
$createUsernameError = "";
$createUserPasswordError = "";
to the top of your script.
P.S. Please pay attention to the security warnings posted in the comments and urgently fix your code to remove these vulnerabilities before using this code in any kind of live environment. Even if you don't plan to use this code for real, you should still fix these issues so that you learn to do things the correct, safe, reliable way and don't get into bad habits. If you copied this code from a course online, I suggest finding a better course.
I have a register email page, which uses referral id, but if no user doesn't get referred by anyone, then by a redirect, I use default af id = 1
with following code::
if ( !isset( $_GET['af'] ) && empty( $_GET['af'] ) ){
header('Location: register-email.php?af=1');exit();
}
Next Here is the form code:
<form class="form-horizontal" role="form" method="post" name="register_email" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-6">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<div class="g-recaptcha" data-sitekey="somecode"></div>
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-warning" name="register-email">Register Email</button>
</div></div>
</form>
Here is the background PHP part:
if (isset($_POST['email'],$_POST['g-recaptcha-response'],$_GET['af'])) {
$test="OK";
}
It never prints "OK", I tested the GET part its working fine not empty or null value. But email & g recaptcha part is null. I am not sure why. Previously it used to work without bootstrap integration.
Note: I didn't use echo $test = OK because I am printing this on other pages with echo statement, whole process includes two files,
register-email.php ( Here I am using the echo $test;)
register-email.inc.php (which includes the isset POST sections)
Try to echo $test. You just have stored it, you didn't printed it. And your condition is not even in right syntax.
There are several mistakes here. You cannot mix $_GET and $_POST, in this case, it must be all $_POST. When testing isset(), you cannot just use commas. How about the following:
if (isset($_POST['email']) AND isset($_POST['g-recaptcha-response']) AND isset($_GET['af'])) {
$test="OK";
}
If the above code does not work, check this out.
if(!isset($_POST['email']) echo "Email not set";
if(!isset($_POST['g-recaptcha-response']) echo "Recaptcha not set";
if(!isset($_POST['af']) echo "AF not set";
Now you can see if any of them is not set. Do keep in mind, for $_POST['g-recaptcha-response'] to have a value, a user must correctly answer the reCaptcha image test (Human test), and reCaptcha must be correctly implemented.
form action remove and change submit button name register_email. after add this php code.
if(isset($_POST['register_email'])){header('Location: register-email.php?af=1');exit();}
I solved my problem by myself after lots of debugging. The form was not working because of the redirect. So remove the code of redirect, in fact, use another type of safe coding in order to check if GET is variable is empty or not internally.
if (isset($_POST['email']) AND isset($_POST['g-recaptcha-response'])) {
if ( !isset( $_GET['af'] ) || empty( $_GET['af'] ) ){
$af_code = 1;
}
else {
$af_code = filter_input(INPUT_GET,'af',FILTER_SANITIZE_STRING);
}
}
Now its working safe & sound
I am trying to create php multipage forms, and I use PHP sessions for this purpose.
However, when there is an error in user input and I want the form to ask user to fill in the form again with correct inputs, the forms field will not hold the data that the user has already put in so the user has to start things all over again.
How to make forms sticky with php session?
Thanks
My code is as bellow
<?php
// Session starts here.
if (!isset($_SESSION)) session_start();
?>
<form action="registration.php" method="post">
<center><h8>Please create your user name and password</h8></center>
<div class="imgcontainer">
<img src="phone.gif" alt="Welcome" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required value="<?php if(isset($_POST['username'])) echo $_POST['username'];?>">
<label><b>Password</b></label>
<input type="Password" placeholder="Enter Password" name="password" required>
<label><b>Confirm Password</b></label>
<input type="Password" placeholder="Confirm Password" name="confirm" required>
<span id="error" width=100%>
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo "<error>".$_SESSION['error']."</error>";
unset($_SESSION['error']);
}
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
?>
</span>
<br>
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</div>
and the registration php contains
<?php
if (!isset($_SESSION)) session_start();
// Checking first page values for empty,If it finds any blank field then redirected to first page.
if (isset($_POST['username']))
{
if (($_POST['password']) === ($_POST['confirm']))
{
foreach ($_POST as $key => $value)
{
$_SESSION['post'][$key] = $value;
}
}
else
{
$_SESSION['error'] = "Password does not match with Confirm Password.";
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
header("location: createlogin.php"); //redirecting to first page
}
}
Something like this:
<input name="var" value="<?= isset($_SESSION['var']) ? $_SESSION['var'] : null ?>" />
Try the other way around. Linking the form-action to the current page, and if all fields are valid; redirect it to the next page (registration.php). This way you'd still have all the post-data, you can process everything that needs to be saved in the session- and you can redirect after all of the logic is done.
My two cent would be keep the same page to validate the content and for the form.
You can include other PHP files from a single page depending on if the form is valid.
This way, you keep the same $_POST between both pages and don't need to store the posted data in a session variable.
Otherwise, if you want to keep the same architecture, you need to use the $_SESSION variables instead of the $_POST ones in your input value, such as the answer by delboy.
Replace:
<?php if(isset($_POST['username'])) echo $_POST['username'];?>
With:
<?php if(isset($_SESSION['username'])) echo htmlspecialchars($_SESSION['username']); ?>
^ Note: htmlspecialchars is used to prevent a reflected XSS if the users enters " as username.
The problem is, your data posted to registration.php, so you can't get the posted value in your original file. You are trying to use $SESSION but that's not recommended, and not right. Your whole solution is wrong.
Forget about session and separated files, put everything to registration.php file together.
You can check if user posted or not with $_SERVER['REQUEST_METHOD'] variable.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print 'Something just posted';
}
PS: Don't forget secure the password before you store it! :)
I have a homework and it's a webpage (log-in page) and the task is to enter and bypass the login forum, well the first thing I have looked into was the page's source and I found that if I want the username I should go to /page.phps directory and I did that. After entering that directory I was redirected to another page with this piece of code
<?php
$super_admin_access = false;
// Set our super-admin level user?
if (isset($_GET['user'])) {
$user = html_entity_decode($_GET['user']);
if ($user === "<root>") {
$super_admin_access = true;
}
}
?>
<div class="logo"><img src="../assets/images/challenge-priserv-logo.svg" alt="Nethub logo"></div>
<div class="login">
<form class="form" onsubmit="doLogin(); return false">
<div class="message message-error" id="login-error-msg" style="display: none">Denied!</div>
<div class="field">
<div class="label">Username</div>
<input type="text" name="username">
</div>
<div class="field">
<div class="label">Password</div>
<input type="password" name="password">
</div>
<!-- In case I forget, details are at page.phps -->
<div class="actions">
<input type="submit" value="Access server" class="btn">
</div>
</form>
</div>
I don't know if I understand the php code in the right way, but what I firstly though of was writing the "<root>" in a html entity format which become "<root>", especially that there was a hint saying
Did you see the comment in the source code suggesting you take a look at page.phps? Take a look. What does urldecode do? Can you do the opposite of urldecode?
So I tried to login using the username "<root>" or the encoded one "<root>" I tried removing the quota but no luck, I don't know if there is a password or something like that, I would appreciate any help given, thanks :).
Form's input's name is username, but it checks for user. To get access to the super-duper-mega admin powers, pass a query parameter in the url
http://yoururl/page.php?user=<root>
Seeing as this is a piece of homework I won't give a direct answer, but rather point you in the right direction.
You are definitely on the right track, but you seem to have gotten a little confused with how PHP handles strings.
Let me give you an example. We go to the page login.php?user=tom.
<?php
$user = $_GET['user'];
$desiredUsername = "tom";
if ($user === $desiredUsername) {
echo "You're in!";
}
Let's take a look at the check that if() is doing in this case.
$desiredUsername === "tom"; // true
$desiredUsername === "frank"; // false
$desiredUsername === "jonas"; // false
When you are setting the $user variable in your code, you are wrapping <root> with quotes like so.. "<root>". While the PHP code checks to see if $user === "<root>", the quotes in this case are actually just specifying that we want to see if $user contains the string <root>.
Test your method of using the encoded entities "<root>" with and without the quotes on either side and see what happens.
First it's must be $_GET['username'] NOT $_GET['user'] because input field name is is "username" not "user"
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__);
}