Skip to content

Creating your own Url shortener.

Good Night,

Here I will show you how to create your own url shortener.

First of all you need to create a table like this:

CREATE TABLE IF NOT EXISTS `urls` (
`uid` int(11) NOT NULL auto_increment,
`url` text default NULL,
`unique_chars` varchar(25) BINARY NOT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `unique_chars` (`unique_chars`)
);

This code was taken from Abhise in this post “Create your own tinyurl with php and mySQL” that was my bigest reference, from it I took some functions and update other ones to be more efficient. For an example I changed the field to BINARY so it be CASE SENSITIVE (aaaa different from AAAA)

The Abhise says to create many files, I particularly, created one file with all functions where I add all the functions and just called the functions in the files.

We need a fucntion to connect/disconnect to mysql

error_reporting(E_ALL);
$link;
$config;
function connect_db_lurl() {
global $link;
global $config;
$hostname = “localhost”;
$username = “USUARIO”;
$password = “SENHA”;
$dbname = “DATABASE”;
$link = mysql_connect($hostname, $username, $password); // Conecta ao mysql.
mysql_select_db($dbname) or die(“Unknown database!”); // Seleciona o Banco de dados.
$config[“domain”] = “http://seudominio.com”; // Define a configuração da URL inicial
}

function close_db_lurl() {
mysql_close(); // Fecha a conexão com o banco de dados
}

After this I created a function to redirect to the URL.

function redirect($url) {
header(“Location:”.$url); // Redireciona para a url.
}

