Loading...
Loading...
00:00:00

Super Global Variables in PHP

In PHP, superglobal variables are predefined variables that are always accessible in all scopes of a script. These variables are available regardless of the scope and can be accessed from anywhere in the code. There are several types of superglobal variables in PHP:

$GLOBALS

$GLOBALS: This variable is an associative array that contains references to all variables that are currently defined in the global scope of the script. It allows you to access variables that are outside the current scope, including variables from within functions and classes.

In PHP, $GLOBALS is a special variable that allows access to all global variables from anywhere in a PHP script. Global variables are variables that can be accessed from any part of the script, regardless of the scope in which they were defined.

The $GLOBALS variable is an associative array where the key is the name of the global variable and the value is the variable value. It's similar to the $_REQUEST, $_POST, and $_GET superglobal variables, but it includes all global variables, not just variables passed through the HTTP request.

Here's an example of how to use the $GLOBALS variable:

$var1 = 'Hello';
$var2 = 'world';

function print_globals() {
    foreach ($GLOBALS as $key => $value) {
        echo $key . ' = ' . $value . '<br>';
    }
}

print_globals();

In the example above, two global variables $var1 and $var2 are defined outside of the print_globals() function. Inside the function, the $GLOBALS variable is used to iterate through all global variables and print out their name and value.

Using $GLOBALS can be a convenient way to access global variables from anywhere in the script, but it's generally considered bad practice to use global variables extensively. Global variables can lead to naming conflicts and make it difficult to track variable dependencies, which can make debugging and maintaining code more difficult. It's often better to use local variables or pass data between functions using arguments and return values.

$_SERVER

$_SERVER: This variable is an associative array that contains information about the server environment and the current request. It includes information such as the headers, paths, and script locations.

Using $_SERVER to get the current page URL:

print_r($_SERVER) // to get all information about server

$pageURL = 'http';
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    $pageURL .= "s";
}
$pageURL .= "://";
if($_SERVER['SERVER_PORT'] != '80') {
    $pageURL .= $_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
} else {
    $pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}

echo $pageURL; // Output: http://example.com/mypage.php

$_GET

$_GET: This variable is an associative array that contains the values of the variables that were passed to the current script via the HTTP GET method. It is used to retrieve data from the URL, such as form data and search queries.

Using $_GET to retrieve data from the URL:

// URL: http://example.com/mypage.php?name=John&age=30
$name = $_GET['name'];
$age = $_GET['age'];

echo "Name: " . $name . "<br>";
echo "Age: " . $age; 

// Output: Name: John, Age: 30

$_POST

$_POST: This variable is an associative array that contains the values of the variables that were passed to the current script via the HTTP POST method. It is used to retrieve data from forms and other types of HTML input.

Using $_POST to retrieve data from a form:

<form method="post" action="process.php">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  
  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
  
  <input type="submit" value="Submit">
</form>

// In "process.php" file
$name = $_POST['name'];
$email = $_POST['email'];

echo "Name: " . $name . "<br>";
echo "Email: " . $email;

// Output: Name: John, Email: john@example.com

$_REQUEST

$_REQUEST: This variable is an associative array that contains the values of $_GET, $_POST, and $_COOKIE variables. It is used to retrieve data from both GET and POST requests.

In PHP, $_REQUEST is a superglobal variable that contains the values of the variables that were passed to the current script via the HTTP request, including variables from $_GET, $_POST, and $_COOKIE superglobal variables.

When a client sends a request to a web server, the server processes the request and sends a response back to the client. The request can contain various types of data, including form data, query string parameters, cookies, and more. The $_REQUEST superglobal variable provides a convenient way to access this data in PHP.

Here's an example of how $_REQUEST can be used to retrieve form data submitted using either the GET or POST method:

<form method="post" action="process.php">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  
  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
  
  <input type="submit" value="Submit">
</form>

// process.php
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];

echo "Name: " . $name . "<br>";
echo "Email: " . $email;

In the example above, the form data is submitted using the POST method, but $_REQUEST can be used to retrieve the data regardless of the method used. If the form was submitted using the GET method, the data would still be accessible via $_REQUEST.

