Check if url contains parameters

Possible duplicate:
saving URL parameters during pagination

I want to add a parameter to the current url with php, but how do I know if the URL already contains the parameter?

Example:

foobar.com/foo/bar/index.php => foobar.com/foo/bar/index.php?myparameter=5 foobar.com/index.php?foo=7 => foobar.com/index.php?foo = 7 & myparameter = 5

The main problem is that I do not know whether to add "?".

My code (found it somewhere, but it doesn't work):

<?php if(/?/.test(self.location.href)){ //if url contains ? $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&myparameter=5"; } else { $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?myparameter=5"; }?> 
+6
source share
3 answers

URL parameters obtained from the global variable $_GET , which is actually an array. So, to find out if the URL contains a parameter, you can use the isset() function.

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

After the settings, you can create a separate array of such a parameter, which must be attached to the 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 find out if you need a symbol ? just count this array

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

Update:

To find out if a parameter is set, just count $_GET

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

Indeed, you should use the parse_url () function:

 <?php $url = parse_url($_SERVER['REQUEST_URI']); if(isset($url['query'])){ //Has query params }else{ //Has no query params } ?> 

You should also enclose your array-based variables in curly braces or break out of a 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 an error message. Note: using the undefined constant REQUEST_URI - the assumed value of REQUEST_URI

+15
source

you can find '?' char as follows:

 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"; } 
+4
source

Source: https://habr.com/ru/post/917283/


All Articles