I need to create very simple register/login system in PHP. User details must be stored in array in txt file. For some reasons even when PHP not show any error details are not saved to txt file. Any hint?
$fullname='';
$email ='';
$username ='';
$password = '';
$error = '';
$form_is_submitted = false;
$errors_detected = false;
$clean = array();
$errors = array();
if (isset($_POST['submit'])) {
$form_is_submitted = true;
if (ctype_alnum ($_POST['fullname'])) {
$clean['fullname'] = $_POST['fullname'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your Full Name!';
}
if (ctype_alnum ($_POST['email'])) {
$clean['email'] = $_POST['email'];
} else {
$errors_detected = true;
$errors[] = 'You have enter an invalid e-mail address. Please, try again!';
}
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
}
if ($form_is_submitted === true
&& $errors_detected === false) {
$fp = fopen('filewriting.txt', 'w');
fwrite($fp, print_r($clean, TRUE));
fclose($fp);
} else {
echo $errors;
}
There are a few things wrong with your code.
There is a missing brace for
if (isset($_POST['submit'])) {$form_is_submitted = true;
so it needs to read as
if (isset($_POST['submit'])) {
$form_is_submitted = true;
}
You are using ctype_alnum so when it comes to an email address, the # and the dot do not count as alpha-numerical characters a-z A-Z 0-9; either remove it if(ctype_alnum ($_POST['email'])) which proved to be successful in testing this.
You can also use another function such as FILTER_VALIDATE_EMAIL
I quote from the PHP manual:
Return Values
Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
This block has a misplaced brace
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
}
Which should read as
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
} // was missing
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
// } // was misplaced - commented out to show you
otherwise it would not have written the password (as part of the array) to file.
Plus this $error = ''; should "probably" read as $errors = ''; but that didn't stop it from writing the data to file.
As for the Array message, remove the square brackets [] from all instances of $errors[]
I think
fwrite($fp, print_r($clean, TRUE));
should be
fwrite($fp, $clean, TRUE);
or
file_put_contents($fp, $clean);
Related
For email validation, the condition for checking email exist or not is failed to function and I still able to register using same email. This is code for email validation
if ( !filter_var($bemail,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
**// check email exist or not**
$result = oci_parse($connection,"SELECT BUSER_EMAIL FROM
POHSENG.BRONTE_USER WHERE BUSER_EMAIL= $bemail");
$count = oci_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
This is overall php code. I tried a lot of way to modify but it is not work at all, while in mysqli it is working.
<?php
require 'oci_connect_hugo.php';
$error = false;
$count="";
$bname="";
$bemail="";
$baddress="";
$bpass="";
$nameError = "";
$emailError ="";
$addError ="";
$passError = "";
if ( isset($_POST['signup']) ) {
// clean user inputs to prevent sql injections
$bname = trim($_POST['bname']);
$bname = strip_tags($bname);
$bname = htmlspecialchars($bname);
$bemail = trim($_POST['bemail']);
$bemail = strip_tags($bemail);
$bemail = htmlspecialchars($bemail);
$baddress =trim($_POST['baddress']);
$baddress = strip_tags($baddress);
$baddress = htmlspecialchars($baddress);
$bpass = trim($_POST['bpass']);
$bpass = strip_tags($bpass);
$bpass = htmlspecialchars($bpass);
// basic name validation
if (empty($bname)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($bname) < 3) {
$error = true;
$nameError = "Name must have at least 3 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$bname)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}
//basic email validation
if ( !filter_var($bemail,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
**// check email exist or not**
$result = oci_parse($connection,"SELECT BUSER_EMAIL FROM
POHSENG.BRONTE_USER WHERE BUSER_EMAIL= $bemail");
$count = oci_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
if (empty($baddress)) {
$error = true;
$addError = "Please enter your address.";
}
// password validation
if (empty($bpass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($bpass) < 6) {
$error = true;
$passError = "Password must have at least 6 characters.";
}
// password encrypt using SHA256();
$bpass = hash('sha256', $bpass);
// if there's no error, continue to signup
if( !$error ) {
$res = oci_parse($connection,"insert into
POHSENG.BRONTE_USER(BUSER_NAME, BUSER_EMAIL, BUSER_ADDRESS,
BUSER_PASSWORD) VALUES('$bname','$bemail','$baddress','$bpass')");
oci_execute($res);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($bname);
unset($bemail);
unset($bpass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
I have made a Log in and Sign up system and on my localhost it worked properly but when i hosted it and created account it says Incorrect credentials. I will send a code if it is needed. And i have crated a MySql db.
Site link: http://metallicafanpage.esy.es
I am using Hostinger
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: home.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($email)){
$error = true;
$emailError = "Please enter your email address.";
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: home.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
Here is Register.php
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// basic name validation
if (empty($name)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($name) < 3) {
$error = true;
$nameError = "Name must have atleat 3 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
// check email exist or not
$query = "SELECT userEmail FROM users WHERE userEmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = hash('sha256', $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
This Is Because Of Your Php Mysql version Your Hosting Server Is Just Using An Old Php Or Mysql Version
How can I put my validation codes into a function? How am I going to return it and call it? I am trying to call put them in just one code and then call them in a function for my forms. Any idea?
Here's my codes:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
$errors[] = "email cannot be blank";
}
if(empty($_POST['first_name']))
{
$errors[] = "First Name cannot be blank";
}
if(empty($_POST['last_name']))
{
$errors[] = "Last Name cannot be blank";
}
if(empty($_POST['password']))
{
$errors[] = "Password cannot be blank";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
$errors[] = "Birth Date cannot be blank";
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = $errors;
//redirect your user back using header('location: ')
header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
//redirect your user to the next part of the site!
}
}
So when I call this this wont work:
echo validate();
Hope you can help. Thanks!
So you're saying something like:
class Validation {
public static function emailFilter($input) {
global $_POST;
return empty($_POST['email']) AND filter_var($input,
FILTER_VALIDATE_EMAIL) != false ? "email cannot be blank" : false;
}
}
Or are you looking to do something else?
EDIT 1
Okay, how about:
function filter ($input, $type) {
if (!$input OR !$type) {
switch ($type) {
case "email":
// Check email
if (empty($_POST['email']) AND filter_var($input, FILTER_VALIDATE_EMAIL)) {
return "email cannot be blank";
}
break;
case "first_name":
if(empty($_POST['first_name']))
{
return "First Name cannot be blank";
}
break;
// And so on.
}
}
}
You could call it then by:
filter($_POST['email'], 'email');
So then:
if (!filter($_POST['email'], 'email')) {
// The email checks out.
} else {
$error[] = filter($_POST['email'], 'email');
}
There are will be more elegant solutions available, but this is based on what I think you want.
Let's say that the user clicks the button after filling-up the required fields, in your $_POST['submit'] or whatever name of your button, just add your codes, and print the error beside the html textbox by adding or if you want, just print $error below the textboxes of your html registration page. And if the errors return zero value, then you can add everything in the database then redirect to your desired page in the else block of your error checking codes.
I would do this like so:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
array_push($errors, "Email cannot be blank");
}
if(empty($_POST['first_name']))
{
array_push($errors, "First Name cannot be blank");
}
if(empty($_POST['last_name']))
{
array_push($errors, "Last Name cannot be blank");
}
if(empty($_POST['password']))
{
array_push($errors, "Password cannot be blank");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
array_push($errors, "Birth Date cannot be blank");
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = implode("|", $errors);
//redirect your user back using header('location: ')
return 0;
/*
Can't use both return & redirect, but return is more flexible.
*/
//header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
return array("email" => $email, "first_name" => $first_name,
"last_name" => $last_name, "password" => $password,
"birth_date" => $birth_date);
// so now you have your results in an associative array.
// you can use print_r(validate()); to see the results, or use
// $r = validate(); if ($r != false) { /*go places!*/}
//redirect your user to the next part of the site!
}
}
I have this PHP code which should return only either true or false after running multiple stored functions, but unfortunately it does not work as expected.
I firstly check the email validation and return true if valid and false if invalid, then i am doing the same for username.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
I need to return only False or True after checking both.
I know that it is very small trick but i could not get it.
Try this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
} else { $valid=false; } //and between the last $valid value
}
or again this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else {
$valid=false; return} //exit from the function if valid is false
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
if(checkmail($_POST['email']) && checkuser($_POST['username'],5,10)) {
$_SESSION['v_mail'] = $_POST['email'];
$_SESSION['v_username'] = $_POST['username'];
$valid = true;
} else {
$valid = false;
}
Sorry was tired missed part of the code, however I would approach this problem little bit differently:
$isMail = (checkmail($_POST['email'])) ? $_SESSION['v_mail'] = $_POST['email'] : false;
$isUser = (checkuser($_POST['username'],5,10)) ? $_SESSION['v_username'] = $_POST['username'] : false;
$valid = $isMail && $isUser;
Or move $_SESSION variables to checkmail, checkuser functions and then simply $valid = checkmail($_POST['email']) && checkuser($_POST['username'],5,10)
I have a form in a file register.php, and it posts to registerPost.php. Inside registerPost.php, I check against a few validation rules, then if any of them are flagged, I return to the first page and print the errors. In theory, that should work. But the validation goes through with no problems, even when I leave everything blank.
Here's the code in question:
$_SESSION["a"] = "";
$_SESSION["b"] = "";
$_SESSION["c"] = "";
$_SESSION["d"] = "";
$_SESSION["e"] = "";
$_SESSION["f"] = "";
$_SESSION["g"] = "";
if(empty($userEmail))
{
$_SESSION["a"] = "You must enter your email.";
}
if(!validEmail($userEmail))
{
$_SESSION["a"] = "Improper Email Format";
}
if(empty($password))
{
$_SESSION["b"] = "You must enter a password.";
}
if(strlen($password) < 5 || strlen($password) > 0)
{
$_SESSION["b"] = "Password must be at least 5 characters.";
}
if($password != $confPassword)
{
$_SESSION["c"] = "Passwords do not match";
}
if(empty($firstName))
{
$_SESSION["d"] = "First Name Required";
}
if(empty($lastName))
{
$_SESSION["e"] = "Last Name Required";
}
if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '$email'")) > 0)
{
$_SESSION["f"] = "This email address already exists in our database.";
}
if(!empty($_SESSION["a"]) || !empty($_SESSION["b"]) || !empty($_SESSION["c"]) || !empty($_SESSION["d"]) || !empty($_SESSION["e"]) || !empty($_SESSION["f"]))
{
header('Location: register.php');
}
Perhaps there is a more straightforward way to do this?
I like this way of registering all errors:
$errors = array();
if (empty($foo1))
$errors[] = "foo1 can't be left blank!";
else if (!preg_match(' ... ', $foo1))
$errors[] = "foo1 was not filled out correctly!";
if (empty($foo2))
$errors[] = "foo2 can't be left blank!";
// ...
if (empty($errors)) {
// do what you need
} else {
// notify the user of the problems detected
}
Do you really need to change the page by header?
I tried your code and it works for me.
Guessing from $username,$email and so on, I think you're doing some sanitizing on the $_POST data. If so, you should dump the $username, etc. to see, if that procedure is putting something in these variables.
Anyway, I like this way of validation better:
$errors = array();
if(empty($username))
{
$errors['username'] = 'Username cannot be empty!';
}
...
$_SESSION['errors'] = $errors;
if(count($errors) > 0) //Redirect...