Gimli
Gimli

Reputation: 29

How can i put this in a for loop?

I want to clean this up and put it in a for loop, 'couse i have more countries, but not much success... Can someone help?

if (strpos($_SERVER['REQUEST_URI'], "hr") !== false){
include '/var/www/sites/footer/zohomerce/include/rabaho/tos/hr.php';

}
else if (strpos($_SERVER['REQUEST_URI'], "hu") !== false){
include '/var/www/sites/footer/zohomerce/include/rabaho/tos/hu.php';

}

else if (strpos($_SERVER['REQUEST_URI'], "it") !== false){
include '/var/www/sites/footer/zohomerce/include/rabaho/tos/it.php';

}

else if (strpos($_SERVER['REQUEST_URI'], "ro") !== false){
include '/var/www/sites/footer/zohomerce/include/rabaho/tos/ro.php';

}

Upvotes: 0

Views: 65

Answers (2)

Eriks Klotins
Eriks Klotins

Reputation: 4180

The author's idea of checking only the presence of value is flawed. What if the URL contains the value but with different semantics?

I would suggest looking both at position and language.

// Explode the url into parts
$urlParts = explode('/',$_SERVER['REQUEST_URI']);

// allowed values
$array = ['hu', 'it', 'ro', 'hr'];

// here I assume that language will always be in the 1st position
// e.g. yoursite.com/hu/whatever
//      yoursite.com/it
// if value is not provided, use hu
$countryStr = isset($urlParts[1]) ? $urlParts[1] : 'hu';

// Checking if value is within allowed values to prevent nasty stuff
if ($countryStr, $array) 
{
    include '/var/www/sites/footer/zohomerce/include/rabaho/tos/' . $countryStr . '.php';
}

There is also the $_GET[] array if you are passing the value as URL parameter

Upvotes: 0

Banzay
Banzay

Reputation: 9470

You can create an array with country codes and loop through it to find match

$array = array('hu', 'it', 'ro', 'hr');

foreach( $array as $country ) {
    if ( strpos($_SERVER['REQUEST_URI'], $country ) !== false ){
       include '/var/www/sites/footer/zohomerce/include/rabaho/tos/' . $country . '.php';
       break;
    }
}

If URI is http://homesite.com, it will contain 'it' and will force false search result. So if URI is like http://homesite.com/it/page.php, you need to search /it/ instead of it

Upvotes: 1

Related Questions