• Resolved isaacbenh

    (@isaacbenh)


    I have a weird problem and it only happens in this specific function.
    I usually use return; instead of exit; and it all works fine, but here the SESSION variables are just not working, unless I use exit; instead.

    function check_reset_link()
    {
        if ( is_page( 'reset-password' ) )
        {
            $user = check_password_reset_key($_REQUEST['key'], $_REQUEST['login']);
            if( is_wp_error ($user ) )
            {
                $lost_password_url = network_site_url( '/lostpassword' );
                $_SESSION["errors"]["send-reset-link-error"] = "Reset link is invalid, you may request another one here.";
                wp_safe_redirect( $lost_password_url );
                exit;
    
                return wp_safe_redirect( $lost_password_url ); // won't work
    
            }
        }
    }
    add_action( 'template_redirect', 'check_reset_link' );

    When I process forms I just use return; and it all works great. Should I change everything to exit: instead?

    By the way, I’m not sure when to use redirect VS. safe_redirect

Viewing 2 replies - 1 through 2 (of 2 total)
  • Max

    (@clementsm)

    After you do a redirect you should exit the script. A redirect causes a new page-load which will start the execution of a new script.

    I am not really sure what you are trying to achieve with this statement:

    return wp_safe_redirect( $lost_password_url );

    A return call in a function ends execution of the function and causes the function to return the value of the parameter passed to the return.

    wp_safe_redirect() is another function call that causes an HTTP redirect response to be sent to the client browser, which then should follow the response to a new location. It also does not return a value.

    There is no point to use return after a re-direct as you would like the current script to stop execution, given the client will request a new page. This is why you want to call “exit” directly after a wp_safe_redirect() statement, so that the script stops execution.

    wp_safe_redirect() will only allow redirects to local URLs, or to the wp-admin url on the site_url. This prevents someone (or a plugin) from adding another host to the redirect. You should probably always consider using wp_safe_redirect(), unless you want to send your visitors somewhere off your site on purpose.

    Thread Starter isaacbenh

    (@isaacbenh)

    Thank you. I understand things better now 🙂

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Session variables only works with exit;’ is closed to new replies.