I am building an application and I have constant called ENVIRONMENT_SETTING. As I am currently developing the application I have it as define('ENVIRONMENT_SETTING', 'dev');
Then I am checking at the top of the file what it is. I am currently doing if statements like so:
if (defined('ENVIRONMENT_SETTING'))
{
if (ENVIRONMENT_SETTING == 'dev')
{
error_reporting(E_ALL);
}
elseif (ENVIRONMENT_SETTING == 'test' || ENVIRONMENT_SETTING == 'prod')
{
error_reporting(0);
}
}
else
{
die('Environment setting not set.');
}
This to me though seems like a bit too much code for such a simple check. Is there a better way to do this?
Well I personally would use a switch statement. It's much more concise. In your case I would do the following:
defined('ENVIRONMENT_SETTING') ? NULL : define('ENVIRONMENT_SETTING', 'dev');
if (defined('ENVIRONMENT_SETTING'))
{
switch (ENVIRONMENT_SETTING)
{
case 'dev':
error_reporting(E_ALL);
break;
case 'test':
case 'prod':
error_reporting(0);
break;
default:
exit('Environment setting not set.');
}
}
If you want to keep your die() part, I consider this form as easier to quickly see in which conditions your script will end / die :
if (defined('ENVIRONMENT_SETTING') || die('Environment setting not set.')) {
if (ENVIRONMENT_SETTING == 'dev')
error_reporting(E_ALL);
elseif (ENVIRONMENT_SETTING == 'test' || ENVIRONMENT_SETTING == 'prod')
error_reporting(0);
}
Related
This question already has answers here:
Switch case with three parameters?
(7 answers)
Closed 8 years ago.
I need to detect different server environments in my site's config file. Up until now I was fine with detecting them using only the server's address.
switch ( $_SERVER['SERVER_ADDR']){
case '127.0.0.1':
// stuff
break;
case '111.222.333.444';
// stuff
break;
}
But I now need to test my environment against both the SERVER_ADDR and SERVER_NAME. I'm no php'er, so I've had a stab at
switch ( $_SERVER['SERVER_ADDR'] && $_SERVER['SERVER_NAME'] ){
case ('127.0.0.1','local'):
// stuff
break;
case ('111.222.333.444','gimmesomefunk.com');
// stuff
break;
}
But it's obviously wrong. Any clues?
If you want to keep using switch, you'll have to combine both to one variable like this:
switch (array($_SERVER['SERVER_ADDR'], $_SERVER['SERVER_NAME'])){
case array('127.0.0.1', 'local'):
// stuff
break;
case array('111.222.333.444', 'gimmesomefunk.com'):
// stuff
break;
}
However, the more normal way would be to use if, elseif:
if ( $_SERVER['SERVER_ADDR'] == '127.0.0.1' && $_SERVER['SERVER_NAME'] == 'local' ) {
// stuff
} elseif ( $_SERVER['SERVER_ADDR'] == '111.222.333.444' && $_SERVER['SERVER_NAME'] == 'gimmesomefunk.com' ) {
// stuff
}
I'm not sure it s the best method but you can concatenate values like this :
switch ( $_SERVER['SERVER_ADDR'].$_SERVER['SERVER_NAME'] ){
case ('127.0.0.1local');
// stuff
break;
case ('111.222.333.444gimmesomefunk.com');
// stuff
break;
}
You can't do this, as what you're actually entering the switch statement with is a boolean (true) because you're saying "is this string truthy, and this string truthy":
var_dump($_SERVER['SERVER_ADDR'] && $_SERVER['SERVER_NAME']) // bool(true)
You could simply do the following by using an if statement instead (you don't have to use $address and $name, but in my opinion it becomes more readable):
$address = $_SERVER['SERVER_ADDR'];
$name = $_SERVER['SERVER_NAME'];
if ($address === '127.0.0.1' && $name === 'local') {
// Stuff
} else if ($address === '111.222.333.444' && $name === 'gimmesomefunc.com') {
// Other stuff
}
I'm trying to make redirect if the user is not signed in.
so it should read like this:
If FName is unset and $page does not equal 'new host' or 'login'
then set header to login and set error message.
All the parts work on their own, but not when I try to assemble them.
Edit, I have it working with a switch now but I'm still intrigued on why this if didn't work.
The || means true if either condition is true.
The and checks to see if the leading and following conditions are true.
Should I be using && or does that make a difference?
Here is my code:
if ( !isset($_SESSION['FName']) and
( $page == '/e-Party/Login/Login.php' || $page == '/e-Party/NewHost/NewHost.php')){
echo "not logged in";
$_SESSION['Error'] =
"you must login to use our site,<br>. Or create a account if you don't have one";
header( 'Location: /e-Party/Login/Login.php' );
exit();
}
Edit, here is my working switch.
if ( !isset($_SESSION['FName']))
switch ($page) {
case '/e-Party/NewHost/NewHost.php':
break;
case '/e-Party/Login/Login.php':
break;
default:
$_SESSION['Error'] =
"you must login to use our site,<br>. Or creat a account if you dont have one";
header('Location: /e-Party/Login/Login.php');
exit();
}
A comment helps much more than a down vote, thank you for reading.
Your if and switch are not equivalent: the switch version would be equivalent to
if (!isset($_SESSION['FName']) && $page != '/e-Party/Login/Login.php' && $page != '/e-Party/NewHost/NewHost.php') {
...
}
I changed the if to a switch and it works perfectly as I intended.
if ( !isset($_SESSION['FName']))
switch ($page) {
case '/e-Party/NewHost/NewHost.php':
break;
case '/e-Party/Login/Login.php':
break;
default:
$_SESSION['Error'] =
"you must login to use our site,<br>. Or creat a account if you dont have one";
header('Location: /e-Party/Login/Login.php');
exit();
}
You wrote
If FName is unset and $page does not equal 'new host' or 'login' ...
But you wrote (in PHP)
if !isset($_SESSION['FName']) and
($page == '/e-Party/Login/Login.php' || $page == '/e-Party/NewHost/NewHost.php')
That is, page equals A or page equals B. To make PHP match English:
if !isset($_SESSION['FName']) and
($page != '/e-Party/Login/Login.php' || $page != '/e-Party/NewHost/NewHost.php')
which is flawed. It is equivalent to
if !isset($_SESSION['FName'])
EDIT: Very simple, figure it out. Just put an else{} without a } before and that will work for both ifs.
Well I wrote this code and it works ok
if($_REQUEST['pag']){
// Variável da página
$pag = $_REQUEST['pag'];
// Possíveis páginas
if($pag == "registrar"){
include "inc/register.php";
}
if ($pag == "recuperar"){
include "inc/recover.php";
}
}
But what if the user types ?pag=ofksaofkoasdkfkopsd ?
The page won't exist, so I want to include a file if that happens.
Is there a way to make this without using a list or something?
you can do this by switch and that would be better way then if because
The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. (manual )
switch($_REQUEST['pag']){
case "registrar":
include "inc/register.php";
break;
case :"recuperar":
include "inc/recover.php";
break;
default:
//default you want to include
break;
}
i hope you know about the complexity of the code and in your case switch case has less complexity in worst/average case
Try with if with else like
$pag = $_REQUEST['pag'];
// Possíveis páginas
if($pag == "registrar"){
include "inc/register.php";
}
elseif ($pag == "recuperar"){
include "inc/recover.php";
}
else{
include "inc/default.php"
}
Or you can use switch case where you can found default option like
switch($pag)
{
case "register":include "inc/register.php";
break;
case "recuperar":include "inc/recover.php";
break;
default : include "inc/default.php";
}
use if {} else{} or switch case.
You can use nested if else though.
At least give an eye on the docs - http://php.net/manual/en/control-structures.elseif.php
Why don't you want to use an array? That really would be the best way to go IMHO. Adding pages is easier, you get less duplicated code... It would also be trivial to load the array from a config file or DB instead of having it hard-coded in a later stadium. I see only benefits.
$pages = array( "registrar" => "inc/register.php",
"recuperar" => "inc/recover.php" );
$requestedPage = $_REQUEST["pag"];
if(array_key_exists($requestedPage, $pages)){
include $pages[$requestedPage];
}
else {
include "inc/error404.php";
}
some Use the switch command.
switch ($_REQUEST['pag']) {
case 'registrar':
echo "some text or action";
break;
case 'xxx':
echo "some text or action";
break;
case 'xxxx':
echo "some text";
break;
default:
echo "some text";
}
$pag = isset($_REQUEST['pag']) ? $_REQUEST['pag'] : null;
switch($pag) {
case 'registrar':
require 'inc/register.php';
break;
case 'recuperar':
require "inc/recover.php";
break;
default:
// Include your default page
}
In a non-dynamic language like C++ you'll have to use
if() elseif() else to compare non-constant values.
if ($condition1)
{
//code
}
elseif ($condition2)
{
//code
}
elseif ($condition3)
{
//code
}
...
else
{
//this is what happens when no other condition is true
}
switch is a better practice. check #user1752647's answer
Try with the elseif and else
if($pag == "registrar"){
include "inc/register.php";
}elseif($pag == "recuperar"){
include "inc/recover.php";
}else{
... //include a file if the page doesn't exist
}
Or you can do it with a switch
switch($pag){
case "registrar":
include "inc/register.php";
break;
case "recuperar":
include "inc/recover.php";
break;
default:
... //include a file if the page doesn't exist
}
Hope it will help you.
You also can use this code
$pages = array("register", "recover");
if (in_array($_REQUEST["pag"], $pages)) {
include $_REQUEST["pag"].".php";
}
else{
include "default.php";
}
I have the following code:
<?php
echo $_SERVER['HTTP_HOST'];
// CONFIGURATION ITEMS
$captcha_private_key = '';
$captcha_public_key = '';
switch ($_SERVER['HTTP_HOST']) {
case 'earth-neighbours.com' || 'www.earth-neighbours.com':
$captcha_private_key = '6Lcb_t4SAAAAALkdH4njSny2HYbrmGKS_G84kM_d';
$captcha_public_key = '6Lcb_t4SAAAAAPEtqJEcWXuo0zmRD5PxYkXx84R4';
echo 'live';
break;
case 'earth-neighbours.projects.mi24.net':
$captcha_private_key = '6Lca_t4SAAAAAJb5L4sA7fEHxDFA0Jl8jFw-h3hE';
$captcha_public_key = '6Lca_t4SAAAAAFd-Q2k8esFa9U8nQ2rirEZHFtAH';
break;
case 'earth-neighbours.local':
$captcha_private_key = '6LcZ_t4SAAAAAGc1_S9ahxo-Vg-e7QgHg4yAWBVU';
$captcha_public_key = '6LcZ_t4SAAAAAPHQDb_f-g4mS6mpmc0heustHQ60&hl';
echo 'local';
break;
}
?>
It's running on the local server (earth-neighbours.local) so should output 'local'. Instead it outputs 'live'. The echo at the top however (echo $_SERVER['HTTP_HOST'];) returns the url earth-neighbours.local so it should be 'local' that is echoed. This has me stumped. I had it working before and now I've shifted it to the top of the page and it doesn't work. Weird! Anyone?
PHP does not do switch case or statements like other programming languages.
When you write the following:
switch ($test) {
case 1 || 2:
$blah();
break;
}
This is what actually happens:
switch ($test) {
if (true == $test) {
}
}
The reason this happens is because the case content actually gets evaluated, and in PHP, 1 || 2 === true. PHP then does a typecast on $test to boolean, and $test, unless empty, comes out true.
The PHP "correct" syntax is:
switch ($test) {
case 1:
case 2:
$blah();
break;
In PHP (and a few other languages, actually), once the interpreter gets in the switch, the only way it will come out is by break. Not breaking at the end of a case tells it to continue.
Use:
case 'earth-neighbours.com':
case 'www.earth-neighbours.com':
instead of:
case 'earth-neighbours.com' || 'www.earth-neighbours.com':
As that is an incorrect syntax for the switch statement
Here is my code...
if($_SERVER['REQUEST_URI'] == '/shop/category/handheld-thermal-imaging/')
{
echo
'<div class="current-mark"></div><div class="top-level">HANDHELD<br />THERMAL IMAGING</div>';
}
else if($_SERVER['REQUEST_URI'] == '/shop/category/mobile-imaging/')
{
echo
'<div class="current-mark"></div><div class="top-level">MOBILE IMAGING</div>';
}
Basically this code displays a different left side site navigation depending on which page you're on in the site. It detects what page you're on by the URL of the page by using the PHP REQUEST_URI feature.
My question is this, how can I make the code detect multiple URLs for the same navigation piece?
I tried this code...
if($_SERVER['REQUEST_URI'] == '/shop/category/handheld-thermal-imaging/' , '/shop/iphone-thermal-imaging-adapter/')
{
But that code doesn't seem to work. Basically all I'm trying to figure out here is how I can use multiple URLs for the REQUEST_URI 'if' statement. Thanks in advance!
Put the URLs in an array and then...
if(in_array($_SERVER['REQUEST_URI'],$array))
You should... switch to a switch statement, which is both neater and offers this option:
switch($_SERVER['REQUEST_URI']) {
case '/shop/category/handheld-thermal-imaging/':
// THERE IS NO CODE AT ALL HERE!
// The absence of a "break;" causes control to "fall through" to the next
case '/shop/iphone-thermal-imaging-adapter/':
echo "something common for the thermal imaging urls";
break;
case 'some other url':
echo "something for the url that stands alone";
break;
}
You can use an "OR" statement in your conditional:
if($_SERVER['REQUEST_URI'] == "whatever" || $_SERVER['REQUEST_URI'] == 'something else")
{
}
I used the OR statement for multiple URL checking
<?php
if ((strpos($_SERVER['REQUEST_URI'], 'contact.php') || strpos($_SERVER['REQUEST_URI'], 'register.php') || strpos($_SERVER['REQUEST_URI'], 'login.php')) === false) {
echo "show";
} else {
echo "hide";
}
?>