codeigniter form submit removes get variables from url - php

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...

Related

How to get the variable passed from another page when form is submitted

I'm working on password reset in core php.
I'm sending code variable from reset.php to resetPassword.php page like this:
reset.php
$code = uniqid(true);
$url = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/resetPassword.php?code=$code"
resetPassword.php
global $code;
if(!isset($_GET['code'])){
echo "There is No Code there !!!";
}
if(isset($_GET['code'])){
$code = $_GET['code'];
echo "The code is set at first , just at visit of the page ".$code;
}
// make sure there is row in the table that matches that passed code
$findEmail = mysqli_query($link,"SELECT `email` from resetpasswords WHERE `code` = '$code' ");
if(mysqli_num_rows($findEmail)==0){ // if no row found
echo "<h2 class = 'text text-center'>No Record regarding this email !</h2>";
exit();
}
// when form submits
if(isset($_POST['reset'])){
$password = md5($_POST['password']);
$confirm = md5($_POST['confirm']);
if($password!=$confirm){
echo "Password Don't matches !";
exit();
}
$row = mysqli_fetch_array($findEmail);
$email = $_POST['email'];
$updatePass = mysqli_query($link,"UPDATE `user` SET user_password = '$confirm' where email = '$email'");
if($updatePass){
$query = mysqli_query($link,"DELETE FROM resetpasswords where code = '$code' ");
exit('Password Updated, Please Login with the New Password');
}
else{
exit('Something went wrong');
}
}
On the same page resetPassword.php, I have the following code:
<form action="resetPassword.php" method="POST">
<div class="form-group">
<label for="password2">Password:</label>
<input type="password" class="form-control" name="password" id="password2" onkeyup="checkPass();">
</div>
<div class="form-group">
<label for="confirm2">Confirm Password:</label>
<input type="password" class="form-control" name="confirm" id="confirm2" onkeyup="checkPass();">
<span id="confirm-message2" class="confirm-message"></span>
</div>
<input type="hidden" value="<?php echo $code;?>">
<input type="submit" name="reset" value="Update Password" class="btn btn-success">
</form>
Problem:
The problem is when I submit the form , it goes all the way to the top of the page, and start executing the resetPassword.php page from the top, due to which for resetPassowrd.php page, it can't get that $code variable.
Because when I submit the form,the condition (!isset($_GET['code'])) at top of resetPassword.php becomes true and it gives me:
There is No Code there !!!
And I want to have that $code when I submit the form.
What I tried:
I tried to use hidden field with value of $code but that didn't worked.
please help me thanks
Consider the below points
1) Use prepared statements and parameterized queries.
2) Use password_hash() and password_verify() to secure your password.
3) In resetPassword.php page, if you submit the form with action="resetPassword.php" this will redirect to resetPassword.php. So replace your action with this
$full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
<form action="<?php echo $full_url ?>" method="POST">
You are missing name attribute in your hidden field and hence you are not able to find the value of $code.
Instead of
<input type="hidden" value="<?php echo $code;?>">
Try
<input type="hidden" value="<?php echo $code;?>" name="code" />

Conflict between Login form and Register form in the same page

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

PHP - Redisplay forms with valid values in fields and error messages where validation fails

I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

Echoing $_POST error on correct page

thanks for reading.
I have an issue getting an error to echo on the correct page after a form submit. When the form is submitted, it redirects to website.com/controllers/accountController.php. I would like it to refresh the current page, website.com/play.php?p=myaccount
Please note that the form is submitting, it is just printing the error on the redirected page instead of the page with the form.
Please take a look at my previous question (related, but different question altogether).
HTML form (myaccount.inc.php):
<div id="change-password">
<form class="clearfix" action="controllers/accountController.php" method="post">
<div><span class="he1">Change Password</span></div>
<div><label class="DEVON" for="password">Current Password:</label></div>
<input type="password" name="password" id="password" size="23" /><br />
<div><label class="DEVON" for="passwordnew1">New Password:</label></div>
<input type="password" name="passwordnew1" id="passwordnew1" size="23" /><br />
<div><label class="DEVON" for="passwordnew2">Confirm New Password:</label></div>
<input type="password" name="passwordnew2" id="passwordnew2" size="23" /><br />
<input type="submit" name="submit" value="Change Password" class="bt_changepass" />
</form>
</div>
PHP code (accountController.php):
<?php
// Checking whether the Password Change form has been submitted.
if(isset($_POST['submit'])=='Change Password')
{
echo "<br />";
// Get the data from the database.
$sql = $mysqli->query("SELECT * FROM ss_members WHERE usr = '".$_SESSION['usr']."' AND pass = '".md5($_POST['password'])."'");
$row = $sql->fetch_assoc();
// Will hold our errors
$err = array();
if($_POST['password'] == "" || $_POST['passwordnew1'] == "" || $_POST['passwordnew2'] == "")
{
$err[] = 'All the fields must be filled in!';
}
if(!$row['pass'] == md5($_POST['password']) && $_POST['passwordnew1'] != "" && $_POST['passwordnew2'] != "")
{
$err[] = 'Current password is not correct!';
}
if($_POST['passwordnew1'] <> $_POST['passwordnew2'])
{
$err[] = 'New passwords do not match!';
}
if(!count($err))
{
if($row['usr'])
{
// If everything is OK change password.
$stmt = $mysqli->prepare("UPDATE ss_members SET pass = md5(?) WHERE usr = {$_SESSION['usr']}");
$stmt->bind_param('s', $_POST['passwordnew1']);
$stmt->execute();
$stmt->close();
echo "Password has been sucessfully updated!<br />";
}
else
{
$err[]='Something broke!';
}
}
if($err)
{
// Save the error messages in the session.
foreach($err as $error)
{
echo $error . "<br />";
}
}
echo "<br />";
}
if(isset($_POST['submit'])=='Change Password') statment is wrong.
Because isset always return Boolean so your if won't execute ever.
OR
You can use it as
if(isset($_POST['submit']) && $_POST['submit'] =='Change Password')
if(isset($_POST['submit'])=='Change Password')
isset returns true of false when comparing it with the change password will return false
Regards.
if(isset($_POST['submit'])=='change Password')
this usage is not valid in php

php stop user from viewing logs

<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 />
<?
}

Categories