Writing to a text file if username doesn't exist - php

I'm having an issue on writing the registration form to the .txt file if a username exist. At the moment, I don't want to write out to the file if a username exist in the user.txt and print out false and if it doesn't exist, continue and write out to the user.txt file.
<?php
if($_POST['submit'])
{
$usernameexist = $_POST['usernameexist'];
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$address = $_POST['address'];
$membership = $_POST['membership'];
$creditcard = $_POST['creditcard'];
$cardexpiry = $_POST['cardexpiry'];
$duration = $_POST['duration'];
$name = "/^[A-Za-z]+$/";
$emailaddress = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/";
$male_status = 'unchecked';
$female_status = 'unchecked';
// Server side form validation using php.
// Validate username field if empty or not.
if (empty($username)){
$err_username = 'Please enter your username.';
}else{
// Load file and check if username exist
$filename = 'user.txt';
if (file_exists($filename)){
$fp = fopen ('user.txt', 'r');
while ($line = fgetcsv($fp,100,",")) {
if ( ($line[0] == $_POST['username']) ) {
$usernameexist = "Username Exist!";
$err_usernameexist = $usernameexist;
}
}
fclose ($fp);
}
else{
echo '<p> File does not exist! </p>';
}
//$val_username = $username;
}
// Validate password field if empty or not.
if (empty($password)){
$err_password = 'Please enter your password.';
}else{
$val_password = $password;
}
// First Name
if (empty($firstname)){
$err_firstname = 'Please enter your first name.';
}else{
$val_firstname = $firstname;
}
// Last Name
if (empty($lastname)){
$err_lastname = 'Please enter a valid last name.';
}else{
$val_lastname = $lastname;
}
// Gender
if (isset($_POST['submit'])){
$selected_radio = $_POST['gender'];
if($selected_radio == 'Male') {
$male_status = 'checked';
}else if ($selected_radio == 'Female'){
$female_status = 'checked';
}
}
// Email Address
if (!preg_match($emailaddress, $email)){
$err_email = 'Please enter a valid email address.';
}else{
$val_email = $email;
}
if ($_POST['membership'] != 0){
$err_membership = 'Nothing selected!';
}else{
$val_membership = $membership;
}
// Credit Card
if (empty($creditcard)){
$err_creditcard = 'Field is empty, please try again.';
}else{
$val_creditcard = $creditcard;
}
// Card Expiry
if (empty($cardexpiry)){
$err_cardexpiry = 'Field is empty, please try again.';
}else{
$val_cardexpiry = $cardexpiry;
}
// Duration
if (empty($duration)){
$err_duration = 'Field is empty, please try again.';
}else{
$val_duration = $duration;
}
if (!empty($username) && !empty($password) && !empty($firstname)
&& !empty($lastname) && preg_match($emailaddress, $email)
&& ($_GET['membership'] != '0') && !empty($creditcard) && !empty($cardexpiry)
&& !empty($duration)){
$fp = fopen ('user.txt', 'r+');
while ($line = fgetcsv($fp,100,",")){
if($line[0] == $_POST['username']){
$usernameexist = "Username Exist!";
$err_usernameexist = $usernameexist;
echo 'Username EXIST AND WRONG';
}
else{
$output_string = $username. ", "
.$password. ", "
.$firstname. ", "
.$lastname .", "
.$dob .", "
.$gender .", "
.$email .", "
.$address .", "
.$membership .", "
.$creditcard .", "
.$cardexpiry .", "
.$duration ."\n";
$fp = fopen ('user.txt', 'a');
fwrite ($fp, $output_string);
echo "<p> Your Registration was successful! </p>";
}
}fclose($fp);
}
else{
echo 'Please re-check your field as field marked with "*" is required';
}
}
?>
Any help is much appreciate and please excuse my question if it seems too confusing as i am slightly new.
Thanks.

