if (isset($_POST['register'])) {
$email = $_POST['email'];
$username = $_POST['username'];
$pass = $_POST['password'];
$rep_pass = $_POST['rep-password'];
$firstname = $_POST['firstname'];
$surname = $_POST['surename'];
$phonenr = $_POST['phone-nr'];
$place = $_POST['place'];
}
if ($email != "" && $username != "" && $pass != "" && $rep_pass != "" && $firstname != "" && $surname != "" && $phonenr != "" && $place != "") {
}
Is there a shorter way to do the same as what I'm doing in the condition of the second if statement?
$required = ['email', 'username', 'password', ...];
foreach($required as $field)
if(empty($_POST[$field]))
throw new EpicFailureException("Mandatory field '$field' is empty");
You could use a preset accepted postvars thing.
You can add custom error messages during validation and such, and my code auto instantiates your variables. Only thing is I don't account for the dashes, but you could consider removing those from your form name's.
$accepted = array('register','email','username','password','rep-password','firstname','surename','phone-nr','place');
$_POST = array('register'=>'blah','email'=>'blah','username'=>'blah','password'=>'blah','rep-password'=>'blah','firstname'=>'blah','surename'=>'blah','phone-nr'=>'blah','place'=>'blah');
$proper = true;
$erroron = "";
foreach($accepted as $val) {
if(isset($_POST[$val])) {
trim($_POST[$val]);
if(!empty($_POST[$val])) {
$$val = $_POST[$val];
}
else {
$proper=false;
$erroron = "Error occured on $val which is empty";
break;
}
}
else {
$proper = false;
$erroron = "Error occured on $val which is not defined";
break;
}
}
if($proper) {
echo "email = $email, you might want to consider removing dashes from form names to auto instantiate those variables";
}
else {
echo "Not everything was done properly. The error message is: $erroron";
}
You can put your values into an array and then use the built in function array_filter().
If you don't provide a callback function to array_filter() it will only remove the false or empty value of your array.
Then count the value before and after the modification if they are != a value is missing.
if (isset($_POST['register'])) {
$user['email'] = $_POST['email'];
$user['username'] = $_POST['username'];
$user['pass'] = $_POST['password'];
$user['rep_pass'] = $_POST['rep-password'];
$user['firstname'] = $_POST['firstname'];
$user['surname'] = $_POST['surename'];
$user['phonenr'] = $_POST['phone-nr'];
$user['place'] = $_POST['place'];
}
$nbArg = count($user);
if($nbArg != count(array_filter($user))) {
echo "One Value is missing"
}
Related
I want to change page after validation in PHP but, it appears on the same page with the validation.
Here is the logical process i want
if validation didnt complete/invalid input
display error messages, and user must input again in the same page.
if form is validated complete with no invalid input.
User will be moved to a new page for reviewing the inputed data.
And this is my PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
if($nameErr == "" && $emailErr == "" && $genderErr == "" && $websiteErr == "") {
header('Location: http://subc.chaidar-525.com');
exit();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I use some referance from W3School, and it makes the review of data is in the same page as the form and validation, and i want the user will be transfered to another new page for reviewing their inputed data.
Use a session, roughly like this:
session_start();
if($nameErr == "" && $emailErr == "" && $genderErr == "" && $websiteErr == "") {
$_SESSION['inputdata'] = $_POST;
//A neater version would be to assign all vars, like:
//$_SESSION['gender'] = $gender;
header('Location: http://subc.chaidar-525.com');
exit();
}
on the next page, use this:
session_start();
$input_data = $_SESSION['inputdata'];
There is a PHP update form where a user can update his records. The below-mentioned code looks redundant to me. How can I optimize this PHP code? Also, I have the admins username and email in a different table and the admin detail columns (such as first name, last name, gender, dob) in a different table. What will be the best way to check if username and email both have been updated or if any one of them and update it in the database accordingly.
Below is my source code:
if(isset($_POST['btnClick']) {
$f_name = NULL;
$l_name = NULL;
$username = NULL;
$email = NULL;
$gender = NULL;
$dob = NULL;
$f_name = filter_input(INPUT_POST, "f_name", FILTER_SANITIZE_STRING);
$l_name = filter_input(INPUT_POST, "l_name", FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$gender = filter_input(INPUT_POST, "gender", FILTER_VALIDATE_STRING);
$dob = filter_input(INPUT_POST, "dob", FILTER_VALIDATE_STRING);
try {
if(isset($username) && $username != $_SESSION['username']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "Username changed value inputted";
}
else if(isset($email) && $email != $_SESSION['email']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "email change value inputted";
}
else if(isset($username) && isset($email)) {
/*Update both records */
}
You can do something like this:
<?php
try {
if (isset($username) && $username != $_SESSION['username']) {
$fieldsToUpdate[] = 'username=:username';
$updatedFields[] = 'Username';
}
if (isset($email) && $email != $_SESSION['email']) {
$fieldsToUpdate[] = 'email=:email';
$updatedFields[] = 'Email';
}
if (isset($fieldsToUpdate) && count($fieldsToUpdate) > 0) {
$sqlUpdate = "UPDATE admins SET " . implode($fieldsToUpdate, ', ') . " WHERE admin_id=:admin_id";
/*Update code here...*/
$finalMessage = 'Fields: ' . implode($updatedFields, ', ') . ' have been updated.';
}
}
PS: This is an example code that how can you optimize your code with PHP arrays and implode() function to run single query to update single or multiple fields.
I wanted to build a super-simple login-script with a text-file. Text-file contains
password username name
Between the password, username and name is a tab. I read the file, explode it by tab, and then check the user input against the lines.
But I always get (one) Undefined offset error. I think it is because of the explode function, but I don't know why...
Here's my code:
if(!empty($_POST['login_inputEmail']) || !empty($_POST['login_inputPassword']))
{
$log = 0; //not logged in
$username = $_POST['login_inputEmail'];
$password = $_POST['login_inputPassword'];
$userdatei = fopen ("documents/user.txt","r");
while (!feof($userdatei))
{
$zeile = fgets($userdatei,800);
$userdata = explode("\t", $zeile);
if ($username == $userdata[1] && $password == trim($userdata[0]))
{
$log = 1; //logged in
}
}
fclose($userdatei);
}
Add is_array() and isset() in your code to avoid errors. Refer this
if(!empty($_POST['login_inputEmail']) || !empty($_POST['login_inputPassword']))
{
$log = 0; //not logged in
$username = $_POST['login_inputEmail'];
$password = $_POST['login_inputPassword'];
$userdatei = fopen ("documents/user.txt","r");
while (!feof($userdatei))
{
$zeile = fgets($userdatei,800);
$userdata = explode("\t", $zeile);
if(is_array($userdata))
{
if(isset($userdata[1]) && isset($userdata[0]))
{
if ($username == $userdata[1] && $password == trim($userdata[0]))
{
$log = 1; //logged in
}
}
}
}
fclose($userdatei);
}
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?
I basically took in 3 pieces of data from a form, and before processing them, I just wanted to make sure that all fields were filled in. So the focus of this is the second to last IF statement, checking if the different variables are empty. It seems to only be working for the first variable and I can't figure out how to make it apply to all of them.
<?php
include ("account.php") ;
include ("connect.php") ;
$isdone = FALSE;
$un = $_REQUEST [ "un"] ;
$pw = $_REQUEST [ "pw"] ;
$data = mysql_query("SELECT * FROM `auth` WHERE username = '$un'") or die(mysql_error());
$info = mysql_fetch_array($data);
$info['username'];
$password = $info['pw'];
session_start();
if(trim($un) != '' && trim($pw) != '' && $password == $pw)
{
$_SESSION['uze']=$un;
include "problem.html";
}
elseif( !isset($_POST['submit1']) && $isdone == FALSE)
{
echo "wrong password";
}
$selected = $_REQUEST [ "type"] ;
if($selected == 'afs')
{
$typeinc = 'afs';
}
else if($selected == 'db')
{
$typeinc = 'database';
}
else if($selected == 'cs')
{
$typeinc = 'computer systems';
}
else if($selected == 'pw')
{
$typeinc = 'password';
}
else if($selected == 'hw')
{
$typeinc = 'hardware';
}
else if($selected == 'other')
{
$typeinc = 'other';
}
$text = $_REQUEST ["inc"];
$selected2 = $_REQUEST ["yesno"];
if($selected2 == 'yes')
{
$email = 'yes';
}
else
{
$email = 'no';
}
if(isset($_POST['submit1']))
{
if(empty($typeinc) || empty($text) || empty($email))
{
print( 'You have not filled in all fields, click to sign in and re-enter' );
}
}
else{
mysql_query("INSERT INTO `swp5_proj`. `inci` (`type`, `date`, `time`, `reporter`, `desc`) VALUES ('$typeinc', CURDATE(), CURTIME(), '".$_SESSION['uze']."', '$text');") or die(mysql_error());
mysql_query("DELETE FROM inci WHERE type = ' '");
$isdone = TRUE;
}
if(isset($_POST['submit1']) && $isdone == TRUE)
{
echo "session over";
}
?>
Make sure you clean your REQUEST variables before you put them in a MySQL query.
if((trim($un) !== '') && (trim($pw) !== '') && ($password == $pw))
You're setting $email to yes or no in the line just above.
In your if statement you are using the shortcut OR operator.... As soon as a single statement evaluates to true, the entire statement evaluates to true and there is no need to continue processing further.