How to make your Own Tiny URL using PHP and MySQLi Database

Creating a short URL typically involves generating a unique identifier for the long URL and then mapping that identifier to the long URL in a database or some data structure. Here's a basic example of how you can create a simple PHP script to generate a short URL using PHP: 

<?php
// Database connection (You'll need to set up your own database)
$servername = "your_server";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the long URL from the form submission
    $longURL = $_POST["long_url"];

    // Generate a unique identifier (you can use a library for this)
    $shortIdentifier = substr(md5(uniqid(rand(), true)), 0, 6);

    // Insert the mapping into the database
    $sql = "INSERT INTO short_urls (short_id, long_url) VALUES ('$shortIdentifier', '$longURL')";

    if ($conn->query($sql) === TRUE) {
        $shortURL = "http://your_domain/$shortIdentifier";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>URL Shortener</title>
</head>
<body>
    <h1>URL Shortener</h1>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <label for="long_url">Enter a long URL:</label>
        <input type="text" name="long_url" id="long_url" required>
        <input type="submit" value="Shorten">
    </form>
    <?php
    if (isset($shortURL)) {
        echo "Short URL: <a href='$shortURL'>$shortURL</a>";
    }
    ?>
</body>
</html>

In this code:

  1. The form allows users to enter a long URL.

  2. When the form is submitted, the PHP code at the top of the file processes the form data.

  3. It generates a unique short identifier, inserts the mapping into the database, and then displays the resulting short URL.

Make sure to replace "your_server", "your_username", "your_password", "your_database", and "your_domain" with your actual database and domain information. Also, consider using a more robust method to generate short identifiers and handle errors more gracefully in a production environment.


To make the generated short URL redirect to the corresponding long URL, you need to implement a redirection mechanism. You can do this by creating a PHP script that reads the short identifier from the URL, looks up the corresponding long URL in the database, and performs the redirection.

Here's an example of how you can modify your code to enable URL redirection:

  1. Create a new PHP script (e.g., redirect.php) that will handle URL redirection:
<?php
// Database connection (You'll need to set up your own database)
$servername = "your_server";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get the short identifier from the URL
$shortIdentifier = $_GET["short_id"];

// Look up the corresponding long URL in the database
$sql = "SELECT long_url FROM short_urls WHERE short_id = '$shortIdentifier'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $longURL = $row["long_url"];
    // Redirect to the long URL
    header("Location: $longURL");
    exit;
} else {
    echo "Short URL not found.";
}

$conn->close();
?>

Modify your previous code to display the short URL correctly with the redirect.php script as the action URL for the form:

<!DOCTYPE html>
<html>
<head>
    <title>URL Shortener</title>
</head>
<body>
    <h1>URL Shortener</h1>
    <form method="post" action="process.php"> <!-- Change "process.php" to the actual file name of your form processing script -->
        <label for="long_url">Enter a long URL:</label>
        <input type="text" name="long_url" id="long_url" required>
        <input type="submit" value="Shorten">
    </form>
    <?php
    if (isset($shortURL)) {
        echo "Short URL: <a href='$shortURL'>$shortURL</a>";
    }
    ?>
</body>
</html>
  1. When you create the short URL in your form, make sure to change the form action to point to your form processing script (e.g., process.php), and set the method attribute to "POST". Also, ensure that the form's action attribute matches the script name you've created for redirection (redirect.php).

Now, when you copy and paste the short URL, it will redirect to the corresponding long URL.


To redirect a short URL to its corresponding long URL, you can use the header function in PHP. Here's how you can create a simple PHP script to handle the redirection:

  1. Create a new PHP file, let's call it redirect.php, and place it on your server. This script will handle the redirection.
<?php
// Database connection (You'll need to set up your own database)
$servername = "your_server";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get the short identifier from the URL
$shortIdentifier = $_GET["short_id"];

// Look up the corresponding long URL in the database
$sql = "SELECT long_url FROM short_urls WHERE short_id = '$shortIdentifier'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $longURL = $row["long_url"];
    // Redirect to the long URL
    header("Location: $longURL");
    exit;
} else {
    echo "Short URL not found.";
}

$conn->close();
?>
  1. Modify the way you create short URLs in your original form processing code. When you generate the short URL, you should make it link to your redirect.php script with the short identifier as a parameter. Here's an example:

In your original form processing code:

// After you generate the short URL, set it as a link
$shortURL = "http://your_domain/redirect.php?short_id=$shortIdentifier";

// Display the short URL as a link
echo "Short URL: <a href='$shortURL'>$shortURL</a>";

Now, when you click on the short URL, it will be redirected to the corresponding long URL.

Make sure to replace "your_server", "your_username", "your_password", "your_database", and "your_domain" with your actual database and domain information. Additionally, ensure that you have set up the database and have the necessary table (short_urls) to store the mappings.

 

 

Related Articles

- All From ChatGPT
PLG_GSPEECH_SPEECH_BLOCK_TITLE