How to create a simple PHP cookie language toggle?

前端 未结 5 1339
我寻月下人不归
我寻月下人不归 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:13

    Thanks for all the suggestions - @Mob set me in the right direction, i.e. processing the cookie on another page and then sending you back to the first.

    I did a bit more thinking and experimenting and I've finally solved it. I'll post the code below incase anyone else wants to use this.

    On your main page put this:

    Language: not set"; } ?>

    Then in another file called 'language_switcher.php' put the following code:

    $lang = "en";
    if( isset( $_POST["lang"] ) ) {
        $lang = $_POST["lang"];
        setcookie ( 'language', $lang, time() + 60*60*24*30, '/', 'mydomain.com');
        header( "Location: /previous_page_url.php" );
    }
    

    The user chooses a language and clicks 'Select Language'. The form then sends the form value to 'language_switcher.php', which sets the cookie and then sends the user back to the previous page.

    Done! :)

提交回复
热议问题