Check if url contains parameters

Really you should be using the parse_url() function:

<?php
$url = parse_url($_SERVER['REQUEST_URI']);

if(isset($url['query'])){
    //Has query params
}else{
    //Has no query params
}
?> 

Also you should enclose your array based variables in curly brackets or break out of the string:

$url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}?myparameter=5";

or

$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."?myparameter=5";

enable error_reporting(E_ALL); and you will see the error. Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' ect


you can search for the '?' char like this:

if (strpos($_SERVER[REQUEST_URI], '?')) { // returns false if '?' isn't there
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&myparameter=5";
} else {
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?myparameter=5"; 
}

The URL parameters are received from a global variable called $_GET which is in fact an array. So, to know if a URL contains a parameter, you can use isset() function.

if (isset($_GET['yourparametername'])) {
    //The parameter you need is present
}

Afterwards, you can create separate array of such parameter you need to attach to a URL. Like:

if(isset($_GET['param1'])) {
    \\The parameter you need is present
    $attachList['param1'] = $_GET['param1'];
}
if(isset($_GET['param2'])) {
    $attachList['param2'] = $_GET['param2];
}

Now, to know whether or not, you need a ? symbol, just count this array

if(count($attachList)) {
    $link .= "?";
    // and so on
}

Update:

To know if any parameter is set, just count the $_GET

if(count($_GET)) {
     //some parameters are set
}

Tags:

Php

Url