In PHP, there are several ways to pass data from one page to another. Here are a few common methods:
-
Pass data using URL parameters:
- Append parameters in the URL, for example:
page2.php?name=John&age=30
. $_GET
Use a superglobal array in the target page to get parameter values, for example:$name = $_GET['name']; $age = $_GET['age'];
.- Underlying principle: When a user clicks on a link containing URL parameters or submits a form containing parameters, the browser sends a request to the server and appends the parameter information as a query string to the URL. The server parses the URL, storing the parameters in
$_GET
a superglobal array for use by the target page.
- Append parameters in the URL, for example:
-
Submit data using the form:
- Create a form in the source page and submit data to the target page using the POST or GET method.
$_POST
Use or$_GET
superglobal array in the target page to get the data submitted by the form.- Underlying principle: When the user submits the form, the browser packages the value of the form field in the HTTP request, and sends the data to the server according to the submission method (POST or GET) of the form. After the server receives the request, it parses the form data and stores it in
$_POST
or$_GET
superglobal array.
-
Use session (Session) or cookie:
- Set session variables or cookies in the source page and read those session variables or cookies in the target page.
- Session: Use
$_SESSION
superglobal arrays to set and get session variables. - Cookie: Use the function to set the cookie, and use the superglobal array
setcookie()
on the target page to get the value of the cookie.$_COOKIE
- The underlying principle: Sessions and cookies are both mechanisms for transferring data between the server and the client. The session stores data on the server side, and the session is identified by setting the session ID in the browser, while the cookie stores the data in the browser and sends it to the server every time it is requested.
The underlying principles involve HTTP request and response mechanisms. When a user visits a page or submits a form in a browser, the browser sends an HTTP request to the server. The server parses and processes the request according to the data in the request, and then returns a corresponding HTTP response containing the passed data. PHP obtains data in requests and responses through superglobal arrays (such as $_GET
, $_POST
, $_SESSION
, etc.), thereby realizing data transfer and exchange.$_COOKIE