Home > Software engineering >  custom get query from url function in php
custom get query from url function in php

Time:02-16

I wrote a function getQuery($param) which returns data from the

function getQuery($param){
    if(!empty(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY))){
    $queries = parse_url(strtok($_SERVER['REQUEST_URI'], PHP_URL_QUERY))['query'];
    parse_str($queries, $query);
    return $query[$param];
    }
}

//url = https://example.com/test?name=Arun&[email protected]

echo getQuery("name"); // Output will be:Arun

But if the URL parameters contain "6" this function is only returning query data until that character

//i.e. if URL = https://example.com/test?name=Arun&[email protected]
echo getQuery("email");   //  Expected Output: [email protected]
                        //  Original Output: arun05

Is there any solution to fix this bug? Someone, please help

Edit:

Thanks for the reply. I found another method to write this function

<?php
function testgetQuery($param){
    $queries = explode("&",explode("?",$_SERVER['REQUEST_URI'])[1]);
    $getQuery = [];
    foreach($queries as $query){
        $getQuery[explode("=", $query)[0]] = explode("=", $query)[1];
    }
    return $getQuery[$param];
}

This worked pretty well

  • Related