Store a redirect URI for use after login I need to pass the current page's URI into either the HTTP headers or as a URL query string so that after being taken to the login page and successfully logging in, the user will be sent back to where they came from.

I think that by attaching a query to any login button around the site I can then tell the login page where to go. The Login button is part of many of my templates / partials show when conditionally displaying content depending on if user is logged in.

By using &lt;a href="members/login?p={% craft.request.path %}"&gt;

For example I thought that:

{% if craft.request.getQuery('p') and craft.request.getQuery('p')|length %}
    {% set p = craft.request('p') %}
{% else %}
    {% set p = '/' %}
{% endif %}


would set me up to redirect if the url contains http://craft.fira/members/login?p=/members/directory/json. However that results in a 404. Is there a safe way to pass a path into a url query? 

Secondly, I then need to know how to deal with this after logging in successfully.

All help greatly appreciated, thank you!
First – your Twig syntax is a little off. Here's how you could add the current URL/request path to a link, as a query parameter p:

&lt;a href="members/login?p={{ craft.request.path }}"&gt;Log in&lt;/a&gt;


Notice that the syntax/tag for printing a value/variable is {{ value }}, not {% value %}.

Second, since the redirect in this case should happen when the login form is successfully submitted, it makes sense to add the redirect URL to the form as a redirect input:

&lt;input type="hidden" name="redirect" value="{{ craft.request.getQuery('p')|default('/') }}" /&gt;


Note that craft.request should be all lowercase; in Craft almost all variables or service names follow the camelCase naming convention (the craft.request variable refers to the HttpRequestVariable class, which wraps the HttpRequestService).

Additionally, the above example demonstrates use of the default filter, which will print the declared value (in this case, /) if the value preceding the default statement is null or false. In this case, using default will save you an if statements and several lines of code.

Finally, if you want to do a (conditional) redirect outside of a form submission, you can make use of Twig's redirect tag:

{% set redirectUrl = craft.request.getQuery('p') %}
{% if redirectUrl %}
    {% redirect redirectUrl %}
{% endif %}