Any way to shorten this bit of php code? (sorry total noob)

mphp

New member
PHP:
$word1 = "site1.com";
$word2 = "site2.com";
$word3 = "example.com";
$word4 = "bing.com";
$word5 = "google.com";
     // WILL PROBABLY BE MORE SITE HERE

if (!empty($referer) and !strpos($referer, $word1) and !strpos($referer, $word2) and !strpos($referer, $word3) and !strpos($referer, $word4) and !strpos($referer, $word5) and !strpos($referer, $word6)) {

     // DO SOMETHING HERE
}

In the future I will probably have a lot more sites added to this list...
Is this the shortest way to write this??

.
 
Last edited by a moderator:
two possible solutions

Code:
<?php
// Store all domains in an array
$allowed_domains = [
    'site1.com',
    'site2.com',
    'example.com',
    'bing.com',
    'google.com'
    // Add more domains here as needed
];

// Function to check if referer contains any of the allowed domains
function checkReferer($referer, $domains) {
    if (empty($referer)) {
        return false;
    }
 
    foreach ($domains as $domain) {
        if (strpos($referer, $domain) !== false) {
            return false;
        }
    }
 
    return true;
}

// Usage
if (checkReferer($referer, $allowed_domains)) {
    // DO SOMETHING HERE
}



solution 2
Code:
$sites = ["site1.com", "site2.com", "example.com", "bing.com", "google.com"];
// Add more sites here

if (!empty($referer) && !array_filter($sites, fn($site) => strpos($referer, $site) !== false))
{  
// DO SOMETHING HERE
}
}


You can also put your $site in a txt file (one domain per row) or databases (e.g. MySQL) and read them in an array.
 
You can extend the admin's second solution:
PHP:
$allowed_domains = [
    'site1.com',
    'site2.com',
    'example.com',
    'bing.com',
    'google.com'
    // Add more domains here as needed
];

// if you want to block not listed referer
in_array($referer, $allowed_domains) or die('Referer is not trusted');

// or if you just want to execute extra code for listed referer
function executedOnListedReferer() {
    // DO SOMETHING HERE
}
in_array($referer, $allowed_domains) and executedOnListedReferer();
 
Back
Top