Primeira tentativa
Dessa vez o código protege contra XSS…
<!-- Arquivo: index.html -->
<!DOCTYPE html>
<html>
<head>
<title>TestSite</title>
<meta charset="utf-8" />
</head>
<body lang="en-US">
<h1>Open user profile</h1>
<form method="GET" action="./user.php">
<p>
<label for="name">User's name:</label>
<input
type="text"
id="name"
name="name"
placehoder="John Doe"
/>
</p>
<input type="submit" value="Open profile" />
</form>
<h1>Register new profile</h1>
<form method="POST" action="./user.php">
<p>
<label for="name">User's name:</label>
<input
type="text"
id="name"
name="name"
placehoder="John Doe"
/>
</p>
<p>
<label for="site_url">User's site URL:</label>
<input
type="url"
id="site_url"
name="site_url"
placehoder="https://mysite.com"
/>
</p>
<input type="submit" value="Register" />
</form>
</body>
</html>
<?php
// Arquivo: user.php
function protect_against_xss(string $value): string
{return str_replace(['<', '>'], ['<', '>'], $value);
}
$dbHost = getenv('DB_HOST');
$dbName = getenv('DB_NAME');
$dbUser = getenv('DB_USER');
$dbPass = getenv('DB_PASS');
$dbCharset = getenv('DB_CHARSET') ?: 'utf8mb4';
try {
$pdo = new PDO(
"mysql:host=$dbHost;dbname=$dbName;charset=$dbCharset",
$dbUser,
$dbPass,
;
)
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = protect_against_xss($_POST['name']);
$site_url = protect_against_xss($_POST['site_url']);
$sql = "
INSERT INTO users_test (
name,
site_url
) VALUES (
:name,
:site_url
)
";
$statement = $pdo->prepare($sql);
$statement->bindParam('name', $name);
$statement->bindParam('site_url', $site_url);
$statement->execute();
echo 'User registered successful!';
else {
} $name = $_GET['name'];
$sql = "
SELECT name, site_url
FROM users_test
WHERE name = :name
";
$statement = $pdo->prepare($sql);
$statement->bindParam('name', $name);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
echo "
{$user['name']}'s site:
<a href=\"{$user['site_url']}\">Click here</a>
";
}catch (\Throwable $e) {
} throw $e;
echo "Something went wrong!";
http_response_code(500);
return;
}