22
loading...
This website collects cookies to deliver better user experience
Just the Gist
A not uncommon criticism of PHP is that it lacks in security. The sad part is, we can't argue against it. It's too broad of a criticism which can be leveraged against most languages, as most have some way a secret can be leaked. Modern PHP and modern coding practices exists to mitigate this. But today, we are going to take a look at one very basic security flaw example, and a way we could mitigate it. It's what could happen if we don't run a web server but still have our php-files public.
index.php
located in a public-folder. This file is protecting the identity of the secret santa until Christmas Day. It may look like this:<?php
define('SECRET_SANTA', "Olaf ⛄");
?>
<!DOCTYPE html>
<html lang="en">
<body>
<h1>The Secret Santa is a secret!</h1>
<p>You have to wait until Christmas Day to know who it is.</p>
<?php
$today = new DateTime("now");
$christmas = new DateTime("2021-12-25");
if ($today >= $christmas) {
echo "<p>The Secret Santa is " . SECRET_SANTA . "!</p>";
} else {
echo "<p>The Secret Santa is still a secret.</p>";
}
?>
</body>
</html>
/
|-- public-folder
| |-- index.php
|
|-- private-folder
|-- SecretSanta.php
SecretSanta.php
file, but they would be able to see the index.php
file. So here's how we could do this.<?php
class SecretSanta
{
private const SECRET_SANTA = 'Olaf ⛄';
public static function getSecretSanta(): bool|string
{
if ((new DateTime("now")) >= new DateTime("2021-12-25")) {
return self::SECRET_SANTA;
} else {
return false;
}
}
}
getSecretSanta()
to access the secret santa. This function will return the secret santa if it's on or after Christmas Day, otherwise it will return false
. index.php
file, we can now get the secret santa by calling the static function on the class (SecretSanta::getSecretSanta()
):<?php
require('../private/SecretSanta.php');
?>
<!DOCTYPE html>
<html lang="en">
<body>
<h1>The Secret Santa is a secret!</h1>
<p>You have to wait until Christmas Day to know who it is.</p>
<?php
if (SecretSanta::getSecretSanta()) {
echo "<p>The Secret Santa is " . SecretSanta::getSecretSanta() . "!</p>";
} else {
echo "<p>The Secret Santa is still a secret.</p>";
}
?>
</body>
</html>
There is so much more to keep track of when it comes to security. This article hasn't covered even a fraction of it. And many of the issues are not specific to PHP. There are Cross Origin Resource Forgery (CSRF) attacks, SQL Injection, Cross Site Scripting (XSS), and many more.