Sometimes we have to redirect users based on a specific keyword in the URL. Trust me we can achieve this very easily in PHP. Here you would see the code in this post. Let’s assume the URL contains events.
For example
URL: https://domain.com/events/lucknow
<?php
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' && $_SERVER['REQUEST_SCHEME'] === 'https' )
$url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
else
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'events') !== false)
echo 'events exists in URL.';
else
echo 'No events.';
?>
PHP8 have default function str_contains
Now in PHP8, we can easily find if the URL contains any string in it using PHP parse_url function.
<?php
$url = 'https://domain.com/events/lucknow';
if (str_contains($url, 'events'))
echo 'events exists in URL.';
else
echo 'No events.';
?>
Check If URL Contains Query String with PHP
What if you would like to know a URL contain any query string, that is also easy to find with PHP. There are two ways of doing this.
<?php
$url = "https://domain.com/events/lucknow/?date=22-08-2021";
if (parse_url($url, PHP_URL_QUERY)) {
echo 'URL has query string';
} else {
echo 'no query string in URL';
}
<?php
if(empty($_GET)) {
echo "No query string";
} else {
echo "query string available";
}
php check if url contains domain
A URL can easily be checked to determine if it contains a specific domain. Url must be passed to the preg_match function, and it will return the number of times the url appears in the string.
<?php
$customurl = "https://phppanda.com/";
$availableDOmainCount = preg_match("/(^(https?:\/\/(?:www\.)?|(?:www\.))?|\s(https?:\/\/(?:www\.)?|(?:www\.))?)phppanda\.com/", $customurl);
if($availableDOmainCount){
echo "yes url contains domain";
}else{
echo "phppanda.com not in the url";
}
?>
check how to detect https in php.