PHP Redirects – Redirect page using PHP

In this post we will be using PHP to redirect to another webpage, in this particular example our webpage will contain a button that will utilize the HTTP POST method. Our PHP script will then make the redirect once the button has been pressed.

We begin by creating our webpage with a button in HTML as seen in the snippet of code below.

<html lang="en">
  <body>
  <p>Click button to go to website</p>
	<form method="post" action="<?php $_PHP_SELF ?>">
	 <button name="redirect">Click here</button>	 
	</form>
  </body>
</html>

The above would be seen as the following in browser.

Button in HTML

We now move on to implementing our server side code in PHP, the snippet of code below will first check if the ‘$_POST’ array is not empty. Providing an item within the array is present it will redirect the webpage to scriptopia.co.uk.

<?php
     if ( !empty($_POST) ) {
	header("Location: http://www.scriptopia.co.uk/");
	 }

The full source code for this project can be found below.

<?php
     if ( !empty($_POST) ) {
	header("Location: http://www.scriptopia.co.uk/");
	 }
?>

<html lang="en">
  <body>
  <p>Click button to go to website</p>
	<form method="post" action="<?php $_PHP_SELF ?>">
	 <button name="redirect">Click here</button>	 
	</form>
  </body>
</html>

Leave a Reply