HTTP Requests and Responses in PHP Practice Questions with Solutions

Introduction

HTTP (Hypertext Transfer Protocol) allows browsers and web servers to communicate with each other. When a user visits a website, the browser sends an HTTP request, and the server returns an HTTP response. In this chapter, you will practise handling request methods, reading request information, setting response headers, and managing HTTP status codes using PHP. HTTP Requests and Responses in PHP Practice Questions with Solutions to help you to understand the concepts.

Question 1: Display the HTTP Request Method

Problem Statement

Create a PHP program that displays the HTTP request method used to access a webpage.

PHP Solution

<?php

$method = $_SERVER["REQUEST_METHOD"];

echo "Request Method: " . $method;

?>

Sample Output

Request Method: GET

Explanation

  • $_SERVER is a PHP superglobal array containing server and request information.
  • REQUEST_METHOD stores the HTTP method used for the current request.
  • When a browser opens a page normally, it usually sends a GET request.
  • PHP reads the method and displays it.

Concepts Covered

  • HTTP request method
  • $_SERVER
  • REQUEST_METHOD
  • GET request

Question 2: Handle GET and POST Requests

Problem Statement

Create a PHP program that identifies whether the current request uses GET or POST and displays an appropriate message.

PHP Solution

<?php

$method = $_SERVER["REQUEST_METHOD"];

if ($method === "GET") {

    echo "You are using a GET request.";

} elseif ($method === "POST") {

    echo "You are using a POST request.";

} else {

    echo "Other HTTP request method.";

}

?>

Sample Output

You are using a GET request.

Explanation

The program reads the current request method and compares it with GET and POST.

  • GET is commonly used to retrieve information.
  • POST is commonly used to submit information.
  • The elseif condition handles POST requests.
  • The final else handles other methods, such as PUT, PATCH, or DELETE.

Concepts Covered

  • GET request
  • POST request
  • Conditional request handling
  • HTTP methods

Question 3: Read the Requested Page URL

Problem Statement

Create a PHP program that displays the requested page URL and query string.

PHP Solution

<?php

$requestURI = $_SERVER["REQUEST_URI"];

echo "Requested URL: " . htmlspecialchars($requestURI);

?>

Sample Output

If the page is opened using:

http://localhost/project/student.php?id=101

Output:

Requested URL: /project/student.php?id=101

Explanation

  • REQUEST_URI contains the URI requested by the browser, including its query string.
  • The value may contain a page path and parameters.
  • htmlspecialchars() safely encodes special HTML characters before displaying the value in an HTML page.

Concepts Covered

  • REQUEST_URI
  • Requested page information
  • Query strings
  • Safe HTML output

Question 4: Display the Client IP Address

Problem Statement

Create a PHP program that displays the IP address reported by the server for the current client connection.

PHP Solution

<?php

$ipAddress = $_SERVER["REMOTE_ADDR"];

echo "Client IP Address: " . htmlspecialchars($ipAddress);

?>

Sample Output

Client IP Address: 127.0.0.1

Explanation

  • REMOTE_ADDR provides the IP address of the client connecting to the server.
  • When running on the same computer through localhost, the address is commonly 127.0.0.1.
  • On a live website, it may show the connecting device’s public IP or an intermediary proxy’s IP.

Important: Do not blindly trust forwarded IP headers such as X-Forwarded-For. They should only be used when supplied by a trusted proxy.

Concepts Covered

  • REMOTE_ADDR
  • Client IP address
  • Server request information

Question 5: Set a Custom HTTP Response Header

Problem Statement

Create a PHP program that sends a custom HTTP response header to the browser.

PHP Solution

<?php

header("X-Website-Name: VSIT");

echo "Custom response header sent.";

?>

Sample Output

Custom response header sent.

Explanation

  • header() sends an HTTP response header.
  • X-Website-Name is a custom header name in this example.
  • VSIT is the value assigned to the header.
  • The browser or an HTTP client can inspect the response header.

To view the header, open the browser’s Developer Tools, select the Network tab, reload the page, and inspect the response headers.

Important: Call header() before sending output such as HTML, text, or whitespace to the browser.

Concepts Covered

  • header()
  • Custom response headers
  • HTTP response
  • Header inspection

Question 6: Set an HTTP Status Code

Problem Statement

Create a PHP program that sends an HTTP 404 status code when a requested page is not available.

PHP Solution

<?php

http_response_code(404);

echo "404 - Page Not Found.";

?>

Sample Output

404 - Page Not Found.

Explanation

  • http_response_code() sets the HTTP response status code.
  • 404 means the requested resource was not found.
  • The message is displayed in the browser.
  • The browser also receives the 404 status code.

A response body and its HTTP status code are separate parts of an HTTP response.

Concepts Covered

  • http_response_code()
  • HTTP 404 status
  • Error responses

Question 7: Redirect a User to Another Page

Problem Statement

Create a PHP program that redirects a visitor from the current page to welcome.php.

PHP Solution

<?php

header("Location: welcome.php");

exit;

?>

Sample Output

The browser opens:

welcome.php

Explanation

  • header("Location: welcome.php") sends a redirect response.
  • The browser follows the redirect and opens the destination page.
  • exit stops the execution of the current PHP script.

By default, a PHP Location redirect normally uses the 302 status code. A permanent redirect can be sent using status code 301.

Important: Do not print anything before the redirect header.

Concepts Covered

  • Location header
  • HTTP redirect
  • exit
  • Redirect response