Please forgive apparent criticism but there are a lot of issues with your code and I think it will help if I point out some poor practices first:
Don't keep reassigning variables. Just use them as $_POST['whatever'] there is no advantage in copying them into other memory intensive structures. It obfuscates rather than clarifying your code.
DO NOT EVER store credit card details in a plain text file.
Why are you using a custom CSV data structure? This is what databases are for XML at a pinch.
You test for username existence twice, neither in the right place to fix the problem.
For your answer:
if (!empty($username) && !empty($password) && !empty($firstname)
&& !empty($lastname) && preg_match($emailaddress, $email)
&& ($_GET['membership'] != '0') && !empty($creditcard) && !empty($cardexpiry)
&& !empty($duration)){
$fp = fopen ('user.txt', 'r+');
while ($line = fgetcsv($fp,100,",")){
if($line[0] == $_POST['username']){
$usernameexist = "Username Exist!";
$err_usernameexist = $usernameexist;
echo 'Username EXIST AND WRONG';
}
else{
$output_string = $username. ", "
etc...
Seems to be your problem here. What this says is: "If the data is wrong, check to see if the username exists and if it does, say so, otherwise if the data is correct, post it to the file. [but don't test for username existence first]
Essentially, you are testing for the existence of the username in the wrong place.
Move the username existence check to the other side of the else. You could even (riskily) test for strlen($err_usernameexist)>0 as this will return true if the username exists.
Once again though, this is dangerous code and although it forms an interesting exercise in CSV file manipulation it is not appropriate for the apparent application type it seems to be designed for. It will also break if a user puts a comma in their data.
you could use fputcsv properly by creating an array which is immune to commas though not to quotes:
myarray=array($name,$password,$encryptedcreditcard,$etcetc);
fputcsv($fp,$myarray);
You SHOULD however save the data in mysql where you can at least AES_ENCRYPT your confidential data.
Alternatively, there are plenty of AES classes posted free for PHP. Mysql will handle very large data sets quickly whilst yours just gets slower and slower with time...

Related

PHP Sign-up Form Issues with Validation and Insertion

I'm looking to create a sign-up page for a large-scale website which means I'm using a lot more layers of validation then I would normally do, given this should be common practice but in this particular case more than any other situation it is imperative.
I've already written most of the code required and formatted it in an order which I believed wouldn't lead to any undefined variable errors, however, upon form submission it doesn't create a new SQL row and doesn't return any errors under the error handling areas of the form validation. In all fairness, the error handling is quite simple at this point and is not a final version, just what I put in place to help me debug and troubleshoot any issues which should arise.
Here's the PHP code, and the snippet of the piss-poor error handling that is supposed to output an error message if an error occurs, to re-state, this error handling isn't final.
$conn = mysqli_connect('localhost', 'root2', '123', 'db');
$signupConditionsMet = "0";
if (isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["passwordCheck"]) && isset($_POST["birthdate"])) {
$signupConditionsMet = "1";
$birthGood = true;
$passGood = false;
$nameGood = false;
$emailGood = false;
}
$usernameSearch = $conn->prepare("SELECT * FROM users WHERE username = ?");
$userInsertion = $conn->prepare("INSERT INTO users (username, passwd, birthdate, email) VALUES (?,?,?,?)");
$nameErr = $emailErr = $passErr = $birthErr = "";
$name = $email = $pass = $birth = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];
$pass = $_POST["password"];
$birthdate = $_POST["birthdate"];
$passCheck = $_POST["passwordCheck"];
}
if ($signupConditionsMet === "1"){
function test_input($name) {
if (!preg_match("/^[a-z\d_]{2,15}$/i",$name)) {
$nameErr = "Only letters and white space allowed";
} else {
$nameGood = true;
return $name;
echo "did name ez";
}
}
function test_input2($email){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$emailGood = true;
return $email;
echo "did email ez";
}
}
function test_input3($password){
if (!preg_match("/^[a-z\d_]{2,15}$/",$pass)) {
$passErr = "Invalid password format";
} else if (!preg_match("/^[a-z\d_]{2,15}$/",$passCheck)){
$passErr = "Invalid password check format";
} else if ($_POST["password"] !== $_POST["passwordCheck"]){
$passErr = "Passwords do not match";
} else {
$passwd2 = AES_ENCRYPT($_POST["password"], 'mysecretstring');
$passwdGood = true;
return $passwd2;
echo "did pass ez";
}
}
}
if (($signupConditionsMet === "1") && ($birthGood === true) && ($nameGood === true) && ($passwdGood === true) && ($emailGood === true)) {
if ($usernameSearch->execute(array($_POST['username']))) {
while ($row = $usernameSearch->fetch()) {
if (!empty($row['id'])) {
$creationError = "This username is already taken";
} else {
$userInsertion->bindParam(1, $name);
$userInsertion->bindParam(2, $passwd2);
$userInsertion->bindParam(3, $birthdate);
$userInsertion->bindParam(4, $email);
$userInsertion->execute();
header('Location: userlanding.php');
}
}
}
}
/* PHP inside the HTML to output errors */
<?php if ($signupConditionsMet === "1") { echo "all inputs received"; echo $_SERVER["REQUEST_METHOD"];} else { echo "drats, they weren't all there"; echo $name; echo $email; echo $birthdate; echo $pass; echo $passCheck;}?>
<?php if ($passErr) { echo $passErr;} else if ($nameErr) { echo $nameErr;} else if ($emailErr) { echo $emailErr;} else if ($birthErr) { echo $birthErr;} ?>
Disregarding the previously admitted terrible error handling, I can't seem to wrap my head around why it doesn't work in its current form. It returns (from the client-side reporting) that all inputs were received and there isn't any fatal errors thrown from running the PHP code. In addition, the second client-side code which prints any errors doesn't print anything either, implying that all functions operated correctly, however, the echos at the bottom of the input tests don't echo the strings they've been assigned, implying those didn't work, but there was no errors. Hmm. Perhaps I'm missing something blatantly obvious regarding my syntax but I don't see why it wouldn't work. Any help would be appreciated.

