How to create a simple PHP cookie language toggle?

前端 未结 5 1347
我寻月下人不归
我寻月下人不归 2020-12-14 04:56

I\'m trying to set up, what I thought would be, a simple language switch. I thought I\'d use PHP cookies, but they\'re not behaving as intended.

I\'ve read a few coo

5条回答
  •  余生分开走
    2020-12-14 05:35

    A cookie is not accessible until the setting page has been reloaded or another page has been accessed (in other words, you cannot set and access a cookie in the same page).

    Check this code out :

    if( $_GET['lang'] ) {
        $lang = (string)$_GET['lang'];
        setcookie( 'lang', $lang, time() + 60*60*24*30,'/' );
    } elseif(  !$_GET['lang']) ) {
        $lang = 'en';
    } else {
        $lang = $_GET['lang'];
    }
    header("Location: redirect_file.php")
    

    Then in redirect_file.php, you redirect back to the cookie page. Perform some checks if you want to avoid redirect loops.

提交回复
热议问题