Creating a Link Shortener Using Backend PHP

Tiempo de lectura: < 1 minuto

We will learn today how to create a link shortener for our back end using a simple PHP script.

City impressive - pexels

We will create our shortener, we can call it link.php

<?php // Cabecera header("Access-Control-Allow-Origin: *"); date_default_timezone_set("Europe/Madrid"); //Anti Bots if (preg_match('/bot|crawl|spider|preview/i', $userAgent)) { // No registrar bots header("Location: $target", true, 302); exit; } // Recoger slug $slug = $_GET['slug'] ?? null; $url= $_GET['url'] ?? null; $links = [ 'custom_link_1' => 'https://www.google.es', 'custom_link_2' => 'https://www.yahoo.com', 'url' => urldecode($url) ]; if (!$slug || !isset($links[$slug])) { http_response_code(404); echo "Link not found"; exit; } $target = $links[$slug]; // Datos básicos del clic $referer = $_SERVER['HTTP_REFERER'] ?? 'Directo'; $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'; $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; $timestamp = date('Y-m-d H:i:s'); // Registrar clic (modo simple: archivo log) $log = sprintf("[%s] %s | %s | %s | %s\n", $timestamp, $slug, $ip, $referer, $userAgent); file_put_contents('clicks.log', $log, FILE_APPEND); // Redirigir al destino header("Location: $target", true, 302); exit; 

We will do the following:

To use it:

https://yourdomain.com/link?tag=custom_link_1 https://yourdomain.com/link?tag=url&url=https://custom_url.com

Leave a Comment