Link shortner Project

Here is an example of how you could write a URL shortening service in PHP:

<?php

// Make sure to connect to your database here

// Check if the form has been submitted
if (isset($_POST['submit'])) {
  // Get the original URL from the form
  $original_url = $_POST['original_url'];

  // Generate a unique short code for the URL
  $short_code = generateUniqueShortCode();

  // Insert the original URL and short code into the database
  $sql = "INSERT INTO url_shortener (original_url, short_code) VALUES (?, ?)";
  $stmt = $conn->prepare($sql);
  $stmt->bind_param("ss", $original_url, $short_code);
  $stmt->execute();

  // Redirect to the shortened URL
  header("Location: http://example.com/$short_code");
  exit;
}

function generateUniqueShortCode() {
  // Generate a random string of characters
  $short_code = generateRandomString();

  // Check if the generated short code is already in use in the database
  $sql = "SELECT * FROM url_shortener WHERE short_code = ?";
  $stmt = $conn->prepare($sql);
  $stmt->bind_param("s", $short_code);
  $stmt->execute();
  $result = $stmt->get_result();

  // If the short code is already in use, generate a new one and check again
  if ($result->num_rows > 0) {
    generateUniqueShortCode();
  }

  return $short_code;
}

function generateRandomString($length = 6) {
  $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  $characters_length = strlen($characters);
  $random_string = '';
  for ($i = 0; $i < $length; $i++) {
    $random_string .= $characters[rand(0, $characters_length - 1)];
  }
  return $random_string;
}

This code will generate a unique short code for a given URL, insert the original URL and short code into a database, and redirect the user to the shortened URL.

You will need to modify this code to fit your specific needs and make sure to connect to your database before trying to execute any database queries.

Leave a Comment