$_SERVER["PHP_SELF"]
$_SERVER["PHP_SELF"]
is a PHP superglobal variable that represents the filename of the currently executing script, relative to the document root. It is often used in HTML forms to ensure that the form data is submitted back to the same PHP script that generated the form. This is useful for creating self-processing forms, where the form and the form-handling logic are contained in the same file.
Here's an example of how $_SERVER["PHP_SELF"]
can be used in an HTML form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Self-Processing Form</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<input type="submit" value="Login">
</form>
<?php
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Process form data
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
// Perform necessary actions with the form data
// (e.g., validate, authenticate, save to a database)
// Display the submitted data (for demonstration purposes)
echo "<h3>Submitted Data:</h3>";
echo "Username: " . htmlspecialchars($username) . "<br>";
echo "Password: " . htmlspecialchars($password);
}
?>
</body>
</html>
In this example:
The action
attribute of the form is set to <?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>
, which means that the form will be submitted back to the same PHP script that generated the form.
The PHP script checks if the form is submitted using the POST method and then processes the form data accordingly.
Note the use of htmlspecialchars()
to prevent potential security issues by escaping special characters in the form data before displaying it.
Using $_SERVER["PHP_SELF"]
in the form's action attribute helps create self-contained forms, where the form and the form-handling logic are kept in a single file. However, it's important to validate and sanitize user input to prevent security vulnerabilities, especially when using user-submitted data in SQL queries or other sensitive operations.
Thank you.