Declaring variables on each script or external file?

Usually I declare each of my variables at the top of the page:

$searchID = isset($_REQUEST[‘searchID’]) ? $_REQUEST[‘searchID’] : null;

Is it more efficient to declare all needed files in a separate file, and then reference them using an include statement?

Thank you.

You mean, all the needed variables? The reason you would centralize the request variable sanitization and initialization is simply for saving coding effort by removing (some) duplication. It wouldn’t be more efficient from a server standpoint, but it is also not terribly less efficient. Considering programming time, it is more efficient and worth it.

Scott

I include all scripts that are used on most or all pages.
Good example is a database connection and validation.
If I ever decide to change my database password or validate another value, it is done in one script only.

Using $_REQUEST is considered to be extremely bad practice as it makes injection much easier than if you specify $_GET $_POST or $_COOKIE specifically as specifying which of the three the value is supposed to be coming from eliminates injection via the other two.

1 Like

Lorenw, so you’re saying that you declare all variables for your entire website once in a single script, and then reference it from each PHP page using include, right? Just wanted to clarify.

Thank you Felgall for the tip.

I think he is saying, the things that are used “globally” are generated in one script, which is then included where it is needed.

Scott

Yes, vars and functions used globally I always include.
Things like an image uploader don’t make much sense to include if you only have one upload page.

For instance, if you have an admin section, I just include secure.php at the top of the page.
I takes care of checking if you are logged in and redirects to the login page if not logged in.

It doesn’t hurt to include db_connect.php and then include secure.php (for admin).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.