Predefined Variables in PHP Language
PHP, as a server-side scripting language, provides a plethora of predefined variables that offer information and functionality for vari
ous aspects of your web applications. In this post, we will explore some of the most commonly used predefined variables in PHP and provide examples of how to leverage them in your code.Superglobals in PHP Language
Superglobals are a set of predefined variables that are always accessible, regardless of scope. The most frequently used superglobals in PHP are:
$_GET
$_GET
is used to collect data sent to a script via a URL query string.
Example:
// URL: http://example.com/index.php?name=John
$name = $_GET['name'];
echo "Hello, $name!";
$_POST
$_POST
is used to collect data sent to a script through an HTTP POST request.
Example:
// HTML form: <form method="post" action="process.php">
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION
$_SESSION
is used to store session variables. It allows you to persist data across multiple pages during a user’s visit.
Example:
// On the login page
session_start();
$_SESSION['user_id'] = 123;
// On the dashboard page
session_start();
$user_id = $_SESSION['user_id'];
$_COOKIE
$_COOKIE
is used to access cookies sent by the client’s browser.
Example:
// Set a cookie
setcookie("username", "John", time() + 3600, "/");
// Retrieve a cookie
$username = $_COOKIE['username'];
Server and Environment Variables in PHP Language
These variables provide information about the server and the environment in which the script is running:
$_SERVER
$_SERVER
contains an array of information about the server and the execution environment.
Example:
$serverName = $_SERVER['SERVER_NAME'];
$remoteAddr = $_SERVER['REMOTE_ADDR'];
$_ENV
$_ENV
contains an array of environment variables.
Example:
$databasePassword = $_ENV['DB_PASSWORD'];
File-Related Variables in PHP Language
PHP provides variables to access information about the currently executing script:
__FILE__
__FILE__
returns the full path and filename of the script.
Example:
$scriptPath = __FILE__;
__LINE__
__LINE__
returns the current line number in the script.
Example:
$lineNumber = __LINE__;
User-Related Variables in PHP Language
These predefined variables are used to access information about the user:
$_SESSION['user_id']
This variable, stored in the $_SESSION
superglobal, is often used to track the currently logged-in user.
Example:
session_start();
$user_id = $_SESSION['user_id'];
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.