Redirecting a web user to another web page without requiring the user to click a link is a common practice in web development. The built in function of C# is the Redirect function. The redirection function can take one or two input parameters. With one input parameter, simply specify the redirect url.
Response.Redirect("http://www.victorchen.info");
By using only one parameter, code after the Redirect function can still be executed. To prevent this, use the overloaded Redirect function with two input parameters. The first input parameter is still the redirect url, but the second input is the a boolean variable indicating whether remaining code on the page should continue executing or stop when the redirection function is reached.
Response.Redirect("http://www.victorchen.info", false);
Redirect is a function of the HttpResponse class. The Redirect function returns void.
To redirect a page to another page during PHP processing, simply use the header function demonstrated below:
<?php
header("Location: http://www.victorchen.info");
?>
Whenever this script is reached, the page will automatically redirect to http://www.victorchen.info.
- The header function must occur before any page output. This includes page outputs originating from include() or require() functions. Additionally, keep an eye out for blank lines before the header function is executed.
- The URL does not need to be a full url (http://www.victorchen.info). It can alternatively be “../index.html”.
The below example will not work because there is an output of “This will not work” before the header() function is called.
<?php
header("Location: http://www.victorchen.info");
?>
This example will also not work because the text “This will not work” is placed in an php echo command.
<?php
echo "This will not work";
header("Location: http://www.victorchen.info");
?>
This next example shows how having a hidden space before the first php command will also not work. Please note the first line of the example below is empty! To see this highlight the code below and see the first character is a blank!
<?php
header("Location: http://www.victorchen.info");
?>
Lastly, the following code below will work. The string “This will work” is placed after the redirect.
<?php
header("Location: http://www.victorchen.info");
echo "This will work";
?>
Please note that the string “This will work” will never actually execute in this scenario, as the header function will trigger the page to first redirect. Simply placing an if statement around the header function allows toggling of when the header function is executed.