CodeBlanks Logo Icon CodeBlanks

$_SERVER and server info

PHP course · Beginner · Lesson 97/116

Learn server and request info (REQUEST_METHOD, HTTP_HOST) with $_SERVER.

$_SERVER and server info

The $_SERVER superglobal is an associative array holding information about the server and the request. Common keys include REQUEST_METHOD (request method), HTTP_HOST (host name), PHP_SELF (running script path), REMOTE_ADDR (client IP) and QUERY_STRING (URL query).

A web server fills these values. In CLI only some are present; for testing you can set them yourself, for example $_SERVER['REQUEST_METHOD'] = 'POST';.

REQUEST_METHOD tells the method

The $_SERVER['REQUEST_METHOD'] key returns the request method as a string: 'GET', 'POST', 'PUT' or 'DELETE'. Form submissions use POST; plain page visits use GET.

By checking the method, the same script can both render a form and handle its submission. Example: if ($_SERVER['REQUEST_METHOD'] === 'POST') { /* handle form */ }. The strict === keeps type safety.

Exercise Set $_SERVER['REQUEST_METHOD'] and print it

Add the line $_SERVER['REQUEST_METHOD'] = "POST";. Then write echo $_SERVER['REQUEST_METHOD'] . "\n";.

Show example solution
First set $_SERVER['REQUEST_METHOD'] = "POST";, then write echo $_SERVER['REQUEST_METHOD'] . "\n";.
Example solution:
<?php
// Set $_SERVER['REQUEST_METHOD'] and print it
$_SERVER['REQUEST_METHOD'] = "POST";
echo $_SERVER['REQUEST_METHOD'] . "\n";

Test yourself

  1. Match the $_SERVER key to its meaning

    REQUEST_METHOD
    Request method
    HTTP_HOST
    Host name
    PHP_SELF
    Script path
    REMOTE_ADDR
    Client IP
  2. Which is a valid $_SERVER key?

    • REQUEST_METHOD
    • FORM_METHOD
    • POST_TYPE
    • GET_TYPE
    Show answer

    REQUEST_METHOD — Correct. REQUEST_METHOD is the $_SERVER key that holds the request method.

  3. Complete the $_SERVER access

    echo $_SERVER[____];
    Show answer
    echo $_SERVER['REQUEST_METHOD'];

All lessons in Beginner