Sharing is caring!

Building a URL shortener service is an excellent project to learn PHP and practice database operations. Here’s a step-by-step guide to help you get started:

  1. Database Setup:
    • Create a MySQL database to store the URLs and click tracking data.
    • Create a table to store the URL mappings, including columns like id, long_url, short_code, and clicks.
// Database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

$conn = new mysqli($servername, $username, $password, $dbname);
  1. URL Shortening Logic:
    • Design a form where users can input a long URL to be shortened.
    • Validate the input URL and generate a unique short code for it. You can use a combination of alphanumeric characters or implement a hashing algorithm.
    • Store the long URL, short code, and initial click count in the database.
  2. URL Redirection:
    • Set up a PHP script that will handle the redirection from the short URL to the long URL.
    • Retrieve the long URL associated with the short code from the database.
    • Update the click count for the corresponding URL in the database.
    • Use the header() function to redirect the user to the long URL.
  3. Analytics and Click Tracking:
    • Create a separate page to display analytics for the shortened URLs.
    • Retrieve the click count and other relevant information from the database.
    • Use PHP to generate charts or tables to present the analytics in a visually appealing manner.
  4. Enhancements:
    • Implement additional features like expiration dates for shortened URLs, custom short codes, and password-protected URLs.
    • Consider adding security measures to prevent abuse, such as CAPTCHA verification.
// Function to generate a unique short code
function generateShortCode($length = 6) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $code = '';

    for ($i = 0; $i < $length; $i++) {
        $code .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $code;
}

// Shorten URL
if (isset($_POST['submit'])) {
    $longUrl = $_POST['longUrl'];
    $shortCode = generateShortCode();

    // Insert the URL mapping into the database
    $sql = "INSERT INTO urls (long_url, short_code, clicks) VALUES ('$longUrl', '$shortCode', 0)";
    $conn->query($sql);
}

// Redirect shortened URL to long URL
if (isset($_GET['code'])) {
    $shortCode = $_GET['code'];

    // Retrieve the long URL associated with the short code
    $sql = "SELECT long_url FROM urls WHERE short_code = '$shortCode'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $longUrl = $row['long_url'];

        // Increment the click count
        $sql = "UPDATE urls SET clicks = clicks + 1 WHERE short_code = '$shortCode'";
        $conn->query($sql);

        // Redirect to the long URL
        header("Location: $longUrl");
        exit();
    } else {
        echo "Invalid short URL";
    }
}

// Display analytics
$sql = "SELECT * FROM urls";
$result = $conn->query($sql);

And if you want to add HTML here is the code:

<!-- HTML Form -->
<form method="POST" action="">
    <input type="text" name="longUrl" placeholder="Enter a long URL" required>
    <input type="submit" name="submit" value="Shorten">
</form>

<!-- Display shortened URLs and click counts -->
<table>
    <tr>
        <th>Short URL</th>
        <th>Long URL</th>
        <th>Clicks</th>
    </tr>
    <?php
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<tr>";
            echo "<td>https://yourdomain.com/?code=" . $row['short_code'] . "</td>";
            echo "<td>" . $row['long_url'] . "</td>";
            echo "<td>" . $row['clicks'] . "</td>";
            echo "</tr>";
        }
    }
    ?>
</table>

Make sure to replace 'your_username', 'your_password', and 'your_database_name' with your actual database credentials. Also, update the form action and the table display URLs with your domain or desired URL structure.

Remember to create a MySQL table named urls with the necessary columns (long_url, short_code, and clicks) before running the code.

Categories: PHP

3 Comments

umemps.org · August 5, 2023 at 9:50 pm

Oh my goodness! Awesome article dude! Thank you, However I am having difficulties
with your RSS. I don’t understand why I cannot subscribe to it.
Is there anybody getting similar RSS issues? Anyone who knows the answer will you kindly respond?
Thanx!!

David Song · September 6, 2023 at 10:39 pm

Hello, We are very interested in learning more about big data.

esim_exsa · September 27, 2023 at 10:58 am

Thank you

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *