This URL shortener is just for my own use and it runs on my local machine. I created this for fun and I doubt if I would ever use it in production. Is my script any good?
shortener.php
<?php
require_once 'lib/db.php';
function random_string($length, $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
$chars_length = strlen($charset) - 1;
$str = '';
for ($i = 0; $i < $length; ++$i) {
$str .= $charset[random_int(0, $chars_length)];
}
return $str;
}
$url = $error = '';
if (isset($_GET['id'])) {
$id = trim($_GET['id']);
$stmt = $pdo->prepare('SELECT url FROM url WHERE id = ?');
$stmt->execute([$id]);
$url = $stmt->fetchColumn();
header('Location: ' . ($url ?: "http://{$_SERVER['HTTP_HOST']}{$_SERVER['SCRIPT_NAME']}"));
exit;
}
else {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$url = $_POST['url'];
if (filter_var($url, FILTER_VALIDATE_URL) !== FALSE) {
do {
$id = random_string(5);
$stmt = $pdo->prepare('SELECT COUNT(*) FROM url WHERE id = ?');
$stmt->execute([$id]);
$count = $stmt->fetchColumn();
}
while ($count > 0);
$stmt = $pdo->prepare('INSERT INTO url (id, url) VALUES (?, ?)');
$stmt->execute([$id, $url]);
header("Location: http://{$_SERVER['HTTP_HOST']}{$_SERVER['SCRIPT_NAME']}");
exit;
}
else {
$error = 'Not a valid URL';
}
}
$last_id = $pdo->query('SELECT id FROM url ORDER BY created DESC LIMIT 1')->fetchColumn();
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Extremely Simple Short URL Generator</title>
</head>
<body>
<form method="post">
<input type="text" name="url" placeholder="URL here" value="<?= htmlspecialchars($url) ?>">
<button type="submit">Submit</button>
</form>
<?php if ($last_id): ?><p><a href="<?= "{$_SERVER['SCRIPT_NAME']}?", http_build_query(['id' => $last_id]) ?>">Latest Link</a></p><?php endif ?>
<?php if ($error): ?><p style="color: red"><?= $error ?></p><?php endif ?>
</body>
</html>
I'm aware that separating the view from the script is better, but for a simple app like this, I don't think it's necessary.
db.php
<?php
$pdo = new PDO(
'mysql:host=host;dbname=dbname;charset=utf8mb4',
'username',
'password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => FALSE,
]
);
Any improvement is welcome.
random_int()
? I could guess that it is similar torandom_string()
or might just utilizerand()
... \$\endgroup\$random_int()
that was added since PHP 7. \$\endgroup\$