how to compare array for single result using if statement - php

i was doing validation for user form after each validation i used to store "valid" in a array index and at last comparing them like this:
if(isset($fullname)){
if ($valid["name"]=="valid"&&$valid["username"]=="valid"&&$valid["password"]=="valid"&&$valid["email"]=="valid") {
session_start();
$_SESSION["reg_name"] = $fullname1;
$_SESSION["reg_username"] = $username1;
$_SESSION["reg_email"] = $email1;
$_SESSION["reg_password"] = $password1;
$_SESSION["reg_gender"] = $_REQUEST['gender'];
header("location:validation&insertion.php");
}
Well i will check validation and then make session .
My question is there any short way to check the whole array across a single value like "valid"?
I hope you have understand my question.Comment it if it is not asked well.
Do not rate as negative.Please ignore my grammar mistakes.I hate those who edit my question's grammar.

You can just count the number of unique values and check if it's equal to 1, then check one value if it is "valid".
if (count(array_unique($valid)) === 1 && $valid["name"] === "valid") {
session_start();
$_SESSION["reg_name"] = $fullname1;
$_SESSION["reg_username"] = $username1;
$_SESSION["reg_email"] = $email1;
$_SESSION["reg_password"] = $password1;
$_SESSION["reg_gender"] = $_REQUEST['gender'];
header("location:validation&insertion.php");
}
Or just simply check if a "notvalid" value is found in the array:
if (!in_array("notvalid", $valid)) {
session_start();
$_SESSION["reg_name"] = $fullname1;
$_SESSION["reg_username"] = $username1;
$_SESSION["reg_email"] = $email1;
$_SESSION["reg_password"] = $password1;
$_SESSION["reg_gender"] = $_REQUEST['gender'];
header("location:validation&insertion.php");
}

Related

avoid repeating variable due to undefined variable error

I'm trying to make a profile completion progress, which shows the percentage of how much a user has completed his profile settings. If a user has filled in a field, he receives +15 or +5, however, if the field is not filled in he receives +0.
the code I did is really bad, with variable repetitions, I wanted to know if you knew a cleaner way to do this.
if (!empty($user->avatar)) {
$avatar = 15;
} else { $avatar = 0; }
if (!empty($user->copertina)) {
$copertina = 15;
} else { $copertina = 0; }
// dati personali
if (!empty($user->name)) {
$name= 5;
} else { $name = 0; }
if (!empty($user->last_name)) {
$last_name = 5;
} else { $last_name = 0; }
[...]
if (!empty($user->biografia)) {
$biografia = 5;
} else { $biografia = 0; }
$personal = $avatar+$copertina+$name+$last_name+$sesso+$nascita;
$gaming = $steam+$battlenet+$xbox+$playstation+$switch+$uplay+$origin+$ds;
$social = $twitter+$facebook+$biografia;
$punti = $personal+$gaming+$social;
how do I remove all the others {$ variable = 0}?
You can't really, since you want the value to be a number, and not "undefined". You could initialize your variables to 0 like in this answer stackoverflow.com/questions/9651793/….
If you want to get into type comparisons for null variables, check php.net/types.comparisons. I would just initialize the variables to 0 and remove all the else.
OR...
modify your $user object to have all these variables in an array ($key:$value). You can then initialize the array to 0 all over, and modify it. Adding a new profile value would be easy, and adding array values is quick.
This snippet :
if (!empty($user->avatar)) {
$avatar = 15;
}
else {
$avatar = 0;
}
is semantically equivalent to :
$avatar = (bool)$user->avatar * 15;
Explanation:
Non-empty field gets converted to true and empty string or null gets converted to false
Because we do multiplication php true/false values gets converted to 1/0
So after multiplication you get 15 * 1 or 15 * 0 - depending if your field was used or not.

Do the same - just with less code

I've been trying to work my way to it simply must check it with all inputs in the present that I might have 100 lines so got it done less to just check it all together for an error or what?
What I think about that: instead of taking 14 lines of code that make it less but may be the same,
if($_POST["email"] == "")
{
$error = 1;
}
if($_POST["pass1"] == "")
{
$error = 1;
}
if($_POST["pass2"] == "")
{
$error = 1;
}
if($_POST["fornavn"] == "")
{
$error = 1;
}
if($_POST["efternavn"] == "")
{
$error = 1;
}
if($_FILES["file"] == "")
{
$error = 1;
}
Just create an array of field names and loop over them...
foreach(array('email','pass1','pass2',...) as $field) {
if(empty($_POST[$field])) {
$error = 1;
}
}
$_FILES you will have to handle separately. You can create another loop if you want. The structure of $_FILES is different though; I think you should be checking the "error" field. Check the docs.
Another way to approach this, considering the fact that you don't seem to be performing different tests for each field, or responding with specific error messages, is to use array_diff_key:
$names = array('email', 'pass1', 'pass2', 'fornavn', 'efternavn', 'file');
$names = array_keys($names); // convert $names to keys
$posts = array_filter($_POST); // filter out any falsy values
$fails = array_diff_key($names, $posts); // check for the differences
$error = $fail ? 1 : 0;
If you then wish to respond with specific messages depending on what is missing, you already have a list of the problem parameters in $fails. If you wish to extend the above to take into account specific value checks, you could write your own array filter callback function and pass it's name as the second parameter to array_filter... however this wont allow you to choose a different filter response based on array key, only on array value. All because rather annoyingly array_filter doesn't receive a key value when filtering an array.

how can i handle a checkbox value being sent from the form to the php

Trying to understand how to handle the values sent from a checkbox. Got the form on one page which accepts a name value email etc then also a "mailingList" checkbox value but im struggling to handle the set and unset values. The following code is the $_POST method from the form page.
if (isset($_POST['register'])) {
$email = trim($_POST['email']);
$password = trim($_POST['pwd']);
$retyped = trim($_POST['conf_pwd']);
$firstname = trim($_POST['fname']);
$lastname = trim($_POST['lname']);
$company = trim($_POST['company']);
$mailingList = $_POST['mailingListCheckbox'];
require_once('./includes/register_user_pdo.inc.php');
}
I currently have this if statement to try and set the value of "mailingListValue" to try and handle it correctly but it doesn't seem to work.
if (!isset($mailingList)) {
$mailingListValue = 0;
}
else {
$mailingListValue = 1;
}
Any tips on the if statement or what im doing wrong would be much appreciated!Thanks for any help!
edit: form
<input name="mailingListCheckbox" type="checkbox" id="mailingListCheckbox" value="1" checked="checked">
<label for="mailingListCheckbox">Yes, I would like to receive alerts and updates from the MSF</label>
Edit your PHP code
if ($mailingList == 1) {
$mailingListValue = 1;
}
else {
$mailingListValue = 0;
}
If your checkbox is checked, the $mailingList value will be "1"
Just do everything in one:
$mailingListValue = isset($_POST['mailingListCheckbox']) ? 1 : 0;
Use #Sean 's method above (in the question comments) and do the test in when set $mailingList or test if a real condition is set to $mailingList i.e...
if($mailingList == 1) {
//do something
} else {
// dont do something
}

String comparison regardless of case

I'm trying to find different variations of "Username" or "Password" , as shown below, in an case-insensitive manner:
$unVar1 = "username";
$unVar2 = "user name";
$usernameVariations1 = strcasecmp($unVar1, $unVar2);
$unVar3 = "User";
$unVar4 = "id";
$usernameVariations2 = strcasecmp($unVar3, $unVar4);
$pwVar1 = "password";
$pwVar2 = "pass";
$passwordVariations1 = strcasecmp($pwVar1, $pwVar2);
if ($element->value === $usernameVariations1
|| $element->value === $usernameVariations2
|| $element->value === $passwordVariations1) {
echo "Weee!";
}
else {
echo "boo!";
}
The problem is it outputs "boo" for each element in the foreach() output. What am I doing wrong? Is it possible to put all of these values in an array? Thanks.
You're making this more complicated then it needs to be. If your usernames and passwords not case sensitive, just make them lowercase when you compare them:
if (strtolower($username) === strtolower($element->value))
{
// ok
}
Now if you're allowing spaces to be added to the middle, and abbreviations, then you can try plan B:
$valid_usernames = array('Username', 'username', 'user name', 'UsE Nam');
if (in_array($element->value, $valid_usernames))
{
// ok
}
Keep in mind that you are now responsible for keeping $valid_usernames complete.

Which checkbox is selected and assigning a value

I am trying to create logic to see what checkbox is selected (of 5 possible checkboxes) and if it is selected assign it a value of 0. if it is not selected I was to assign it a value of 1. The proceeding code snippet highlight this but throws a parse error in my else statement and I cannot fighure out why.
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = 'unchecked';
$chkBox2 = 'unchecked';
$chkBox3 = 'unchecked';
$chkBox4 = 'unchecked';
$chkBox5 = 'unchecked';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
else{
$chkBox1 = '1';
}
}//End of chkBox1Selected logic
You don't understand how checkboxes work. If a checkbox is deselected before posting, it will not be set on post.
Therefore, the only condition that will ever be present in your code is that every value will show as 1, since they cannot be overridden.
Take this snippet and try it out. It dynamically loops for the amount of variables you need and assigns the values based upon the submitted value.
$_POST['chkBox4'] = 'test';
for( $i = 1; $i <= 5; $i++ )
{
$name = 'chkBox' . $i;
$$name = !isset( $_POST[$name] ) ? 0 : $_POST[$name];
}
print $chkBox2 . ' // '. $chkBox4;
http://codepad.org/51RotnCf
Ok I got it to work from a syntax standpoint, however now no matter what is selected it is still assigning a value of 1 to all the checkboxes and not changing the selected checkbox to a value of 0. Here is the new code that is correct from a syntax standpoint but defaults to 1 no matter what:
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = '1';
$chkBox2 = '1';
$chkBox3 = '1';
$chkBox4 = '1';
$chkBox5 = '1';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
}//End of chkBox1Selected logic
if (isset($_POST['chkBox2'])) {
if ($chkBox2 == 'chkBox2Selected') {
$chkBox2 = '0';
}
}//End of chkBox2Selected logic
if (isset($_POST['chkBox3'])) {
if ($chkBox3 == 'chkBox3Selected') {
$chkBox3 = '0';
}
}//End of chkBox3Selected logic
if (isset($_POST['chkBox4'])) {
if ($chkBox4 == 'chkBox4Selected') {
$chkBox4 = '0';
}
}//End of chkBox4Selected logic
if (isset($_POST['chkBox5'])) {
if ($chkBox5 == 'chkBox5Selected') {
$chkBox5 = '0';
}
}//End of chkBox5Selected logic

Categories