Than I used the function from Abhise to generate the char sequence. (I add some chars to elevate the number of combinations

function generate_chars() {
$num_chars = 6; // Tamanho que você deseja as strings
$i = 0;
$my_keys = “123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”; // Caracteres que valem para formação de endereço
$keys_length = strlen($my_keys);
$url = “”;
while($i<$num_chars) { // Gera sequencia aleatoria $rand_num = mt_rand(1, $keys_length-1); $url .= $my_keys[$rand_num]; $i++; } return $url; }

Created a function to verify if the key is unique.

function isUnique($chars) {
global $link;
$q = “SELECT * FROM `urls` WHERE `unique_chars`='”.$chars.”‘”;
$r = mysql_query($q, $link); // Verifica se a chave é unica.
if( mysql_num_rows($r)>0 ) {
return false;
} else {
return true;
}
}

And other to verify if the URL is in DB

function isThere($url) {
global $link;
$q = “SELECT * FROM `urls` WHERE `url`='”.$url.”‘”;
$r = mysql_query($q); // Verifica se já existe a url
if(mysql_num_rows($r)>0) {
return true;
} else {
return false;
}
}

Function to create

function create() {
global $link;
global $config;
$chars = generate_chars(); // Gera sequencia de caracteres.

while(!isUnique($chars)){ // Verifica se é unico, se não for gera denovo.
$chars = generate_chars();
}

$url = $_GET[“u”]; // Pega o endereço que está em ?u=endereço
$url = trim($url); // Retira espaços em branco do inicio e do fim
$url = mysql_real_escape_string($url);

if(!isThere($url)) { // Caso não exista o endereço no banco.
$q = “INSERT INTO `urls` (url, unique_chars) VALUES (‘”.$url.”‘, ‘”.$chars.”‘)”;
$r = mysql_query($q, $link); // Insere o endereço
if(mysql_affected_rows()) {
$q = “SELECT * FROM `urls` WHERE `url`='”.$url.”‘”;
$r = mysql_query($q);
$row = mysql_fetch_row($r);
echo $config[“domain”].”/”.$row[2]; // Imprime endereço para acesso da nova url
} else {
echo “Desculpe, problemas com o banco de dados.”;
}
} else { // Caso já exista
$q = “SELECT * FROM `urls` WHERE `url` = ‘”.$url.”‘”;
$r = mysql_query($q); // Seleciona endereço para URL
$row = mysql_fetch_row($r);
echo $config[“domain”].”/”.$row[2]; // Imprime endereço para acesso da url.
}
}

Looking to the code I thought to create a function to get the url.

function take_lurl($lurl) {
global $link;
$q = “SELECT url FROM `urls` WHERE `unique_chars` = ‘”.$lurl.”‘”;
$r = mysql_query($q, $link); // Pega endereço original para tal string.
if(mysql_num_rows($r)>0) {
$info = mysql_fetch_array($r);
$url = $info[“url”];
} else {
echo “Sorry, link not found!”;
}
return $url;
}

Created the file “functions-little-url.php” with these functions.

index.php:

create.php:

We need to add some lines do .htaccess and enable mod_rewrite.


RewriteEngine On
RewriteRule ^([1-9a-zA-Z]*)$ index.php\?u=$1 [L]

I did this in my system that uses wordpress (that already uses mod_rewrite) so it work a little bit different. This is my .htaccess


RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f # Verifica se a página acessada não é um arquivo real
RewriteCond %{REQUEST_FILENAME} !-d# Verifica se a página acessada não é um diretório
RewriteRule ^([A-Za-z0-9]{6})$ /lurl/index.php?u=$1 [L] # Caso coincida com a expressão regular redirecione para /lurl/index.php?u=$1 onde /lurl/ é o diretório que está os meus arquivos de tiny-url e [L] indica que é a ultima instrução a ser executada.

# Caso não feche com a parte em cima continua nas regras “padrões” do WordPress
RewriteCond %{REQUEST_FILENAME} !-f # Verifica se a página acessada não é um arquivo real
RewriteCond %{REQUEST_FILENAME} !-d# Verifica se a página acessada não é um diretório
RewriteRule . /index.php [L]

(my URL shortener is inside /lurl/ directory but the redirect was done in matbra.com/XXXXXXX so it redirects to /lurl/

To create URLs acess create.php?u=ADDRESS

URL-Shortener

If you have any problem feel free to contact me.

Best Regards,
Matheus Bratfisch

References:
—- “Tiny Url”:
www.php.net
Wynia.org
htmlCenter
—- “Mod Rewrite”:
Apache Mod Rewrite

Published inAprendendoMySQLphp

45 Comments

  1. Joao Joao

    Pessoalmente acho melhor você pegar o auto_increment do Mysql e transformar o número inteiro em base alguma coisa. exemplo:

    <?php
    $de = 96408050;
    $str = dec2string($de, 36);
    $dec = string2dec($str, 36);

    echo ”
    de = $de
    str = $str
    dec = $dec
    “;

    function dec2string($decimal, $base)
    {
    global $error;

    // $charset = ‘0123456789abcdefgihjklmnopqrstuvwxyz’;
    // $charset = ‘23456789abcdefghjkmnpqrstuvwxyz’; // 31 = removed 0, o, i, L, 1 (one)
    $charset = ‘0123456789abcdefgihjklmnopqrstuvwxyz’;
    $charset = ‘0123456789’. // 10
    ‘abcdefghijklmnopqrstuvwxyz’. // 36
    ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’. // 62
    ‘_-;.,+~^@$()[]{}’; // 42
    $charset = ‘0123456789’. ‘abcdefghijklmnopqrstuvwxyz’;
    $ml = strlen($charset);
    $string = null;
    $base = (int)$base;
    if ($base $ml | $base == 10)
    {
    echo ‘BASE must be in the range 2-9 or 11-‘. $ml;
    exit;
    }
    $charset = substr($charset, 0, $base);
    if (!ereg(‘(^[0-9]{1,12}$)’, trim($decimal)))
    {
    $error[‘dec_input’] = ‘Value must be a positive integer’;
    return false;
    }
    while ($decimal > 0)
    {
    $decimal = (int)$decimal;
    $remainder = ($decimal % $base);
    $char = substr($charset, $remainder, 1);
    $string = “$char$string”;
    $decimal = ($decimal – $remainder) / $base;
    }
    return $string;
    }
    function string2dec ($string, $base)
    {
    global $error;

    // $charset = ‘23456789abcdefghjkmnpqrstuvwxyz’;
    // $charset = ‘0123456789abcdefgihjklmnopqrstuvwxyz’;
    $charset = ‘0123456789’. ‘abcdefghijklmnopqrstuvwxyz’;
    $ml = strlen($charset);
    $decimal = 0;
    $base = (int)$base;
    if ($base $ml | $base == 10)
    {
    echo ‘BASE must be in the range 2-9 or 11-‘.$ml;
    exit;
    }

    $charset = substr($charset, 0, $base);
    $string = trim($string);
    if (empty($string))
    {
    $error[] = ‘Input string is empty’;
    return false;
    }
    while ($string null)
    {
    $char = substr($string, 0, 1);
    $string = substr($string, 1);
    $pos = strpos($charset, $char);
    if ($pos === false)
    {
    $error[] = “Illegal character ($char) in INPUT string”;
    return false;
    }
    $decimal = ($decimal * $base) + $pos;
    }
    return $decimal;
    }

    // Call makeCksum once upon landing on the homepage
    function makeCksum()
    {
    $str = “”;
    for ($i=0;$i

  2. João,

    Realmente acredito que também seja uma ótima solução, provavelmente melhor que a que eu implementei no dia que fiz esse código já que a mesma não fica tentando criar pois em um banco de dados extenso a criação “aleatória” pode gerar inumeros valores repetidos caindo em algum tipo de loop “semi infinito”.

    Bom, para os próximos que forem ler esse tópico fica ai a dica do João, quem sabe assim que eu tiver um tempo pra mecher na implementação desse script (e pretendo fazer algumas modificações) eu adote está solução que também me parece mais viavél.

    Obrigado pela sua sugestão.

  3. […] Durante a programação também me lembrei que era necessário utilizar algumas regras de Rewritting para fazer o mesmo funcionar e eu estava esquecendo de frisar isso nos outros posts sobre “Tiny-URL”, provavelmente levando muitos usuarios a não conseguirem que o mesmo funcione. Editei os posts antigos colocando um PS, no final. Você pode ver o que deve ser feito no Mod Rewrite no primeiro post sobre este assunto, “Como criar o seu proprio Tiny-URL” […]

  4. Приветствую всех! Хотел поделиться простым лайфхаком по определению печенья в браузере. Часто бывает, что нужно незамедлительно найти отдельные файлы куки, чтобы понять кэшированными данными или стереть целевые cookie-файлы. Для этого следует задействовать специализированными программами и утилитами, которые существенно улучшают процесс.

    Когда захотите использовать что-то удобное, предлагаю ознакомиться с данный ресурс Поиск печенек , где досконально освещены методы определения и регулирования печеньем в многообразных браузерах. Это на самом деле рационализирует время и способствует точнее разбираться, что в частности сохраняется на личном устройстве. Полагаю, некто признает это ценным!

  5. Die Spielbank Garmisch-Partenkirchen, eingebettet in die malerische Alpenlandschaft, bietet eine einzigartige Glücksspielkulisse.
    Mit einer breiten Palette von Spielautomaten und einfachen Spielregeln bieten sie eine unterhaltsame Möglichkeit, das Glück herauszufordern. Sie bieten eine unkomplizierte Möglichkeit, das Glücksspiel zu genießen, ohne lange
    Wege auf sich nehmen zu müssen. Günstig im Zentrum gelegen, bietet es eine moderne und zugängliche Glücksspieloption für Städter und Besucher gleichermaßen. Auf haben wir im Laufe der Zeit ein übersichtliches Städtekonzept entwickelt.

    Die bayerische Hauptstadt München, als pulsierende Metropole bekannt,
    zieht nicht nur durch ihre kulturellen Schätze und Feste, sondern auch durch ein abwechslungsreiches Entertainment-Angebot in ihren Bann.
    Nach der Eröffnung vier weiterer Spielbanken verfügt jeder Regierungsbezirk über eine staatliche
    Spielbank mit Ausnahme Oberbayerns. Nicht mit Spielbanken versorgt waren die Regierungsbezirke Niederbayern, die Oberpfalz sowie Ober- und Mittelfranken.
    Die Vielfalt an Anbietern wie MunichPoker, IsarPoker oder der Poker-Bundesliga bietet für jeden das richtige Event.
    Diese Events finden häufig in kleineren, gemütlichen Locations statt.
    IsarPoker verbindet die Münchner Poker-Community und bietet
    eine Plattform für private Pokerabende und Turniere. Somit können sich auch die bayerischen Glücksspielhäuser nicht dem
    bundesweiten Trend entgegenstemmen.

    References:
    https://online-spielhallen.de/bizzo-casino-bonus-code-ihr-weg-zu-extra-gewinnen/

  6. Immer mittwochs spielst du Omaha Pot Limit mit einem Table Stake von 200 € bzw.

    Du kannst diese online jederzeit abrufen und sowohl die
    aktuellen Permanenzen des Tages als auch vergangener Jahre betrachten. Die US-amerikanische Version findest du unseren Erfahrungen zufolge an acht Spieltischen. Die Automatenspiele begrüßen dich nach dem Eintritt in das Esplanade Casino als erstes.

    Darüber hinaus stehen dir klassische Tischspiele wie Roulette,
    Blackjack und Poker zur Verfügung. So schreibt die Spielbank zum Beispiel für den Automatenbereich keine bestimmten Kleidungsstücke vor.

    Der Zutritt ins Automatenspiel ist während des gesamten Abends auch ohne gesondertes Silversterticket möglich.
    Sichern Sie sich Ihre Tickets noch heute und seien Sie
    Teil dieses fantastischen Events! Unsere exklusive Silvesterparty bietet Ihnen die perfekte Gelegenheit, ausgelassen zu feiern und gleichzeitig die
    Spannung des Spielangebots zu erleben. Direkt an der Außenalster gelegen, erfreuten sich die Gäste zur Eröffnung
    über Roulette, Black Jack & Baccarat an insgesamt 15 Spieltischen.
    Zentral gelegen, ist das Casino Steindamm im Erdgeschoss des Hotel „Graf Moltke“ untergebracht und damit zentrale Anlaufstelle für alle Glücksspielinteressierten eines der
    lebendigsten Viertels der Stadt.
    Bis auf Casino Poker wird hier die ganze Palette der Casinospiele zur Verfügung gestellt.
    Die größte Auswahl gibt es im Esplanade Casino, denn hier gibt es das volle Programm der Glücksspiele.

    Ein wenig mehr Auswahl bietet das Casino an der Reeperbahn. Alternativ bietet sich der
    Besuch in einem Blackjack Live Casino oder Roulette Live Casino an. So gibt es in den Spielbanken am Steindamm
    und in Mundsburg beispielsweise gar kein Roulette, Blackjack und Poker.

    References:
    https://online-spielhallen.de/vinyl-casino-deutschland-ihr-tor-zur-musikalischen-glucksspielwelt/

  7. Coba Over Under & Mix Parlay di Popdut8. Platform sportsbook resmi dengan keamanan terjamin dan deposit murah 10k.

    Buktikan analisis Anda dan menang besar sekarang juga!

  8. This doesn’t influence our evaluations of
    a casino or the order in which they are listed. Spins are usually tied to specific pokies and come
    with wagering requirements – typically 40x. These are typically smaller than welcome
    offers but add long-term value.
    If you lose your deposit, the bonus is activated and
    you can continue playing with bonus credits. A non-sticky casino bonus (sometimes
    called a “parachute bonus”) allows you to withdraw both your deposit and
    any winnings at any time. You can use the bonus money to play and meet the
    wagering requirements, but when you request
    a withdrawal, the bonus amount is deducted from
    your total balance. These bonuses often offer higher match percentages, bigger
    maximum bonus amounts, and exclusive perks. Cashback bonuses refund a percentage
    of your net losses as bonus cash over a specified period, giving
    you a second chance to play and win. Free spins are awarded on specific casino
    games, each spin valued at the minimum bet (e.g.,
    $0.10).
    The best gambling sites have the best online casino bonuses, right?
    We deliver everything you need to gamble like
    a boss – exclusive bonuses, slot games, new gambling sites, and much more.

    Also, you can check out the table of top 5 Australian online casinos for real money.
    These are gambling sites with live dealer sections where players can pay and get an immersive live casino experience from the comfort of their homes.

    References:
    https://blackcoin.co/13_vip-slots-casino-review-2022_rewrite_1/

  9. It is extremely frustrating to have bonus online casino credits expire, which is why I recommend finding the lowest play-through requirements possible if you’re a high roller. However, if you have to play through a large amount of bonus credits 30x or more within a limited amount of time, you might be better off choosing another online casino. If you enjoy the live dealer experience, make sure the online casino that you’re registering a new account with has live dealer blackjack and roulette. Some of the https://blackcoin.co/play-free-slots-%f0%9f%8e%b0-browse-19430-online-slot-games/ will have the RTP rate published or displayed when you’re gaming, and others will not. In general terms, a good RTP rate for online casinos is around 95% or above for slot titles. This is because online casinos do not have the extra overhead of property maintenance, licensed service staff, and other infrastructure that retail casinos are tasked with.
    If you haven’t already contacted them, but intend to, I suggest getting in touch with them either by email or live chat where available. If this applies to you, then I suggest that you continue with the communication that you have already started with the casino regarding your complaint. Online casino operators don’t like to see bad things being said about their casino, which is why in most cases, they will bend over backwards to get things sorted for you. Following these steps will put you on the quickest track to getting your issue resolved directly with the casino.

  10. All of these offers have wagering requirements ranging from 30x-40x (except for
    the cashback), and each one requires a different bonus
    code. There’s also a 5-tiered high roller bonus worth up to A$50,000 and 780 free spins, but the minimum deposit to qualify for each part of the bonus is $500.
    This welcome offer covers five deposits in total, maxing out at
    A$5,000 + 350 free spins.
    The best online casinos in Australia give you thousands of pokies to explore, smooth payouts in AUD,
    and heaps of bonus offers. Here’s a breakdown of
    the main types you’ll encounter while exploring real money
    online casinos Australia trusts These online casino table games suit players who prefer strategy
    over chance, with blackjack and baccarat offering some of the highest payout rates.
    They’re great for players who don’t trust crypto or
    prefer linking to their bank.However, withdrawals can take days, and banks may flag gambling transactions.Many best
    online casinos like King Johnnie let you mix and
    match.
    20 free spins are available on Super Diamond Wild or Pinata Fiesta, and will be credited to
    your account the day following your deposit. 40x wagering requirements on bonus and FS.
    Max bonus 120 EUR and 120 Free Spins. Join Pribet Casino with minimum €20 deposit requirement for all 4 deals.

    References:
    https://blackcoin.co/popular-variations-of-casino-slots-game-rules-and-descriptions/

Leave a Reply

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