PHP get URL string parameters?

php get all url parameters
php get value from url
php get current url with query string
php parse url
how to pass parameter in url in php
php parse query string
php url
get string in url php

After reading many articles here, I did not find a solution, so I need help to do this... My URLs are those Example:

Home Page

https://mywebsite.com/
https://mywebsite.com/al/
https://mywebsite.com/it/
https://mywebsite.com/videos/
https://mywebsite.com/al/videos/
https://mywebsite.com/it/videos/
https://mywebsite.com/news/
https://mywebsite.com/al/news/
https://mywebsite.com/it/news/

Query

https://mywebsite.com/search/?q=YouTube
https://mywebsite.com/videos/search/?q=YouTube
https://mywebsite.com/news/search/?q=YouTube

https://mywebsite.com/al/search/?q=YouTube
https://mywebsite.com/al/videos/search/?q=YouTube
https://mywebsite.com/al/news/search/?q=YouTube

https://mywebsite.com/it/search/?q=YouTube
https://mywebsite.com/it/videos/search/?q=YouTube
https://mywebsite.com/it/news/search/?q=YouTube

My php & html to change the language

<?php $Ava_Sulg = $_SERVER["REQUEST_URI"];?>

<a class="x" href="/<?php echo $Ava_Sulg;?>">EN</a>
<a class="x" href="/al<?php echo $Ava_Sulg;?>">AL</a>
<a class="x" href="/it<?php echo $Ava_Sulg;?>">IT</a>

so I'm allowing users to change their language, that what I want to do, is when they change the language the url can be one of the above, example if they change the language from AL to IT and url is https://mywebsite.com/al/videos/search/?q=YouTube with PHP I want to get this https://mywebsite.com/it/videos/search/?q=YouTube so I want to change from this url only (/al/ to /it/) or exmaple from IT to EN (/it/ to Nothing) but that what I want to change is in the middle, and on home page is different, it is very difficult for me, How I can do this is this possible or no? I hope to find a solution here, if possible! Thank you very mouch.

Since you are only interested in manipulating the path component you can simply use parse_url to extract the path component instead of regex:

function generateurl($url, $lc) {
    $parts = parse_url($url);
    $parts['path'] = preg_replace('@^/[a-z][a-z]/@', '/', $parts['path']);
    if ($lc !== 'en') {
        $parts['path'] = '/' . $lc . $parts['path'];
    }
    $url = '';
    if (isset($parts['scheme'])) $url .= $parts['scheme'] . '://';
    if (isset($parts['host'])) $url .= $parts['host'];
    if (isset($parts['port'])) $url .= ':' . $parts['port'];
    if (isset($parts['path'])) $url .= $parts['path'];
    if (isset($parts['query'])) $url .= '?' . $parts['query'];
    if (isset($parts['fragment'])) $url .= '#' . $parts['fragment'];
    return $url;
}

The above function could be simplified if you have http_build_url function available. Function input and output:

                           https://mywebsite.com/ + en = https://mywebsite.com/
                           https://mywebsite.com/ + al = https://mywebsite.com/al/
                           https://mywebsite.com/ + it = https://mywebsite.com/it/
                        https://mywebsite.com/al/ + en = https://mywebsite.com/
                        https://mywebsite.com/al/ + al = https://mywebsite.com/al/
                        https://mywebsite.com/al/ + it = https://mywebsite.com/it/

                    https://mywebsite.com/videos/ + en = https://mywebsite.com/videos/
                    https://mywebsite.com/videos/ + al = https://mywebsite.com/al/videos/
                    https://mywebsite.com/videos/ + it = https://mywebsite.com/it/videos/
                 https://mywebsite.com/al/videos/ + en = https://mywebsite.com/videos/
                 https://mywebsite.com/al/videos/ + al = https://mywebsite.com/al/videos/
                 https://mywebsite.com/al/videos/ + it = https://mywebsite.com/it/videos/

   https://mywebsite.com/videos/search/?q=YouTube + en = https://mywebsite.com/videos/search/?q=YouTube
   https://mywebsite.com/videos/search/?q=YouTube + al = https://mywebsite.com/al/videos/search/?q=YouTube
   https://mywebsite.com/videos/search/?q=YouTube + it = https://mywebsite.com/it/videos/search/?q=YouTube
https://mywebsite.com/al/videos/search/?q=YouTube + en = https://mywebsite.com/videos/search/?q=YouTube
https://mywebsite.com/al/videos/search/?q=YouTube + al = https://mywebsite.com/al/videos/search/?q=YouTube
https://mywebsite.com/al/videos/search/?q=YouTube + it = https://mywebsite.com/it/videos/search/?q=YouTube

                        /videos/search/?q=YouTube + en = /videos/search/?q=YouTube
                        /videos/search/?q=YouTube + al = /al/videos/search/?q=YouTube
                        /videos/search/?q=YouTube + it = /it/videos/search/?q=YouTube
                     /al/videos/search/?q=YouTube + en = /videos/search/?q=YouTube
                     /al/videos/search/?q=YouTube + al = /al/videos/search/?q=YouTube
                     /al/videos/search/?q=YouTube + it = /it/videos/search/?q=YouTube

