Syntax for multiple switch statement to detect server environment [duplicate] - php

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
}

Related

PHP Loose comparison and null on Switch

Today I saw a strange bug on my code.
I have a switch with comparison on case and if my variable equals null or '' it will always comes in the first case.
My code :
$sHost = filter_input(INPUT_SERVER, 'HTTP_HOST');
switch($sHost){
// Local
case strpos($sHost, "dev.localhost") !== false: $this->_sEnv = 'local';
break;
// Prod
default: $this->_sEnv = 'production';
break;
}
On an if statement it's work but on switch case it doesn't work , I don't know why .. Maybe a PHP problems ? Anyone has had a similar bug ?
$sHost can be null because sometimes I run the script with a batch.
if(strpos($sHost, "dev.localhost") !== false){
// Nothing
}
else{
return false;
}
Of course I can do an if is_null before the switch , but I want to understand why it's working like that..
Edit: I forgot to said I have 5 cases on my switch , one case by environment
Thank you for your future answer :)
If $sHost equals to null or '', then the first switch case is always true because
var_dump($sHost == (strpos($sHost, "dev.localhost") !== false));
is true. How switch work.
You can do this:
switch(true) {
// Local
case strpos($sHost, "dev.localhost") !== false:
$this->_sEnv = 'local';
break;
// Prod
default:
$this->_sEnv = 'production';
break;
}
switch(strpos($sHost, "dev.localhost")){
// Local
case -1: $this->_sEnv = 'production';
break;
// Prod
default: $this->_sEnv = 'local';
break;
}
#Leggendario, good point, fixed above.

Better way of checking my application environment setting?

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);
}

PHP - Do an else to many ifs?

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";
}

switch using $_SERVER['HTTP_HOST'] always defaults to first

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

cannot get variable to work [duplicate]

This question already has answers here:
Why is PHP not replacing the variable in string? [closed]
(2 answers)
Closed 8 years ago.
I have this code here:
<?php
$search=htmlspecialchars($_GET['load']);
$method = isset( $_GET['btnAction'] ) ? $_GET['btnAction'] : '';
switch( $method ) {
case 'Search':
header('Location: search.php?load=$search');
break;
case 'Im Feeling Lucky':
//do chapter two stuff
header('Location: search_lucky.php?load=$search');
break;
default:
echo 'Not a valid operation';
}
?>
Everything works except the $search variable, I don't understand what is wrong.
Can someone tell me why $search variable dont work when i hit this url: handler.php?load=keyword&btnAction=Search
The problem is in your header() function.
header('Location: search_lucky.php?load=$search');
should be
header("Location: search_lucky.php?load=$search");
as php treats everything between the (') as literals. so it's literally passing load=$search
Have you tried using an if() statement to do it.. see below..
<?php
$search=htmlspecialchars($_GET['load']);
if(isset($_GET['btnAction']) {
$method = $_GET['btnAction'];
}
switch( $method ) {
case 'Search':
header('Location: search.php?load=$search');
break;
case 'Im Feeling Lucky':
//do chapter two stuff
header('Location: search_lucky.php?load=$search');
break;
default:
echo 'Not a valid operation';
}
?>
EDIT: just noticed the the 'Search' with capitol S. Change to lowercase might work better.
This code is a little bit broken, so take a look at this after it's changed:
<?php
$search=htmlspecialchars($_GET['load']);
$method = isset( $_GET['btnAction'] ) ? $_GET['btnAction'] : '';
switch( $method ) {
case "search":
header("Location: search.php?load=$search");
break;
case "Im Feeling Lucky":
//do chapter two stuff
header("Location: search_lucky.php?load=$search");
break;
default:
echo 'Not a valid operation';
}
?>
The reason is because you were testing $method (which had a value of 'search') to see if it matched 'Search' (with a capital S). Those two cases do not match, which is why you were seeing "Not a valid operation" output.
In PHP, variables are interpreted only in double quotes.
header("Location: search.php?load=$search");
To use single quote you'll need to concatenate the values
header('Location: search.php?load='.$search);

Categories