Table of Contents:
Welcome to phponline.in, your trusted PHP learning hub.
In this detailed course page, we’ll explore PHP Global Variables, which are a fundamental concept in PHP programming. Understanding global variables is essential because they allow data to be accessed across multiple scopes of your script.
By the end of this tutorial, you will:
- Understand the difference between local, global, and static variables
- Learn how to use the $GLOBALS superglobal array
- Work with PHP Superglobals ($_POST, $_GET, $_REQUEST, $_SERVER, $_SESSION, $_COOKIE, $_FILES, $_ENV)
- Discover best practices for handling global variables securely
- Build real-world examples like forms, sessions, and cookie management
You will Learn
- What are Global Variables in PHP?
- Variable Scope in PHP
- Local Scope
- Global Scope
- Static Scope
- The $GLOBALS Superglobal
- Examples of Using $GLOBALS
- PHP Superglobals Overview
- $_SERVER Superglobal
- $_REQUEST Superglobal
- $_POST Superglobal
- $_GET Superglobal
- $_SESSION Superglobal
- $_COOKIE Superglobal
- $_FILES Superglobal
- $_ENV Superglobal
- Difference Between $_POST and $_GET
- Using Global Variables in Functions
- Security Concerns with Global Variables
- Real-World Example: Login System with $_POST and $_SESSION
- Real-World Example: Contact Form with $_POST
- Real-World Example: Tracking Visitors with $_SERVER
- Best Practices for Using Global Variables
- Common Mistakes with Global Variables
- Advanced Usage with Superglobals
- PHP Global Constants vs. Global Variables
- Functions vs. Global Variables
- Debugging Global Variables
- How Global Variables Work in Large Applications
- Organizing Superglobal Usage in PHP Projects
- PHP Global Variables and Object-Oriented Programming
1. What are Global Variables in PHP?
In PHP, a global variable is a variable declared outside of a function and accessible from any part of the script (with the global
keyword or $GLOBALS
).
Example:
$x = 50;
function test() {
global $x;
echo $x; // Accessible inside function using global
}
test(); // 50
2. Variable Scope in PHP
PHP has three main types of variable scope:
- Local Scope – Variable declared inside a function.
- Global Scope – Variable declared outside functions.
- Static Scope – Variables that retain value after function execution.
Local Scope Example
function localScope() {
$x = 10;
echo $x;
}
localScope(); // 10
echo $x; // Error: undefined
Global Scope Example
$y = 100;
function globalScope() {
global $y;
echo $y;
}
globalScope(); // 100
Static Scope Example
function counter() {
static $count = 0;
$count++;
echo $count;
}
counter(); // 1
counter(); // 2
counter(); // 3
3. The $GLOBALS Superglobal
The $GLOBALS array is an associative array containing all global variables.
$a = 5;
$b = 10;
function add() {
$GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
}
add();
echo $c; // 15
4. Examples of Using $GLOBALS
- Sharing data between functions
- Accessing configuration variables
- Avoiding duplication of code
5. PHP Superglobals Overview
Superglobals are built-in global arrays available in all scopes:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_SESSION
$_COOKIE
$_FILES
$_ENV
6. $_SERVER Superglobal
$_SERVER
contains server and execution environment information.
echo $_SERVER['PHP_SELF'];
echo $_SERVER['SERVER_NAME'];
echo $_SERVER['HTTP_USER_AGENT'];
7. $_REQUEST Superglobal
$_REQUEST
is used to collect form data sent by GET or POST.
$name = $_REQUEST['username'];
echo "Welcome $name";
8. $_POST Superglobal
$_POST
is used for form submissions (secure).
<form method="post">
Name: <input type="text" name="user">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Hello " . $_POST['user'];
}
?>
9. $_GET Superglobal
$_GET
is used for URL parameters.
<a href="page.php?name=John">Click</a>
<?php
echo $_GET['name']; // John
?>
10. $_SESSION Superglobal
$_SESSION
is used to store data across multiple pages.
session_start();
$_SESSION['username'] = "Alice";
echo $_SESSION['username'];
11. $_COOKIE Superglobal
$_COOKIE
stores small data on the client browser.
setcookie("user", "John", time()+3600);
if(isset($_COOKIE['user'])) {
echo "Welcome " . $_COOKIE['user'];
}
12. $_FILES Superglobal
Handles file uploads.
<form method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<input type="submit">
</form>
move_uploaded_file($_FILES["fileUpload"]["tmp_name"], "uploads/" . $_FILES["fileUpload"]["name"]);
13. $_ENV Superglobal
Contains environment variables like OS paths.
print_r($_ENV);
14. Difference Between $_POST and $_GET
- $_POST – Secure, does not show data in URL, used for forms.
- $_GET – Data visible in URL, used for links and bookmarks.
15. Using Global Variables in Functions
$greeting = "Hello";
function display() {
global $greeting;
echo $greeting;
}
display(); // Hello
16. Security Concerns with Global Variables
- Avoid exposing sensitive data via
$_GET
- Sanitize
$_REQUEST
inputs - Use sessions instead of cookies for critical data
17. Real-World Example: Login System with $_POST and $_SESSION
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = $_POST['username'];
$pass = $_POST['password'];
if ($user == "admin" && $pass == "1234") {
session_start();
$_SESSION['user'] = $user;
echo "Login successful!";
} else {
echo "Invalid credentials";
}
}
18. Real-World Example: Contact Form with $_POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$message = $_POST['message'];
echo "Thank you $name. Your message: $message";
}
19. Real-World Example: Tracking Visitors with $_SERVER
$ip = $_SERVER['REMOTE_ADDR'];
echo "Your IP address is: " . $ip;
20. Best Practices for Using Global Variables
- Minimize usage of global variables
- Use functions and OOP instead
- Sanitize all user input before processing
21. Common Mistakes with Global Variables
- Overusing
global
keyword - Directly trusting
$_GET
or$_POST
- Forgetting to
session_start()
before using sessions
22. Advanced Usage with Superglobals
- Combining
$_GET
and$_POST
with$_REQUEST
- Using
$_SERVER
for security checks - File uploads with
$_FILES
23. PHP Global Constants vs. Global Variables
- Constants – Value cannot change (
define("PI", 3.14)
) - Variables – Value can be updated
24. Functions vs. Global Variables
- Functions provide encapsulation
- Global variables provide shared state
25. Debugging Global Variables
print_r($GLOBALS);
26. How Global Variables Work in Large Applications
- Use config files for storing global settings
- Use dependency injection instead of excessive globals
27. Organizing Superglobal Usage in PHP Projects
- Centralize handling in a Request class
- Validate data in input filters
28. PHP Global Variables and OOP
Instead of globals:
class User {
public $name;
function setName($name) {
$this->name = $name;
}
}
PHP global variables, PHP $GLOBALS, PHP superglobals, PHP variable scope, PHP $_POST, PHP $_GET, PHP $_SESSION, PHP $_COOKIE, PHP server variables, PHP tutorial for beginners
Frequently Asked Questions (FAQ)
Q1: What are global variables in PHP?
A: Global variables are accessible from anywhere in the script using global
or $GLOBALS
.
Q2: What are PHP Superglobals?
A: Predefined arrays like $_POST
, $_GET
, $_SESSION
, available globally.
Q3: When should I use $_POST vs $_GET?
A: Use $_POST
for secure data (forms), $_GET
for URL parameters.
Q4: Are global variables safe?
A: No, they can lead to security issues if not handled properly.
Q5: What is the difference between $GLOBALS and global keyword?
A: $GLOBALS
is an array; global
imports the variable into function scope.