PHP: $_GET, An associative array of variables passed to the current script via the URL parameters (aka. query string). Note that the array is not only populated for GET  The parameters from a URL string can be be retrieved in PHP using pase_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it. It parse an URL and return an associative array which contains its various components.

First I'd recommend that for English you keep the /en/ in the URL, it will be easier to manage.

Then to extract the language code and replace by an other value you can use

You can use preg_replace (REGEX)

$url = "https://mywebsite.com/en/foo";
$codes = [ 'it', 'fr', ...]; 
$urls = [];
foreach($codes as $code){
    $urls[$code] = preg_replace("(https://mywebsite.com/)[a-z]{2}(.*)", "$1". $code. "$2", $url);
}

parse_url - Manual, If the component parameter is specified, parse_url() returns a string (or an able to find a simple conversion back to string from a parsed url, here's an example: A URL can pass along parameters in the form of query string. PHP can retrieve and get the query string for manipulation and handling in functions and processes. The easiest and fastest way to get the value of query string in PHP is through $_GET predefined variables. $_GET contains an associative array of variables passed to the current script via the URL parameters, which are passed through urldecode ().

Replacement of URL is bad practice. You should make two parts for work with URL:

  1. Parsing of language and URI without language
  2. A building of any URI with language

For example, parsing of language might be looked like:

function extractLanguage($uri)
{
    if (preg_match('/^\/[a-z]{2}\//', $uri, $matches)) {
        $language = trim($matches[0], '/');
    } else {
       $language = ''; // or default language
    }   
    return $language;
}

extractLanguage('/search/?q=YouTube'); // will return empty string
extractLanguage('/al/search/?qURIuTube'); // will return 'al'

Parsing of URI without language might be looked like

function extractUri($uri)
{
    $uri= preg_replace('/^\/[a-z]{2}\//', '', $uri);
    if ($uri[0] !== '/') {
        $uri = '/' . $uri;
    }
    return $uri;
}

extractUri('/search/?q=YouTube'); // will return '/search/?q=YouTube'
extractUri('/al/search/?q=YouTube'); // will return '/search/?q=YouTube'

If you will have separated language and separated URI you can build target URL, for example with help the following function

function buildUri($path, $params = [], $language = '')
{
   $query = '';
   if (!empty($params)) {
       $query = '?' . http_build_query($params);
   }
   if (!empty($language)) {
       $language = '/' . $language ;
   } 
   return $language . $path . $query;
}

buildUri('/news/search', array('q' => 'YouTube')) // will return '/news/search/?q=YouTube'
buildUri('/news/search', array('q' => 'YouTube'), 'it') // will return 'it/news/search/?q=YouTube'

How to get parameters from a URL string in PHP?, Approach: Parse the URL string using parse_url() function which will return an associative array that contains its (passed URL) various components. The query of  Using $_SERVER['QUERY_STRING'] in PHP we can get the full query string from the current URL. For example: For example: echo $_SERVER['QUERY_STRING']; // Output: key1=value1&key2=value2

I've created a function that does this for you. Here is how it works:

  1. It removes the chosen language and everything after that from the url and puts that in $startUrl.
  2. Takes the original url and removes the first part of it including the language, and puts that into $endUrl.
  3. Adds the provided language to the middle and puts all three parts together, naming them $newUrl and returns that.

NOTE: This function requires you to specify language in every url, even for english!

NOTE 2: You might need to change the $key-value in both removing-parts of the function if you change the structure of your base url from https://mywebsite.com/ to, say, https://mywebsite.com/public/. I've added comments in the code about where they´re located.

function createUrl($url, $language){
    /*
    * FIX THE BEGINNING OF THE URL
    */
    // Explode the url into smaller parts and put into an array
    foreach((explode('/', $url)) as $key => $value){
        $expArray[$key] = $value;
    };

    // Remove the last part of the URL (including chosen language)
    foreach($expArray as $key => $value){
        if($key > 0){ /*<--This is one of the values you might need to be changed if your base url structure changes*/
            unset($expArray[$key]); 
        }
    }

    // Implode the array back to a string
    foreach($expArray as $key => $value){
        $startUrl = implode('/', $expArray);
    };



    /*
    * FIX THE END OF THE URL
    */
    // Explode the url into smaller parts and put into an array
    foreach((explode('/', $url)) as $key => $value){
        $expArray[$key] = $value;
    };

    // Remove the first part of the URL (including chosen language)
    foreach($expArray as $key => $value){
        if($key < 2){ /*<--This is the other value you might need to be changed if your base url structure changes*/
            unset($expArray[$key]); 
        }
    }

    // Implode the array back to a string
    foreach($expArray as $key => $value){
        $endUrl = implode('/', $expArray);
    };


    /* 
    * Put it all together
    */
    if(isset($endUrl)){
       $newUrl = $startUrl . $language . $endUrl;
       return $newUrl;
    }else{
       $newUrl = $startUrl . $language;
       return $newUrl;
    }
};

To use it in your example you write it like this:

<a class="x" href="<?php echo createUrl($_SERVER["REQUEST_URI"], '/EN/');?>"></a>
<a class="x" href="<?php echo createUrl($_SERVER["REQUEST_URI"], '/AL/');?></a>
<a class="x" href="<?php echo createUrl($_SERVER["REQUEST_URI"], '/IT/');?></a>

How To Get Key/Value Pair From URL Query String In PHP , In this article we look at different ways in PHP to retrieve the query string and its parameter values from a URL. We'll be using the following string for all the  PHP get current page URL. In PHP there are some built in global variables that make the getting the current URL process quite simple. You can get every piece of information about the current URL using the $_SERVER suberglobal array. You can get the domain name, the script name, the url parameters and any variation of these.

My solution! 'not perfect' beaucose if the user is searching on https://example.com/es/news/search/?q=news when i change the language, example from es to en, the url change like this https://example.com/search/?q=news

if(isset($_GET["q"])) {
$qurl = $_GET["q"];
$surl = "/search/?q=";
}else{
$qurl = "";
$surl = "";
}

PHP parse_str() Function, Parameter Values. Parameter, Description. string, Required. Specifies the string to parse. array, Optional (Required from PHP 7.2)  PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.

Passing Variables through URL, To get the variable values from the url use the $_GET method Example. this is an example of passing a string variable tom and int variable 22 to the php script. parse_url ( string $url [, int $component = -1 ] ) : mixed. This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded. This function is not meant to validate the given URL, it only breaks it up into the above listed parts.

Retrieve & Get Query String from URL in PHP, A URL can pass along parameters in the form of query string. PHP can retrieve and get the query string for manipulation and handling in  Description ¶ An associative array of variables passed to the current script via the URL parameters (aka. query string). Note that the array is not only populated for GET requests, but rather for all requests with a query string. $HTTP_GET_VARS contains the same initial information, but is not a superglobal.

Query string, On the World Wide Web, a query string is a part of a uniform resource locator (​URL) that assigns values to specified parameters. form content is only encoded in the URL's query string when the form submission method is GET. Retrieved from "https://en.wikipedia.org/w/index.php?title=Query_string&oldid=960519802". Here the biggest advantage is we can pass data to a different site even running at different servers. Any scripting language like ASP, JSP, PHP or Perl running at receiving end can process and collect the value from the query string or from the URL. Easy to save the URL or bookmark it for frequent use. Copy the URL and send it to a friend to refer.

Comments
  • Thank you very very mouch fro your help, i have fix that, but now I can not output the video titile and images, video:title & video:thumbnail_loc,
  • <video:title>Video Title </video:title> <video:description> des </video:description> </video:thumbnail_loc> image </video:thumbnail_loc><video:duration>302</video:duration>
  • <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="sitemaps.org/schemas/sitemap/0.9" xmlns:video="google.com/schemas/sitemap-video/1.1"> <url> <loc>video post url/</loc> <video:video> <video:player_loc allow_embed="yes">yembed url/</video:player_loc> <video:title>TITLE</video:title> <video:description>DESCREPTIN</video:description> <video:thumbnail_loc>IMAGE.jpg</video:thumbnail_loc> <video:duration>384</video:duration> </video:video> </url>
  • on html, how i add the url now? <a class="x" href="/<?php echo $url;?>">EN</a> ?
  • Assuming the url is absolute i.e. starts with https or / you need to <a class="x" href="<?php echo generateurl($url, 'en'); ?>">EN</a>
  • Thanks for your help, but I have more then 20 Languages on my website, I find it difficult to do that what I want, beaucose im not that good for script, just I like to do somthing, but thanks again
  • If you have several languages, you just need to wrap one of the two options (the 2nd is recommended) in a foreach loop
  • i need som php code to do this function example, if after domain url mywebsite.com is /it/ or /es/ or /fr/ remove it.
  • I updated the answer to show you an example of how you can implement it with a foreach loop
  • thanks again for your help, but in this case does not help me.
  • Thanks for your help
  • thanks for your help, but is not working, when i change from mywebsite.com/al to example mywebsite.com/it that is goin on this link mywebsite.com/al/it
  • That is probably since your using mywebsite.com/al and not https://mywebsite.com/al. Try adjusting the $key-values accordingly.
  • Allright, I've tried this out in a real apache environment instead of this php-fiddle tool I used before and it seems that my browser (chrome) cuts away the https:// part. I've updated the code in the original answer to work with this scenario. Please try it out again. P.S I've allso added an if-statement at the bottom of the code to prevent an error when working with short urls.
  • Thanks for your help.