- How to create a basic PHP router
- How beginners navigate files
- How professionals navigate files
- Redirect all HTTP requests to the router
- Create a routing system with switch
- Code
- How to navigate between pages in PHP
- How to navigate between pages in PHP
- How to Redirect a Web Page with PHP
- Using the header() Function
- Using a Helper Function
- JavaScript via PHP
- Navigate from one php page to another php page
How to create a basic PHP router
Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.
When you begin your PHP journey, chances are that you will primarily hard code file paths in the URL to access them.
Let’s say you have a project called platform with the following files.
- index.php : welcome note
- courses.php : list of courses
- authors.php : list of authors
- aboutus.php : about the platform
How beginners navigate files
Imagine you want to access a list of all authors. What do you do? You type platform.com/authors.php on the URL.
It works, but what if you decide to change the name of the file one day? You’ll have to fix it everywhere you called this link.
Another issue with this way of directly calling files is that you reveal the project’s internal structure to the world, which is unsafe for security purposes.
Lastly, the URL does not look elegant. For example, calling a URL like platform.com/authors is more elegant than platform.com/authors.php .
Let’s see how we can do better.
How professionals navigate files
To do things better, we’ll need to create a routing system, which is a technique that consists of mapping all HTTP requests to a request handler. We will:
- redirect all HTTP requests to index.php (the router)
- create a routing system with switch
Redirect all HTTP requests to the router
To redirect all HTTP requests to the router, create a file named .htaccess on the root of the project and redirect all traffic to index.php . This is shown below:
RewriteEngine On RewriteCond % !-f RewriteRule ^(.*)$ index.php
In our .htaccess file, we first activate the Apache server’s runtime rewriting engine. We limit access to physical files with Apache RewriteCond directive. Then, we redirect all upcoming requests to the index.php file.
.htaccess is a configuration file for the Apache server. It has no extension, but starts with a dot ( . ) for a hidden file.
In case your app/site is not at the root of your server, or if you don’t have a virtual host, you’ll need to create your .htaccess . This is shown below:
RewriteEngine On RewriteBase // RewriteRule ^index\.php$ - [L] RewriteCond % !-f RewriteCond % !-d RewriteRule . /folder/index.php [L]
Note: Replace with the name of the folder containing your site.
Create a routing system with switch
Our routing system will work as follows:
- get the user requested path with $_SERVER super global variable
- require the corresponding page
Code
Add the code below after an index.php file is created.
How to navigate between pages in PHP
This post goes into extensive details of the cause and solutions How to fix «Headers already sent» error in PHP Also, you can find information on how to redirect web pages with HTML, JavaScript, Apache and Node.js.
How to navigate between pages in PHP
I need to verify the inputs in a Page given and then, if any errors are present, then I should be displaying the same page with the error messages. If the inputs are correct, then I should be displaying the next page. How would I achieve this ??
enter code here else if (empty($_POST["email"])) else if (empty($_POST["pwd"])) else if (empty($_POST["gender"])) else > if($valid) < header('Location: dbregister.php'); exit(); >function test_input($data) < $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; >?> "> Name :
Email:
Password:
Gender:
Click here to Submit:
I was able to validate the inputs and display the error messages, but unable to send another page which says, registration is successful ‘dbregister.php’
Also I am getting undefined error for $valid in if($valid)
There are plenty of tutorials for error handling in forms e.g. http://www.w3schools.com/php/php_form_validation.asp.
Sample file (named index.php):
How to access the file in another folder in php, I need to include a php file to one of my file. Asking for help, clarification, or responding to other answers. Making statements based on opinion; back them up with references or personal experience. To learn more, see our tips on writing great answers.
How to Redirect a Web Page with PHP
This short snippet will show you multiple ways of redirecting a web page with PHP.
So, you can achieve redirection in PHP by following the guidelines below.
Using the header() Function
This is an inbuilt PHP function that is used for sending a raw HTTP header towards the client.
The syntax of the header() function is as follows:
header( $header, $replace, $http_response_code )
Also, it is likely to apply this function for sending a new HTTP header, but one should send it to the browser prior to any text or HTML.
Let’s see how to redirect a web page using the header() function:
header('Location: //www.w3docs.com'); // or die(); exit(); ?>
As you can notice, exit() is used in the example above. It is applied to prevent the page from showing up the content remained (for instance, prohibited pages).
Also, you can use the header() function with ob_start() and ob_end_flush() , like this:
ob_start(); //this should be first line of your page header('Location: target-page.php'); ob_end_flush(); //this should be last line of your page ?>
Using a Helper Function
Here, we will demonstrate how to use a helper function for redirecting a web page. Here is an example:
function Redirect($url, $permanent = false) < header('Location: ' . $url, true, $permanent ? 301 : 302); exit(); > Redirect('//www.w3docs.com/', false);
Note that this function doesn’t support 303 status code!
Let’s check out a more flexible example:
function redirect($url, $statusCode = 303) < header('Location: ' . $url, true, $statusCode); die(); >
In some circumstances, while running in CLI (redirection won’t take place) or when the webserver is running PHP as a (F) CGI, a previously set Statusheader should be set to redirect accurately.
function Redirect($url, $code = 302)< if (strncmp('cli', PHP_SAPI, 3) !== 0) < if (headers_sent() !== true) < if (strlen(session_id()) > 0) // if using sessions session_regenerate_id(true); // avoids session fixation attacks session_write_close(); // avoids having sessions lock other requests > if (strncmp('cgi', PHP_SAPI, 3) === 0) < header(sprintf('Status: %03u', $code), true, $code); > header('Location: ' . $url, true, (preg_match('~^30[1237]$~', $code) > 0) ? $code : 302); > exit(); > >
JavaScript via PHP
Here, we will provide you with an alternative method of redirection implementing JavaScript via PHP. In JavaScript, there is a windows.location object that is implemented for getting the current URL and redirecting the browser towards a new webpage. This object encompasses essential information about a page (for example, href, a hostname, and so on).
This is how to redirect a web page using window.location:
html> html> head> title>window.location function title> head> body> p id="demo"> p> script> document.getElementById("demo").innerHTML = "URL: " + window.location.href + ""; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Hostname: " + window.location.hostname + ""; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Protocol: " + window.location.protocol + ""; script> body> html>
To conclude, let’s assume that in this short tutorial, we provided you with multiple methods to redirect a web page with PHP. Also, you can find information on how to redirect web pages with HTML, JavaScript, Apache and Node.js.
PHP page redirect, Yep, this was a life-saver for me; I dynamically populate page titles and body ids from a header include so no matter what, I was always going to have sent headers. And for me this is just a web form bot response. Nice one, thanks. –
Navigate from one php page to another php page
Yes this question has been asked before but we are including one step that we have not seen in any other answers. This question involves three pages one HTML and two PHP pages. The HTML page has a reCaptcha that is verified when the user clicks the SEND button that navigates to the verify.php page. It has your standard true or false if statements code below
if ($captcha_success->success==false) < echo "You are a bot! Go away!
"; > else if ($captcha_success->success==true) < header('location:https://androidstackoverflow.com/contactform/send- info.php');/* page on the server */ echo "You are not not a bot!
";*/ >
This is where the fail or lack of results starts. if true we want to navigate to send-info.php and send the info to the server. We can not see the code in send-info.php load or execute. We know the code works by adding it inside the true if statement So the question is this a fail because the send-info.php is not loading or no variable info is being received from the HTML page with the data? Web Page can be seen here Web Page We are not web developers and this is the only PHP code we have ever written. It has taken 5 days to get this far with the contact form so we are desperate ! For clarity contactform is a folder and all three forms are in this folder we have tried with out contactform in the path
When you view the source code it contains
1 2 You are not not a bot!
Which implies there has been some white space outputted somewhere in the PHP file prior to the header command and I suspect you have warning/error reporting turned off otherwise you would have gotten the following warning appearing: «Cannot modify header information — headers already sent by (output started at. » The solution is to make sure there are no empty lines before the
at the top of the php file.
Also try turning on error reporting. and it’ll tell you where the first output occurred
Remember to remove the error reporting code once you’ve fixed it.
This post goes into extensive details of the cause and solutions How to fix «Headers already sent» error in PHP
Redirect to specified URL on PHP script completion?, Here’s a solution to the «headers were already sent» problem. Assume you are validating and emailing a form. Make sure the php code is the first thing on your page before any of the doctype and head tags and all that jazz. Then, when the POST arrives back at the page the php code will come first and not encounter …