phpparse-url

How to avoid php parse_url return false when parse "/s?a=12&b=12.3.3.4:1233" which has ":" in the params?


How to avoid php parse_url return false when parse ''/s?a=12&b=12.3.3.4:1233" which has ":" in the params?

<?php                                                                                                                                                         
var_dump(parse_url('/s?a=12&b=12.3.3.4:1233', PHP_URL_QUERY));

returns

bool(false)

Here is the online run test result:

https://3v4l.org/8LKIV


while test good in php 7.1.7

print_r(parse_url('/s?a=12&b=12.3.3.4:1233', PHP_URL_QUERY));

return good:

a=12&b=12.3.3.4:1233

Solution

  • In PHP7 you can leave out the scheme and host, but below that version you cant.

    So you should also always include the scheme and host.

    <?php
    echo 'Without scheme and host'.PHP_EOL;
    print_r(parse_url('/s?a=12&b=12.3.3.4:1233', PHP_URL_QUERY));
    
    echo PHP_EOL.PHP_EOL;
    
    echo 'With scheme and host'.PHP_EOL;
    print_r(parse_url('http://example.com/s?a=12&b=12.3.3.4:1233', PHP_URL_QUERY));
    

    Output for 7.0.0 - 7.2.0

    Without scheme and host
    a=12&b=12.3.3.4:1233
    
    With scheme and host
    a=12&b=12.3.3.4:1233
    

    Output for 5.6.0 - 5.6.30, hhvm-3.18.5 - 3.22.0

    Without scheme and host
    
    
    
    With scheme and host
    a=12&b=12.3.3.4:1233
    

    https://3v4l.org/EQhh6