PHP sign up code

I am creating my first sign in/register function to my web site by following a online tutorial. Every thing seems to be working good , My problem is in the tutorial the php if ($_SERVER['REQUEST_METHOD'] == 'POST') is set in the index page which checks if all the fields and then inserts them into the DB . But for me this not seem to work. But if I put the code onto the page where the form action redirects after it works fine. Is this the right way to do it. I wouldn't like to think so because I would like to check all the variable before we move on.
So if someone would like to educate me on this would be great.
Here is my php code still not fully finished but i wanted to clear this up first.
This is used by include method
<?php
//setup some variables/arrays
$action = array();
$action['result'] = null;
//check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$message = "wrong answer";
echo "<script type='text/javascript'>alert('$message');</script>";
$firstName = mysqli_real_escape_string($link,$_POST['firstName']);
$lastName = mysqli_real_escape_string($link,$_POST['lastName']);
$password = mysqli_real_escape_string($link,$_POST['sign-up-password']);
$confirmPassword = mysqli_real_escape_string($link,$_POST['password-confirm']);
$email = mysqli_real_escape_string($link,$_POST['email2']);
//quick/simple validation
if(empty($firstName)){ $action['result'] = 'error';}
if(empty($lastName)){ $action['result'] = 'error';}
if(empty($password)){ $action['result'] = 'error';}
if(empty($email)){ $action['result'] = 'error';}
if($password != $confirmPassword){ $action['result'] = 'error';}
if($action['result'] != 'error'){
$add = mysqli_query($link,"INSERT INTO `users` VALUES(NULL,'$firstName','$lastName','$password','$email',0)");
if($add){
//the user was added to the database
//get the new user id
$userid = mysqli_insert_id($link);
//create a random key
$key = $firstName . $email . date('mY');
$key = md5($key);
//add confirm row
$confirm = mysqli_query($link,"INSERT INTO `confirm` VALUES(NULL,'$userid','$key','$email')");
if($confirm){
//let's send the email
}
}else{
$action['result'] = 'error';
array_push($text,'User could not be added to the database. Reason: ' . mysql_error());
}
}else{
}
}
?>

basic php else if not working

