Narzędzia użytkownika

Narzędzia witryny


narzedzia:php_url_short

PHP: URL Shortener with Simple Flat-File storage

Skrypt w języku PHP pozwalający na skracanie długich adresów URL

Dostępny pod linkiem:

https://wiki.ostrowski.net.pl/urlshort/

Kod rozwiązania:

index.php
<?php
/*
 * Simple Flat-File URL Shortener with Admin Panel and Basic Authentication
 * Single PHP file solution using a JSON file for storage.
 * Features:
 * - Shorten URLs
 * - Redirect shortened URLs
 * - Admin view with login/password protection, list and delete entries
 * Usage:
 * 1. Place this file (e.g., index.php) on your server.
 * 2. Ensure the script has write permissions to the directory.
 * 3. Visit the script in your browser to shorten URLs.
 * 4. Access shortened URLs via: http://your-domain.com/index.php?c=SHORTCODE
 * 5. Visit the admin panel: http://your-domain.com/index.php?view=admin
 */
 
session_start();
 
// Configuration
$storage_file = __DIR__ . '/urls.json';
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
    . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
 
// Admin credentials
$admin_user = 'admin';        // Change to desired username
$admin_pass = 'password123';  // Change to desired password
 
// Handle logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: ' . $base_url);
    exit;
}
 
// Show login form if accessing admin panel without authentication
$view_admin = (isset($_GET['view']) && $_GET['view'] === 'admin');
if ($view_admin && !isset($_SESSION['authenticated'])) {
    $error = '';
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'], $_POST['password'])) {
        if ($_POST['username'] === $admin_user && $_POST['password'] === $admin_pass) {
            $_SESSION['authenticated'] = true;
            header('Location: ' . $base_url . '?view=admin');
            exit;
        } else {
            $error = 'Invalid username or password.';
        }
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Admin Login</title>
        <style>
            body { font-family: Arial, sans-serif; max-width: 400px; margin: 50px auto; padding: 0 20px; }
            input { width: 100%; padding: 8px; margin: 8px 0; }
            input[type="submit"] { width: auto; }
            .error { color: red; }
        </style>
    </head>
    <body>
        <h1>Admin Login</h1>
        <?php if (!empty($error)): ?>
            <div class="error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <form method="post">
            <label>Username:<br><input type="text" name="username" required></label>
            <label>Password:<br><input type="password" name="password" required></label>
            <input type="submit" value="Login">
        </form>
    </body>
    </html>
    <?php
    exit;
}
 
// Load existing URLs
$urls = [];
if (file_exists($storage_file)) {
    $json = file_get_contents($storage_file);
    $urls = json_decode($json, true) ?: [];
}
 
$message = '';
 
// Handle deletion in admin panel
if ($view_admin && isset($_GET['delete']) && isset($_SESSION['authenticated'])) {
    $code_to_delete = preg_replace('/[^a-zA-Z0-9]/', '', $_GET['delete']);
    if (isset($urls[$code_to_delete])) {
        unset($urls[$code_to_delete]);
        file_put_contents($storage_file, json_encode($urls, JSON_PRETTY_PRINT));
        $message = "Entry '$code_to_delete' has been deleted.";
    } else {
        $message = "Code not found.";
    }
}
 
// Handle redirection if 'c' parameter is present
if (isset($_GET['c'])) {
    $code = preg_replace('/[^a-zA-Z0-9]/', '', $_GET['c']);
    if (isset($urls[$code])) {
        header('Location: ' . $urls[$code]);
        exit;
    } else {
        http_response_code(404);
        echo "<h1>404 Not Found</h1><p>Short URL not found.</p>";
        exit;
    }
}
 
// Handle form submission for shortening
$short_url = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['url']) && !$view_admin) {
    $original_url = filter_var(trim($_POST['url']), FILTER_VALIDATE_URL);
    if ($original_url) {
        // Generate unique code
        do {
            $code = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
        } while (isset($urls[$code]));
        // Save mapping
        $urls[$code] = $original_url;
        file_put_contents($storage_file, json_encode($urls, JSON_PRETTY_PRINT));
        $short_url = $base_url . '?c=' . $code;
    } else {
        $message = 'Please enter a valid URL.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Simple URL Shortener</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 0 20px; }
        input[type="url"] { width: 70%; padding: 8px; }
        input[type="submit"] { padding: 8px 16px; }
        .message { margin: 20px 0; color: red; }
        .result { margin: 20px 0; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f4f4f4; }
        .actions a { color: #c00; text-decoration: none; }
        .nav { margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="nav">
        <a href="<?= htmlspecialchars($base_url) ?>">Shorten URL</a> |
        <?php if (isset($_SESSION['authenticated'])): ?>
            <a href="<?= htmlspecialchars($base_url . '?view=admin') ?>">Admin Panel</a> |
            <a href="<?= htmlspecialchars($base_url . '?action=logout') ?>">Logout</a>
        <?php else: ?>
            <a href="<?= htmlspecialchars($base_url . '?view=admin') ?>">Admin Login</a>
        <?php endif; ?>
    </div>
 
    <?php if ($message): ?>
        <div class="message"><?php echo htmlspecialchars($message); ?></div>
    <?php endif; ?>
 
    <?php if ($view_admin && isset($_SESSION['authenticated'])): ?>
        <h1>Admin Panel</h1>
        <?php if (empty($urls)): ?>
            <p>No entries found.</p>
        <?php else: ?>
            <table>
                <tr><th>Code</th><th>Original URL</th><th>Short URL</th><th>Actions</th></tr>
                <?php foreach ($urls as $code => $url): ?>
                <tr>
                    <td><?php echo htmlspecialchars($code); ?></td>
                    <td><a href="<?php echo htmlspecialchars($url); ?>" target="_blank"><?php echo htmlspecialchars($url); ?></a></td>
                    <td><a href="<?php echo $base_url . '?c=' . $code; ?>" target="_blank"><?php echo $base_url . '?c=' . $code; ?></a></td>
                    <td class="actions">
                        <a href="<?php echo $base_url . '?view=admin&delete=' . $code; ?>" onclick="return confirm('Delete <?php echo $code; ?>?');">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>
    <?php else: ?>
        <h1>Simple Flat-File URL Shortener</h1>
        <form method="post">
            <input type="url" name="url" placeholder="Enter URL to shorten" required>
            <input type="submit" value="Shorten">
        </form>
        <?php if ($short_url): ?>
            <div class="result">
                Short URL: <a href="<?php echo $short_url; ?>" target="_blank"><?php echo $short_url; ?></a>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</body>
</html>
narzedzia/php_url_short.txt · ostatnio zmienione: 2025/05/16 18:49 przez administrator