I have a registration form which posts data to save.php. But occasionally the data is getting posted multiple times.
Below is my code for save.php
<?php
session_start();
//save registration details in my table
include('connect_database.php');
include('my_functions.php');
$_SESSION['newUser'] = '0'; // new user
//POSTED DATA--------------------------
$t_email = $_POST['email'];
$t_psw = $_POST['psw'];
$t_first_name = addslashes($_POST['first_name']);
$_SESSION['lastname'] = $t_last_name = addslashes($_POST['last_name']);
$t_mobile = $_POST['mobile'];
$_SESSION['licNum'] = $t_lic_no = $_POST['lic_no'];
$t_dob = $_POST['dob'];
$t_abn = $_POST['abn'];
$tx_expiry = $_POST['tx_expiry'];
$drv_for = $_POST['driven_for'];
$lng_drv = $_POST['long_driven'];
//referred by
$ref_drLic = $_POST['ref_driLic'];
$ref_drName = $_POST['ref_driName'];
$t_dr_front = get_image('dr_front',$_POST['last_name'].'_dr_front');
$t_dr_bck = get_image('dr_bck',$_POST['last_name'].'_dr_bck');
//if tx required-------
if($_SESSION['ce_cr_tx'] == 1){
$t_tx_front = get_image('tx_front',$_POST['last_name'].'_tx_front');
$t_tx_bck = get_image('tx_bck',$_POST['last_name'].'_tx_bck');
}
else{
$t_tx_front = "";
$t_tx_bck = "";
}
//store data in logfile
$nwtxt = "Email is - ".$_POST['email'].". Mobile no - ".$_POST['mobile'];
writeFile($nwtxt);
//---------------------------------------
//query to save data in my table
$ad_sql = "INSERT INTO myTable (email, password, firstname, lastname, mobile, licence, drfront, drbck, txfront, txbck, cnfrm, dob, abnf, texpiry, drifor, driven, reLic, reNname)
VALUES('".$t_email."','".$t_psw."','".$t_first_name."','".$t_last_name."','".$t_mobile."','".$t_lic_no."','".$t_dr_front."','".$t_dr_bck."','".$t_tx_front."','".$t_tx_bck."','0','".$t_dob."','".$t_abn."','".$tx_expiry."','".$drv_for."','".$lng_drv."','".$ref_drLic."','".$ref_drName."')";
if(!empty($t_email)){
if($conn->query($ad_sql) == true){
//echo'Success';
$lst_id = $conn->insert_id;
$_SESSION['ls_id'] = $lst_id;
$_SESSION['s_email'] = $t_email;
$_SESSION['s_code'] = mt_rand(11111,99999);
//email code to user--------------------------
$subjct = "Email Verification Code";
$usr_msg = "Hi ".$_POST['first_name']." ".$_POST['last_name'].",<br><br>
A new account has been requested at 'Portal'
using your email address.<br><br>
To confirm your new account, please enter this code in the web page:<br>
<h3>".$_SESSION['s_code']."</h3><br><br>
If you need help, please call us<br><br>
Thank you,
Administrator";
sendEmail($t_email, $usr_msg, $subjct); //sends and email
writeFile('Code is :'.$_SESSION['s_code']); // write a log in file
//--------------------------------------------
//redirect to verify email page----------------------
header("location: verifyEmail.php");
exit();
}
else{
echo'Error creating account- '.$conn->error.'. Please try again.';
$gbck = "cr=".$_SESSION['ce_cr_id']."&crs=".$_SESSION['ce_cr_nm']."&tx=".$_SESSION['ce_cr_tx']."&erms=Error creating account. Please try again";
header('location: Enroll.php?'.$gbck);
exit();
}
}
else{
echo'Error creating account. Please try again.';
$gbck = "cr=".$_SESSION['ce_cr_id']."&crs=".$_SESSION['ce_cr_nm']."&tx=".$_SESSION['ce_cr_tx']."&erms= EMPTY data. Error creating account. Please try again";
header('location: Enroll.php?'.$gbck);
exit();
}
?>
I checked my code multiple times but couldn't find anything that is triggering it. When someone registers, the page keeps loading for sometime and I receive multiple entries in database and user receives multiple verification emails.
Is something wrong in my code?
The code itself looks fine, but i get the growing suspicion that it might be a config issue or whats happening before this executes. If your looking for a patchwork fix i would probably put a condition near your if(!empty($t_email)) that checks if the sql table row already exists dont execute, which would rectify the fact that multiple requests are coming in.
Related
<?php
$filename = 'whitelist.txt';
if (isset($_POST['uname'])) {
$uname = $_POST['uname'];
file_put_contents($filename, '{"'.$uname.'"}');
if (empty($uname)) {
header("Location: generator.php?error=No Empty Username");
exit();
}
}else{
header("Location: generator.php");
exit();
}
The expected output should be:
{"User1", "User2"}
But it is:
{"User1"}
I just wanna make a whitelist user by using a form so he can get whitelisted, I hope someone can help! Thank you!
To make a user blacklist you'll need to use some database and authentication otherwise you'll end up with problems in a case where like user1 and user2 have the same data
But for your question.
One way is to replace the last character every time here is how...
replace the file_put_con... line with this
$existing = file_get_contents($filename);
if(strpos($existing,"}")){ //check if at least one username exists
$newcontent = str_replace('}',',"'.$uname.'"}',$existing); //replace old data with new
file_put_contents($filename,$newcontent);
} else { // incase there is no username at all
$newcontent = '{"'.$uname.'"}';
file_put_contents($filename,$newcontent);
}
You'll obviously corrupt the data if you enter } in the uname
So prevent that by using entities or prevent the } character from being accepted
I am writing a code snippet to send a email notification with a dynamic link that includes a db token. I am receiving the email which is handled by different code but for some reason I the button will not hyperlink and I think it's because this code block is not generating the link properly.
Can anyone point me in the right direction here?
public function sendVerification2($writerID, &$errors) {
$sql = "SELECT
user.`user_id` id,
user.`email_1` email,
user.`usr_verify_email_token` vtoken
FROM
`writer_split` split,
`writer`,
user
WHERE
split.`writer_id` = writer.`writer_id`
AND
writer.`user_id` = user.`user_id`
AND
split.`writer_id` = ?
LIMIT 1
";
$user = $this->db->select($sql, array($writerID), $errors);
if (count($errors) > 0 || count($user) === 0) {
return;
}
$user = $user[0];
//Add the change url to the the user array
$user[0]['verifyUserLink'] = $this->authconfig['verifyUser'] . $user['vtoken'];
//Send an e-mail to the user with the token
$this->mailer->sendTemplate($user[0]['email'], 'new_user', $user[0], $errors);
return count($errors) === 0;
}
I am trying to create a "flash" success message which pops up when the user successfully changes their password. But, It doesn't work how I would like it to.
The basic idea is, when people enter their new password (and it passes to the database), it will echo to the page "Successfully updated password". But it will only echo once (when the user refreshes, the echoed message will disappear and not display again until they submit a new password).
I have tried searching around, but I can't seem to find any scripts that will actually work how I would like them to.
This is my PHP function, currently:
function updatePassword($conn, $newpwd, $username){
$newpwd = hash('md5', $newpwd);
mysqli_query($conn, "UPDATE users SET password = '$newpwd' WHERE username = '$username'");
}
Cheers.
Let me explain you pseudo logic.
Steps:
1) When your password change is done successfully, assign success message to a session variable.
$_SESSION['message'] = 'Password changed successfully.';
2) On the redirected success page, echo this.
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
Also, unset() it, so that, it will not be shown other time again.
I created something myself recently, the code could probably be better though, but it works.
function flash_message($message, $type = 'success') {
switch($type) {
case 'success':
$class = "success";
break;
case 'info':
$class = "info";
break;
case 'error':
$class = "error";
break;
}
$_SESSION['flash_message'] = "<p class='flash_message ".$class."'>".$message."</p>";
}
function show_flash_message() {
if (isset($_SESSION['flash_message'])) {
$message = $_SESSION['flash_message'];
unset($_SESSION['flash_message']);
return $message;
}
return NULL;
}
You use show_flash_message() on the page where you want to display it. If there is no message, it wont display anything.
You'd call it by doing this:
function updatePassword($conn, $newpwd, $username){
$newpwd = hash('md5', $newpwd);
mysqli_query($conn, "UPDATE users SET password = '$newpwd' WHERE username = '$username'");
flash_message('Successfully changed your password');
}
The different classes are for if you want to change the display of the message. (Wrong username/password is an error, e-mail been sent can be info/success etc.)
I have a website running on a less well known CMS called Ushahidi. There is built in OpenID functionality where folk can login with Facebook or Google.
I don't have enough dev skills to understand whats happening here but, it appears that I've almost got it working, except, I'm receiving the following error when trying to test it out on my own Google login:
An error was detected which prevented the loading of this page. If
this problem persists, please contact the website administrator.
application/controllers/login.php [503]: Undefined variable: user
I suspect, but am not sure, that defining a variable is easy enough but since I lack the knowledge I hoped to ask someone on here if they could see where I need to define the variable. Line 503 is part of a larger code block of about 100 lines, I know that it's not good practice to post larger chunks of code on here but I'm really unsure of what is and is not relevant. So forgive me. I have highlighted in bold where line 503 is. Can anyone point out what I must do here?
// OpenID Post
try
{
$openid = new OpenID;
// Retrieve the Name (if available) and Email
$openid->required = array("namePerson", "contact/email");
if( ! $openid->mode)
{
if(isset($_POST["openid_identifier"]))
{
$openid->identity = $_POST["openid_identifier"];
header("Location: " . $openid->authUrl());
}
}
elseif ($openid->mode == "cancel")
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = "You have canceled authentication!";
}
else
{
if ($openid->validate())
{
// Does User Exist?
$openid_user = ORM::factory("openid")
->where("openid", $openid->identity)
->find();
if ($openid_user->loaded AND $openid_user->user)
{
// First log all other sessions out
$auth->logout();
// Initiate Ushahidi side login + AutoLogin
$auth->force_login($openid_user->user->username);
// Exists Redirect to Dashboard
**(THIS IS LINE 503)** url::redirect($user->dashboard());
}
else
{
// Does this openid have the required email??
$new_openid = $openid->getAttributes();
if ( ! isset($new_openid["contact/email"]) OR
empty($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . " has not been logged in. No Email Address Found.";
}
else
{
// Create new User and save OpenID
$user = ORM::factory("user");
// But first... does this email address already exist
// in the system?
if ($user->email_exists($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $new_openid["contact/email"] . " is already registered in our system.";
}
else
{
$username = "user".time(); // Random User Name from TimeStamp - can be changed later
$password = text::random("alnum", 16); // Create Random Strong Password
// Name Available?
$user->name = (isset($new_openid["namePerson"]) AND ! empty($new_openid["namePerson"]))
? $new_openid["namePerson"]
: $username;
$user->username = $username;
$user->password = $password;
$user->email = $new_openid["contact/email"];
// Add New Roles
$user->add(ORM::factory('role', 'login'));
$user->add(ORM::factory('role', 'member'));
$user->save();
// Save OpenID and Association
$openid_user->user_id = $user->id;
$openid_user->openid = $openid->identity;
$openid_user->openid_email = $new_openid["contact/email"];
$openid_user->openid_server = $openid->server;
$openid_user->openid_date = date("Y-m-d H:i:s");
$openid_user->save();
// Initiate Ushahidi side login + AutoLogin
$auth->login($username, $password, TRUE);
// Redirect to Dashboard
url::redirect($user->dashboard());
}
}
}
}
else
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . "has not been logged in.";
}
}
}
catch (ErrorException $e)
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $e->getMessage();
}
The problem is that the code is using $user several lines before it's actually defined. It might be a typo, though - maybe $openid_user->user->dashboard() at line 503 might work, though it's a WAG.
I am very new to PHP and still trying to learn the "ins and outs" to it.(Self-taught) I have a petition website that I had a friend develop a code for, to block identical ip's from signing more than once.
This particular petition is sent to offices with multiple signers that use the same IP, so I am needing to change the code from blocking duplicate IP's to blocking duplicate "GLVAR" numbers the signer provides. I have the database setup, but I just dont know where to exactly change the coding to make this work.
Also, I am trying to send the information the signer submitted to my email address for an extra copy. I know this should be simple, but like I said, I am self teaching and very new, so any help would be greatly appreciated. Thank you so much for your time.
<?php
include('database/config.php');
include('database/database.php');
$err = '';
if(isset($_POST['submit'])){
$first = addslashes(trim($_POST['first']));
$last = addslashes(trim($_POST['last']));
$glvar = addslashes(trim($_POST['glvar']));
$ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
//echo $ip;
if(($first!='')&& ($last!='')&& ($glvar!='')){
$database = new Database(HOST, DATEBASE, USERNAME, PASSWORD);
$allUsers = $database->select('user','ip','*',"ip = '".$ip."'");
//echo $ip;
$checkIp = 0;
$checkIp = count($allUsers);
$userData = array(
'first_name' => $first,
'last_name' => $last,
'glvar_id' => $glvar,
'ip' => $ip,
);
if(!$checkIp) {
$database->insert('user',$userData);
header('location:thank-you.html');
} else $err.='<p style="color:red">Ooops! You have already signed the petition</p>';
} else {
if($first=='') $err.='<p style="color:red">Your first name not empty</p>';
if($last=='') $err.='<p style="color:red">Your last name not empty</p>';
if($glvar=='') $err.='<p style="color:red">Your GLVAR ID not empty</p>';
}
}
?>
You should query the database for the glvar rather than the IP:
It might look like this depending on what the glvar_id columns look like in the database.
$allUsers = $database->select('user','glvar_id','*',"glvar_id = '".$glvar."'");
//echo $ip;
$checkglvar = 0;
$checkglvar = count($allUsers);
if you want to mail yourself on success then you will want to configure the php mail function for work and add it here:
if(!$checkIp) {
$database->insert('user',$userData);
mail("to#me.com", "Subject", "message");
header('location:thank-you.html');
}