简体   繁体   中英

Why is file_get_contents() messing up GET data?

So, I as I understand, my problem is that file_get_contents() does not send proper UTF-8 URL even though it's being passed, so the $_GET data which server is receiving is a bit messed up. Part of my code:

//receiving post data from html form "nacionālā opera"
$q = $_POST["q"];

if (!empty($q)) {
    $get_data = array( 
        'http' => array(
            'header'=> array("Content-Type: text/plain; charset=utf-8",
                             "User-agent: PHP bots;")   
        ) 
    );
    $stream_cont = stream_context_create($get_data);

    $search = str_replace(" ", "+", $q);
    $url = 'http://127.0.0.1/test.php?stotele='.$search.'&a=p.search&t=xml&day=1-5&l=lv';

    if (mb_detect_encoding($url) === 'UTF-8') {
        echo '$url encoding is ok...??';
    } else {
        echo 'URL encoding not UTF-8!';
        exit();
    }

    $rec_data = file_get_contents($url, false, $stream_cont);

Here is what the server gets when printing the $_GET array:

stotele => nacionÄ_lÄ_ opera // this should have been "nacionālā opera", but as u see it got distorted
a => p.search 
t => xml 
day => 1-5 
l => lv 

I hope you understand what I am trying to say. This thing drives me crazy and I can't solve it, would be nice if someone gave me hints(and yes, my browser encoding is set to UTF-8, also form is sending UTF-8 and if I echo $q or $search or $url I get a normal string, not some messed up symbols.

Try using urlencode

// instead of this:
// $search = str_replace(" ", "+", $q);
// use:
$search = urlencode($q);
$url = 'http://127.0.0.1/test.php?stotele='.$search.'&a=p.search&t=xml&day=1-5&l=lv';

saw it on php.net

if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")=="UTF-8" ) 

or

if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")==="UTF-8" ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM