What are some common methods for securing files on a server with password protection using PHP?
Securing files on a server with password protection using PHP involves creating a login system where users must enter a username and password to access the files. This can be achieved by storing user credentials in a database, verifying the entered credentials against the database, and granting access only if the credentials match.
<?php
session_start();
// Check if the user is already logged in
if(isset($_SESSION['username'])) {
// Display the protected files here
echo "Welcome, ".$_SESSION['username']."!";
} else {
// If not logged in, show the login form
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Verify the credentials against a database
if($username == 'admin' && $password == 'password123') {
$_SESSION['username'] = $username;
echo "Login successful!";
} else {
echo "Invalid username or password.";
}
}
?>
<form method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit" name="login">Login</button>
</form>
<?php
}
?>