Efficient way to check multiple variables declarations? - php

In a project of mine I am working with a sequence of pages that each give information that is used in the next, with POST and session variables. Simple example:
Page 1: enter name -> page 2 display name; ask birth date -> page 3 display name and birth date.
If a user goes directly to page 3 I want to display a message that s/he has not entered a name and/or birth date and should try again. Currently I am still doing it like so. On page 2:
if (isset($_POST['name'])) $_SESSION['name'] = $_POST['name'];
and page 3:
if (isset($_SESSION['name'])) $name = $_SESSION['name'];
if (isset($_POST['bday'])) $_SESSION['bday'] = $_POST['bday'];
as declarations and in the body an if-clause like
if (isset($name) && isset($_SESSION['bday'])) {
// do main stuff
else {
// display error message
}
The example is simple enough, but in the real world my code has a lot more variables and data from the forms, and putting all this first in variable assignments and then in an if-clause is tiring and seems not efficient to me. Is there a better, more straightforward way to check things like this? Or is what I posted the best, most-used way to go?

You can use one call to isset to check several variables.
isset($_SESSION['name'], $_SESSION['bday'], ...)
Or you can write your own function like
if (variablesFilled(['name', 'bday', ...])) { }
function variablesFilled($array) {
foreach ($array as $entry) {
if (!isset($_SESSION[$entry])) {
return false;
}
}
return true;
}

I believe you just need to write some helper methods. One to rewrite $_POST data to $_SESSION, dumb as this:
function copyPostToSession(array $fields) {
foreach($fields as $field) {
if(isset($_POST[$field])) {
$_SESSION[$field] = $_POST[$field];
}
}
}
so instead of if forest, you do:
copyPostToSession(array('name','bday'));
(additionally you can count how many fields were present and return true or false if there's mismatch) and the other (pretty similar) to check if you got all the required data in $_SESSION.

PHP's isset() function is a variadric function.
You can put as many arguments as you want:
isset($a, $b, $c)
...which translates to:
isset($a) && isset($b) && isset($c)
Hope it helped!

Seperate functions tend to differ a bit on a per server case. You could try calculating the time to perform a function a large number of times and compare which is faster.
But, yeah, that looks like fairly fast code there.
Might be worth trying a switch case statement as an alternative perhaps?

Related

WordPress Wedding RSVP using Gravity Forms

I am building my wedding website and want to integrate an RSVP form using Gravity Forms. The issue I am running into is how to set certain guest that have +1's. I would like to show an additional guest entry (First Name, Last Name, Meal Option) when the initial First Name and Last Name has been populated. How would I go about doing this? Any help would be great! Thanks in advance!
Here is how I'd solve this problem:
First, you need to put everything in the DB, the easiest way would be to either do it manually or somehow loop through an array/CSV calling add_option($key, $value) Again, I would recommend a mobile/phone number as they'll be unique so you don't pull the wrong "John Smith". I'll assume you'll keep it basic with $key as the unique identifier and $value as boolean as to whether to show additional info. Interestingly, by default, if not found get_option($key) will return false and therefore not show your additional data, which I would assume you'd want anyway. If you'd rather it return true just pass true as the second argument.
Now for your answer:
Your URL is something like https://somesite.com/rsvp?id=1234.
function allowed_plus_one() {
$id = $_GET["id"];
$allowed = get_option($id);
return $allowed;
}
Then assumedly it'll be something like
if (allowed_plus_one()) {
// show form with plus one
} else {
// show form without
}
EDIT:
Keeping separate incase this has already been viewed.
You should also be checking for the existence of $_GET["id"] and behaving accordingly. eg:
if (isset($_GET["id"] && !empty($_GET["id"]) {
//do logic above
} else {
//here by mistake so don't show any form?
}

PHP - Use a URL Key to get data from a separate file not normally index

I'm not a PHP dev and I have little experience with it. I ask for your forgiveness and assistance.
Here's my problem:
I have a script and I need to be able to append a 'key' (I don't know what else to call it) like:
http://my-web-address.com/packages.php?key=secret
When this key is present, I need to run the code responsible for extracting the data from a .json file in a separate directory. (Normally, the code wouldn't index this directory. It should only indexes it when the key is present in the URL.)
I believe this code to be the foreach section in the link above.
I'm having a hard time explaining this in a way that makes sense, so I guess it's easier to show you what I mean.
I know it should be easy; at first I thought I could simply do it with something like this:
if ($key == "secret") {
$document['packages'][] = getPackageData("secretdirectory/secret.json");
}
But alas, simply appending that didn't make it work.
Any ideas?
As Ron Dadon said, but with a slight modification:
sanitize($value) {
// Sanitize the key - see below
return $value;
}
$key = sanitize($_GET['key']);
if ($key == "secret") {
$document['packages'][] = getPackageData("secretdirectory/secret.json");
}
However you should sanitize that input, as anyone can change the key. Here are some resources on that:
Clean & Safe string in PHP
Remove all special characters from a string
The ultimate clean/secure function
You need to use the GET array:
if ($_GET['key'] == "secret") {
$document['packages'][] = getPackageData("secretdirectory/secret.json");
}

Error-message for failed register, login etc. - Use $GLOBAL oder $_SESSION?

For example:
If anyone fails at the login function (for example: enters wrong password) on my webpage, i want to show an error-message at the webpage. My idea was like that:
if(doLogin()) {
//....
}else {
$GLOBAL['errorLogin'] = "Wrong Userdata";
}
and then echo the global-variable in the .html.
But i searched also for this topic and found only this method, but everyone had used the $_SESSION variable for this instead of $GLOBAL.
Is my variant with the $GLOBAL varible wrong or bad practise?
And why use $_SESSION for a error-message, if i only echo the message one time and don't need it in the next request?
I think you mean $GLOBALS (notice the s) which is a suber global variable and therefore can be accessed from anywhere in the PHP script (also from within functions or methods).
There is nothing wrong about that.
I don't think that you should use the $_SESSION variable for that, because the user needs to see the error message only one time. In your case, and in most cases, that's why it might make no sense to store it in a session.
Personally, I just would use a custom errorMessage-Array, like that:
//store all Error Messages in one array.
$errorMessages = array();
if(doLogin()) {
//....
}else {
$errorMessages["Login"] = "Wrong Userdata";
}
//...
foreach($errorMessages as $key=>$message){
echo $key.": ".$message."<br>";
}

Create a variable in one function and pass it to another in PHP

Let me first say I've spent a day reading three google pages of articles on this subject, as well as studied this page here.
Ok, here's my dilemma. I have two functions. Both called upon via AJAX. This first one assigns a value to the variable and the second one uses that variable. Both functions are triggered by two separate buttons and need to stay that way. The AJAX and the firing off of the functions work fine, but the variable isn't passed. Here is my code:
if( $_REQUEST["subjectLine"] ) //initiate first function
{
$CID = wpCreateChimpCampaign();
echo $CID; //this works
}
if( $_REQUEST["testEmails"] ) //initiate second function
{
echo $CID; //does not return anything but should contain "apple"
wpSendChimpTest($CID);
}
function wpCreateChimpCampaign () //first function
{
$CID = "apple";
return $CID;
}
function wpSendChimpTest ($CID) //second function
{
echo $CID; //does not return anything but should contain "apple"
}
I'm open to using a class but I haven't had much luck there either. I was hoping to solve this issue without using classes. Thanks for the help in advance!
If you are making 2 separate calls to this file, it may be helpful for you to visualise this as being 2 functions in 2 totally separate files. Although they exist in the same PHP file, because they used called in different calls, they don't retain the value of the variable $CID. Once the file has run, the variable is destroyed and when you call the file again, the value is null again.
So you need to store that variable between calls. You can either store it in a database or store it in a session variable.
So call session_start(); at the beginning of the file, then rather than use $CID, just use $_SESSION['CID'];
I'm not sure where the hold up is. The code you have will work:
$CID = wpCreateChimpCampaign(); // returns 'apple'
wpSendChimpTest($CID); // echos 'apple'
The code looks fine, but are you certain that all requirements are being met so both functions execute?
In other words are you supplying values for both $_REQUEST["subjectLine"] and $_REQUEST["testEmails"]?

How can I write this Drupal snippet more efficiently?

I'm working on a patch to submit to the Registration Code module for Drupal. In short, is there a more efficient way to write the code below?
if (module_exists('regcode_voucher')) {
$cnfg = variable_get('regcode_voucher_display', array('regform' => 'regform'));
if (empty($cnfg['regform'])) {
return;
}
}
It seems like I should be able to reduce it to one if statement with && combining two conditions, but I haven't found the syntax or the necessary php array function that would allow me to do that.
In case some context helps, the regcode_voucher sub-module allows users to enter their registration code on the user edit page. On our sites, after a "beta" period, we want to simplify the registration form by removing the registration code field; but we'd like users to still be able to enter the code on their account edit page. The code above is part of a patch that allows the regcode's hook_user changes to be bypassed.
Code looks like good, what efficient do you want? Little changes may be:
if (module_exists('regcode_voucher')) {
$cnfg = variable_get('regcode_voucher_display', null);
if ($cnfg) {
// do your actions
}
}
And I don't recommend to merge if..., code should be clear and simpler to understand. If you merge these for optimizing, you win "tiny" milliseconds for real-live processors, but lost your clean code.
Why are you returning an array from variable_get if the variable is not found? variable_get will always return a string or a serialized array (that needs to be unserialized). If I'm missing something, you can use array_key_exists('regcode', variable_get(...)) to check for the array key.
This should work... note returning "false" from variable_get as a default if the variable is not found, which will cause the if conditions to not match. I personally find this more readable than nested if statements (for 3+ conditions I'd nest, though).
if( module_exists('regcode_voucher') && variable_get('regcode_voucher_display', false) ) {
// stuff
}

Categories