🌍 Global Variables in PHP
A global variable is declared outside any function and can be used throughout the PHP script. However, it cannot be accessed directly inside functions unless made global explicitly.
🧠 Why Use Global Variables?
- To share values (e.g., settings, constants) across multiple functions
- To reduce code repetition for values used in multiple places
🛠️ Accessing Global Variables Inside a Function
Use the global keyword or the $GLOBALS superglobal array.
$x = 10;
$y = 20;
function sum() {
global $x, $y;
echo $x + $y;
}
sum(); // Output: 30
🗃️ PHP Superglobal Variables
PHP provides several built-in global arrays, called superglobals. They are accessible anywhere in the script.
| Superglobal | Description |
|---|---|
| $GLOBALS | Access global variables inside functions |
| $_SERVER | Information about headers, paths, and server |
| $_REQUEST | Collect data from form using GET or POST |
| $_POST | Collect form data via POST method |
| $_GET | Collect data via URL query parameters |
| $_FILES | Used for file uploads |
| $_COOKIE | Access cookie values |
| $_SESSION | Used to store session values |
| $_ENV | Access environment variables |
🔧 Examples of Superglobals
✅ 1. $GLOBALS
$a = 5;
$b = 10;
function multiply() {
echo $GLOBALS['a'] * $GLOBALS['b'];
}
multiply(); // Output: 50
✅ 2. $_SERVER
echo $_SERVER['SERVER_NAME']; // Output: localhost
✅ 3. $_GET
URL: http://example.com/page.php?name=John
echo $_GET['name']; // Output: John
✅ 4. $_POST
HTML Form:
<form method="POST"> <input type="text" name="username"> <input type="submit"> </form>
PHP:
echo $_POST['username'];
✅ 5. $_COOKIE & $_SESSION
// Set cookie
setcookie("user", "Alice", time() + 3600);
// Read cookie
echo $_COOKIE["user"]; // Alice
// Start session
session_start();
$_SESSION["username"] = "John";
echo $_SESSION["username"]; // John
⚠️ Best Practices
- Use
globaland$GLOBALScarefully to avoid conflicts - Prefer using parameters and return values for function communication
- Sanitize and validate all superglobal input like
$_GETand$_POST - Initialize sessions with
session_start()before using$_SESSION

0 Comments