Question 8: Send a JSON HTTP Response

Problem Statement

Create a PHP program that sends student information as a JSON response.

PHP Solution

<?php

http_response_code(200);

header("Content-Type: application/json; charset=UTF-8");

$student = [
    "id" => 101,
    "name" => "Rahul",
    "course" => "PHP",
    "status" => "Active"
];

echo json_encode($student);

?>

Sample Output

{
    "id": 101,
    "name": "Rahul",
    "course": "PHP",
    "status": "Active"
}

Explanation

  • http_response_code(200) sets the success status.
  • Content-Type: application/json tells the client that the response contains JSON.
  • The $student array stores student information.
  • json_encode() converts the PHP array into JSON.
  • The JSON data is sent as the HTTP response body.

Concepts Covered

  • JSON response
  • Content-Type header
  • HTTP 200 status
  • JSON encoding

Question 9: Handle a PUT Request

Problem Statement

Create a PHP program that checks whether the request method is PUT and displays a message when a PUT request is received.

PHP Solution

<?php

$method = $_SERVER["REQUEST_METHOD"];

if ($method === "PUT") {

    echo "PUT request received.";

} else {

    http_response_code(405);

    echo "Method Not Allowed.";

}

?>

Sample Output

When a PUT request is sent:

PUT request received.

When the page is opened normally using GET:

Method Not Allowed.

Explanation

  • PUT is an HTTP method commonly used to update a resource.
  • REQUEST_METHOD identifies the method used by the client.
  • The program checks whether the method is PUT.
  • If another method is used, PHP returns status code 405.
  • 405 Method Not Allowed indicates that the requested method is not supported for that resource.

A PUT request does not automatically populate $_POST. To read its raw request body, PHP provides php://input.

Concepts Covered

  • PUT request
  • REQUEST_METHOD
  • HTTP 405 status
  • Request method checking

Question 10: Create a Complete HTTP Request and Response System

Problem Statement

Create a PHP program that accepts GET requests and returns student information in JSON format. If another request method is used, return an HTTP 405 response.

PHP Solution

<?php

$method = $_SERVER["REQUEST_METHOD"];

header("Content-Type: application/json; charset=UTF-8");

if ($method === "GET") {

    http_response_code(200);

    $student = [
        "id" => 101,
        "name" => "Rahul",
        "course" => "PHP Programming",
        "status" => "Active"
    ];

    echo json_encode($student);

} else {

    http_response_code(405);

    echo json_encode([
        "error" => "Method Not Allowed",
        "message" => "Only GET requests are accepted."
    ]);

}

?>

Sample Output

For a GET request:

{
    "id": 101,
    "name": "Rahul",
    "course": "PHP Programming",
    "status": "Active"
}

For a POST request:

{
    "error": "Method Not Allowed",
    "message": "Only GET requests are accepted."
}

Explanation

This program combines request handling and response creation.

  1. REQUEST_METHOD identifies the incoming HTTP method.
  2. Content-Type tells the client that the response is JSON.
  3. If the method is GET, PHP returns student information.
  4. http_response_code(200) indicates a successful response.
  5. If another method is used, PHP returns status code 405.
  6. json_encode() converts both successful data and error information into JSON.

Concepts Covered

  • HTTP request handling
  • GET and POST methods
  • HTTP response headers
  • Status codes 200 and 405
  • JSON responses
  • API-style response structure

Key Takeaways

  • HTTP allows browsers and servers to exchange information.
  • A request is sent by the client, and a response is returned by the server.
  • $_SERVER["REQUEST_METHOD"] identifies the HTTP request method.
  • $_SERVER["REQUEST_URI"] provides the requested URI.
  • $_SERVER["REMOTE_ADDR"] provides the connecting client’s IP address.
  • header() sends HTTP response headers.
  • http_response_code() sets the response status code.
  • Location headers are used for redirects.
  • Content-Type identifies the type of response data.
  • JSON responses are commonly used when building APIs.

Important: HTTP headers must be sent before output begins. Do not trust user-controlled request headers or IP information without appropriate checks. Use HTTPS for sensitive communication.

Frequently Asked Questions (FAQs)

1. What are HTTP requests in PHP?

An HTTP request is a message sent by a browser or client to a web server asking for a resource or requesting an action. PHP can read request information and process it.

2. What is an HTTP response?

An HTTP response is the message returned by the server to the client. It can contain a status code, headers, and a response body.

3. Which PHP variable stores request information?

The $_SERVER superglobal contains server and request information, including the request method, requested URI, and client connection address.

4. How can we check the HTTP request method in PHP?

Use $_SERVER["REQUEST_METHOD"] to identify whether the request uses GET, POST, PUT, DELETE, or another HTTP method.

5. What is the purpose of the header() function?

The header() function sends HTTP response headers, such as Content-Type, Location, and custom headers.

6. What is the purpose of http_response_code()?

It sets or retrieves the HTTP response status code, such as 200, 301, 404, or 500.

7. What does HTTP status code 404 mean?

Status code 404 means that the requested resource could not be found on the server.

8. What does HTTP status code 405 mean?

Status code 405 means that the server does not allow the HTTP request method used for that particular resource.

9. How can PHP send a JSON response?

Set the response Content-Type to application/json and convert PHP data into JSON using json_encode().

10. What is the difference between GET and POST requests?

GET is commonly used to retrieve information, while POST is commonly used to submit information. POST data is generally sent in the request body rather than the URL query string.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top