I have some php validation for a user signup form. It's validating all the input then if all is correct the else at the end, checks to see if that username is in use and if not creates that record in the database. For some reason the last else doesn't get activated and it just refreshes with all the data still in the input boxes. I can't find the problem anywhere!!
if(isset($_POST['user']))
{
$firstname = sanitiseString($_POST['firstname']);
$surname = sanitiseString($_POST['surname']);
$user = sanitiseString($_POST['user']);
$pass = sanitiseString($_POST['pass']);
$email = sanitiseString($_POST['email']);
$dateOfBirth = sanitiseString($_POST['dateOfBirth']);
$gender = sanitiseString($_POST['gender']);
$test_arr = explode('-',$dateOfBirth);
if($firstname == "" || $surname =="" || $user == "" || $pass == "" || $email == "" || $dateOfBirth == "" || $gender == "")
{$error = "Not all fields were entered</br></br>";}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{$error = "Email format invalid</br></br>";}
else if(count($test_arr) == 3)
{
if (!checkdate($test_arr[0], $test_arr[1], $test_arr[2]))
{$error = "Enter a date in the format: MM-DD-YYYY</br></br>";}
}
else if(count($test_arr) <> 3)
{$error = "Enter a date in the format: MM-DD-YYYY</br></br>";}
else
{
$result = querySQL("SELECT * FROM members WHERE user='$user'");
if($result->num_rows)
{$error = "That Username already exists</br></br>";}
else
{
querySQL("INSERT INTO members VALUES('','$firstname','$surname','$user','$pass','$email','$dateOfBirth','$gender')");
die("<h4>Account Created</h4>Please Log In.</br></br>");
}
}
}
First thing to comment on is the incredible amount of nested logic this script has; it's not uncommon to lose control of the flow when you're if / else branching gets out of control.
Example Restructure
if (isset($_POST['user']))
{
// Prep
$error = '';
// Sanitize
foreach( $_POST as $varName => $value )
{
// Doing this for minification on Stackoverflow
$$varName = sanitiseString($_POST[$varName]);
// Validate
if ( empty($$varname) )
$error .= "Not all fields were entered<br /><br />";
}
// Valid Email?
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$error .= "Email format invalid<br /><br />";
// Validate date
$dateArray = explode('-', $dateOfBirth);
if (!checkdate($dateArray[0], $dateArray[1], $dateArray[2]))
{
$error .= "Enter a date in the format: MM-DD-YYYY</br></br>";
}
$result = querySQL("SELECT * FROM members WHERE user='$user'");
if ($result->num_rows)
{
$error .= "That Username already exists</br></br>";
}
if ( !empty($error) )
die($error);
querySQL("INSERT INTO members VALUES('','$firstname','$surname','$user','$pass','$email','$dateOfBirth','$gender')");
die("<h4>Account Created</h4>Please Log In.</br></br>");
}
Some other things to note are conflicting logic with your count($test_arr) == 3 and count($test_arr) <> 3. And the value of $result->num_rows may not be 0, as your expecting.

How to validate a connection between JS And PHP