It's worth noting that $_REQUEST is not always the best choice for accessing request data in PHP. This is because it combines data from multiple sources, which can make it harder to debug issues and track down where the data is coming from. In general, it's recommended to use the more specific superglobal variables ($_GET, $_POST, $_COOKIE) instead, depending on the type of data being accessed.

$_COOKIE

$_COOKIE: This variable is an associative array that contains the values of cookies that were sent to the current script. Cookies are small pieces of data that are stored on the client-side and sent with every request.

In PHP, $_COOKIE is a superglobal variable that contains any cookies sent to the script via the HTTP request headers. Cookies are small pieces of data that are stored on the client's computer and can be accessed by the server.

When a client makes a request to a PHP script, it can include one or more cookies in the request headers. These cookies are stored in the $_COOKIE superglobal variable, which is an associative array where the key is the name of the cookie and the value is the cookie value.

Here's an example of how to set and retrieve a cookie using $_COOKIE:

// set a cookie with the name "username" and the value "john" 
setcookie("username", "john", time() + 3600); // expires in 1 hour

// retrieve the value of the cookie "username"
$username = $_COOKIE['username'];

echo "Welcome, " . $username;

In the example above, the setcookie() function is used to set a cookie with the name "username" and the value "john". The cookie is set to expire in 1 hour. Later, the script retrieves the value of the cookie using $_COOKIE['username'] and displays a welcome message.

It's worth noting that cookies can be modified or deleted by the client, so it's important to validate and sanitize any cookie data before using it in the script. Additionally, sensitive information should not be stored in cookies as they can be accessed by the client and potentially modified.

$_SESSION

$_SESSION: This variable is an associative array that contains session variables that are available to the current script. Sessions are used to store data across multiple requests and are stored on the server-side.

Using $_SESSION to store and retrieve session data:

// start the session
session_start();

// set session variable
$_SESSION['username'] = 'john123';

// retrieve session variable
$username = $_SESSION['username'];

echo "Welcome, " . $username; // Output: Welcome, john123

$_FILES

$_FILES: This variable is an associative array that contains information about files that were uploaded to the server. It includes information such as the file name, type, and size.

In PHP, $_FILES is a superglobal variable that contains information about uploaded files. When a file is uploaded using a form with the enctype attribute set to multipart/form-data, the file information is stored in the $_FILES array.

The $_FILES array contains one or more file upload elements, each represented as an associative array with the following keys:

  • name: the name of the file as it was on the client machine
  • type: the MIME type of the file, as determined by the browser
  • tmp_name: the temporary filename of the file on the server
  • error: the error code associated with the file upload (if any)
  • size: the size of the file in bytes

Here's an example of how to handle an uploaded file using $_FILES:

<form action="upload.php" method="post" enctype="multipart/form-data">
  <label for="file">Choose a file to upload:</label>
  <input type="file" id="file" name="file">
  <input type="submit" value="Upload">
</form>

// upload.php
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
  $filename = $_FILES['file']['name'];
  $tmp_name = $_FILES['file']['tmp_name'];
  $size = $_FILES['file']['size'];
  $type = $_FILES['file']['type'];
  
  // Move the uploaded file to a new location
  move_uploaded_file($tmp_name, "uploads/" . $filename);
  
  echo "File uploaded successfully.";
} else {
  echo "Error uploading file: " . $_FILES['file']['error'];
}

In the example above, the enctype attribute is set to multipart/form-data to enable file uploads. When the form is submitted, the file is uploaded to the server and $_FILES['file'] is populated with the file information. The script checks the error code to see if there were any issues with the upload, and if everything is OK, the file is moved to a new location using the move_uploaded_file() function.

It's important to validate and sanitize file uploads to prevent security issues, such as file injection and arbitrary code execution. Some common techniques for file upload validation include checking file size, file type, and file name, and using file upload libraries that provide additional security features.

These superglobal variables are always available in PHP and are used frequently in web development to process data sent from the client-side or to interact with the server environment.