php if url contains | if url contains php | php check if url contains string | php check if url contains | php if url contains echo somehting

Check If URL Contains String with PHP8

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

check how to detect https in php.

Leave a Comment

Your email address will not be published. Required fields are marked *