PHP Code:
$dom = new DOMDocument;
$headtitle = "Register";
$errors = array();
if(isset($_POST['register'])){
$username = preg_replace('/[^A-Za-z]/', '', $_POST['username']);
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$c_password = $_POST['c_password'];
$birthday = $_POST['birthday'];
$country = $_POST['country'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$level = $_POST['level'];
$date = $_POST['date'];
if(file_exists('users/' . $username . '.xml')){
$errors[] = ' Username already exists';
}
if($username == ''){
$errors[] = ' Username is missing. Try again.';
}
if($name == ''){
$errors[] = ' Name is missing. Try again.';
}
if($lastname == ''){
$errors[] = ' Lastname is missing. Try again.';
}
if($country == ''){
$errors[] = ' Country is missing. Try again.';
}
if($gender == ''){
$errors[] = ' Gender is missing. Try again.';
}
if($age == ''){
$errors[] = ' Age is missing. Try again.';
}
if($email == ''){
$errors[] = ' Email is missing. Try again.';
}
if($password == '' || $c_password == ''){
$errors[] = ' Passwords are missing. Try again.';
}
if($password != $c_password){
$errors[] = ' Passwords do not match';
}
if(count($errors) == 0){
$xml = new SimpleXMLElement('<user></user>');
$xml->addChild('name', ($name));
$xml->addChild('lastname', ($lastname));
$xml->addChild('password', md5($password));
$xml->addChild('birthday', $birthday);
$xml->addChild('country', $country);
$xml->addChild('gender', $gender);
$xml->addChild('age', $age);
$xml->addChild('email', $email);
$xml->addChild('level', $level);
$xml->addChild('date', $date);
$xml->asXML('users/' . $username . '.xml');
header('Location: index.php');
die;
}
}
Javascript Code:
function vaildate() {
if (document.getElementById('username').value.length <= 4) {
document.getElementById('errors').innerHTML = "Username must me more than 4 words <br />";
return false;
}
return true;
}
Now my problem is, that when I click submit button (that contains name="login" and onclick="vaildate();") he excute only php errors and ignores javascript errors (assuming that id="username" has less than 4 words).
My question is how can I make Javascript & PHP errors work? not only PHP and the system ignores Javascript.
Thank you all..
EDIT:
Also i got this code to echo PHP errors
if(count($errors) > 0){
echo '<font color="red"><ul>';
foreach($errors as $e){
echo '<li>' . $e . '</li>';
}
echo '</ul></font>';
}
Try this:
onclick="return vaildate();"
You need to return the validate function (return the true or false), not just call it.
Your Javascript and PHP you are showing looks fine. What we don't have is the actual markup of the login page. My suspicion is that your markup is not consistent with the code you have in your Javascript.
If you could also try and explain more specifically what you mean by
My question is how can I make Javascript & PHP errors work? not only PHP and the system ignores Javascript.
Have you used a Javascript debugger to see if part your Javascript (maybe elsewhere on the page) is erroring?

registration form in php

$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';
$yourname='';
$email='';
$email2='';
$password='';
$password2='';
$country='';
if (isset($_POST['Registerme']))
{
$_POST['yourname']=$yourname;
$_POST['email']=$email;
$_POST['email2']=$email2;
$_POST['password']=$password;
$_POST['password2']=$password2;
$_POST['country']=$country;
if($yourname==''){
$error1='name required';
}
if($email==''){
$error2='email required';
}
if($email2==''){
$error3='required field';
}
if($password==''){
$error4='password required';
}
if($password2==''){
$error5='required field';
}
if($country==''){
$error6='country required';
}
if(empty($error1) && empty($error2) && empty($error3) && empty($error4) && empty($error5) && empty($error6))
{echo 'mysql query goes here and add the user to database';}
}///main one
else {$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';}
this is a registration validation script. in my registration form there are two email and password filelds.second fields are for confirmation.i want to check weather user typed same information in that both field.if i want to do that in this script should i use another if statement? or i should use else if? i am confused about that step...
Some comments:
You MUST sanitize input! Take a look at best method for sanitizing user input with php.
Your assignments: Instead of "$_POST['yourname']=$yourname;" it should be "$yourname=$_POST['yourname'];".
You're using a lot of variables for error control, and after that if all went well you simply forget the error messages in the last else block. Use some kind of array for error strings, and use it!
Are you sure you aren't validating usernames/passwords to not contain spaces or weird characters, or emails to be valid?
Some sample code...:
// Simple sanitize function, complete it
function sanitize_input ($inputstr) {
return trim(mysql_real_escape_string($inputstr));
}
if (isset ($_POST['Registerme']) {
// array of error messages to report
$error_messages = array();
$isvalid = true;
// Assignment
$yourname = sanitize_input ($_POST['yourname']);
$email = sanitize_input ($_POST['email']);
$email2 = sanitize_input ($_POST['email2']);
$password = sanitize_input ($_POST['password']);
$password2 = sanitize_input ($_POST['password2']);
$country = sanitize_input ($_POST['country']);
// Validation
if (empty ($yourname)) {
$error_messages[] = "You must provide an username";
}
if (empty ($password)) {
$error_messages[] = "You must provide a password.";
}
elseif ($password !== $password2) {
$error_messages[] = "Passwords do not match.";
}
// Same for email, you caught the idea
// Finally, execute mysql code if all ok
if (empty($error_messages)) {
// Execute mysql code
isvalid = true;
}
}
// After form processing, use isvalid which is false if there are errors
// and the error_messages array to report errors
add additional conditions to your second if statement.
e.g.
if($email=='' || $email != $email2){
...
Just add simple checks. I wouldn't combine the check with the general password check - as I can imagine you would like to tell the user what went wrong exactly.
if ($password1 !== $password2) {
// Add an specific error saying the passwords do not match.
}
I would replace the user of loose errors to an array like:
$aErrors = array();
if ($password1 !== $password2) {
$aErrors[] = 'Another specific error!';
}
if (empty($password1) || empty($password2)) {
$aErrors[] = 'Another specific error';
}
if (empty($aErrors)) {
// Process the form!
}
There are lots of issues with your code.
1. You are assinging $_POST['key'] = $somevalue, while I think you mean $somevar = $_POST['key']
2. Use an array for all error messages as it'll make your life a bit easier ..
3. To compare password use something like
if ($password1 !== $password2) {
}
so .....
$errors = array();
so you'd check something like ..
if ($password1 !== $password2) {
$errors[] = 'Password dont match';
}
if(count($errors) > 0) { //if there are errors
foreach($errors as $err) {
echo $err.' <br />';
}
} else {
// whatever you want to do if no error
}
I'll also suggest to sanitise the $_POST values before you use them in your queries.
I hope it helps.
I think you mean to do this:
$yourname = $_POST['yourname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$country = $_POST['country'];
Second this make use of an errors array:
$errors = array();
Third use nested ifs(just a suggestion)
if (!empty($_POST['password1'])) {
if ($_POST['password1'] != $_POST['password2']) {
$errors[] = '<font color="red">The 2 passwords you have entered do not match.</font>';
} else {
$password = $_POST['password1'];
}
} else {
$errors[] = '<font color="red">Please provide a password.</font>';
}

Categories