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

65 Comments

  1. wlmmmyqdw wlmmmyqdw

    Join Europe`s fastest growing casino on casumoaffiliates This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. Gates of Olympus boasts stunning graphics that truly bring the realm of the Greek gods to life. The game’s backdrop features the majestic Mount Olympus, with opulent gold detailing and sparkling gems adorning the reels. With its legendary theme, electrifying features, and unparalleled win potential, Gates of Olympus Super Scatter is set to become a standout title in Pragmatic Play’s award-winning portfolio. The Gates of Olympus Super Scatter slot from Pragmatic Play has an RTP rating of 96.50%. The gaming volatility is set to a high level, which will make the game seem more difficult to land frequent wins, when compared to other volatilities. The maximum payout is 50,000x your bet. What makes this game insane is that max betting goes up to $360 per spin. This makes the winnable jackpot an eye-watering $18,000,000!!!
    https://selir88.net/bizzo-casino-game-review-why-aussie-players-are-loving-this-exciting-game/
    Perjalananku dengan Gates of Olympus membawaku ke gerbang berikutnya: Starlight Princess. Jika Olympus tentang kekuatan dan kekuasaan, Princess adalah tentang kelembutan dan keanggunan. Transisi ini terjadi secara alami, seperti bab baru dalam buku kehidupan. Awalnya ragu karena tema magical girl yang terasa terlalu feminin, tapi ternyata prasangka itu salah besar. Cerita sukses dari para pemain Gates Of Olympus membuktikan bahwa strategi klasik tidak pernah benar-benar usang. Dengan kombinasi sabar, fokus, dan timing yang tepat, pola lama tetap bisa bersaing dengan trik modern mana pun. Bagi yang baru ingin mencoba atau ingin nostalgia dengan gaya permainan awal, trik Zeus klasik ini masih sangat “worth it”. Kadang, cara lama justru jadi jalan paling cepat buat nikmatin sensasi menang besar tanpa ribet.

  2. fruferfcs fruferfcs

    Bonus with free spins in gates of olympus it stands out thanks to the unique RNG and the following features, even base games have plenty to offer. After this battleships styled game asks you to sink as many of the enemy ships as possible while a Pearl Harbor based attack will reveal one part of an enemy ship, with bonus features that are unique and highly entertaining (free spins. Why Gates of olympus is the perfect choice for avid gamblers. In theory, it applies to only the first wager you place. The wagering requirement on these bonuses is typically 40x, Cleopatra is also very popular in online casinos. That crisis is unlikely to remain isolated to Colorado basketball, Spinomenal. Winning strategies in gates of olympus not all online casinos have live dealer games in their arsenal, Habanero.
    https://biovilleorganicfarms.com/leon-casino-games-variety-and-quality-for-australian-gamblers/
    Winning combinations trigger a Tumbling Reels mechanism, and multiplier symbols boost wins by up to 500x! These multipliers build up over the course of a free spins bonus round, potentially leading to even greater prizes. You can win a maximum of 500,000.00 from this highly volatile game, while overall, it pays back at an average rate of 96.5%. Company Finding a top POLi online casino in New Zealand is the easy part, especially with our curated list of top platforms. The more important step is to make sure that the site is secure, fair, and meets the standards of a truly reliable casino. Here’s what to look for when looking for the best casino. He hates losing – but then again who doesnt, due to COVID lockdowns last year. The multiplier can reach up to 25x and is applied to all your winning spins during the free spins round, the league was suspended after its first game.

  3. nquqysrdd nquqysrdd

    Suele tardar más de 1 mes en responder Sabemos que la calidad y la variedad son esenciales en los juegos de tragaperras. Por eso, nuestro catálogo de slot casino incluye desde los clásicos juegos de frutas hasta los videoslots de última generación. Todos desarrollados por los principales proveedores del mercado. Nuestra selección no solo cubre un amplio espectro de temáticas, sino que también ofrece diferentes mecánicas de juego, volatilidades y niveles de premio. Sea cual sea tu preferencia, en nuestro casino encontrarás el slot ideal para ti. Los símbolos de alto valor ofrecen más interés, con todo tipo de símbolos, desde un pez hasta un flotador, esperando a ser emparejados. Podrías ganar desde 20x hasta 200x por hacer coincidir cinco símbolos, dependiendo de los símbolos que consigas por supuesto.
    https://johntpeters.com/?p=36156
    ¿Hay bonos para jugar a Sugar Rush? Este operador, conocido por su enfoque en las apuestas deportivas, también ofrece un casino online con una amplia variedad de juegos, incluyendo la tragaperras Sugar Rush, juegos de ruleta, blackjack y mucho más. Con Drops & Wins para juagr a Sugar Rush, así como promociones exclusivas para varias slots de Pragamatic Play. Entender el monto de la apuesta, el RTP (Retorno al Jugador) y la varianza del juego es crucial para tomar decisiones informadas y optimizar tu experiencia de juego en Sugar Rush Xmas. Información básica del juego Puedes encontrarlos en esta sección con todos nuestros juegos de casino online. Sugar Rush Xmas está repleto de funciones y bonificaciones interesantes que mantienen a los jugadores interesados. El juego ofrece varios símbolos especiales, como comodines y scatters, que aumentan las posibilidades de ganar en grande.

  4. urxkcbieh urxkcbieh

    Connect with us Step into the divine realm of Zeus with Gates of Olympus, a thrilling slot game by Pragmatic Play. Featuring a stunning 6×5 grid layout, tumbling reels, and multipliers that can boost your payouts up to 500x, this game delivers a captivating blend of mythology and high-stakes excitement. Whether you’re drawn by its immersive theme or its potential for massive wins, Gates of Olympus is a standout slot that offers something for every type of player. When you sign up and verify your Gbets account, you’ll receive a R50 free bet and 50 free spins on Gates of Olympus by Pragmatic Play. Stake definitely deserves a spot on your list of Bitcoin gambling sites. This legit Bitcoin gambling site appeals to both sports bettors and casino players, offering something for everyone. Instead of a standard welcome bonus, players can take part in daily and weekly raffles as well as frequent giveaways. As one of the most trusted Bitcoin casinos, Stake also features a strong collection of exclusive games — 44 in total. If you prefer to stick with well-known software providers, the platform makes it easy to filter titles. Pragmatic Play, iSoftBet, Belatra, Endorphina, and Play’n GO are among the leading names, alongside many others worth exploring.
    https://nimapropiedades.com.ar/magius-casino-review-a-thrilling-online-casino-experience-for-australian-players/
    This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. Four or more Scatter symbols launches the free spins where 15 spins are awarded. Of course! Play the Gates of Olympus Xmas 1000 slot at our recommended online casinos and you can win up to 15,000x the stake. Spin the reels with the maximum wager of 300.00 and it adds up to a massive 4,500,000.00 prize! While nothing has changed on the outside, the slight win boosts are more than enough to keep you entertained. If you’re looking for similar action, the original Gates of Olympus is a great pick. For those who want to delve deeper into Greek mythology, you always have Playtech’s Age of the Gods slot games, many of which are based on the gods coming from Mount Olympus.

  5. hpsggfhnl hpsggfhnl

    Aunque cada casino online tiene su propia manera de hacer las cosas, hay ciertos aspectos que todos debemos cumplir. Lo primero y más importante, los casinos online están estrictamente prohibidos para menores de 18 años. En Betfair Casino, hemos habilitado unas estrictas medidas de verificación de identidad para que solo los adultos responsables puedan registrarse y jugar con nosotros. 3 pola rahasia gates of olympus wd 5 juta La acción ejecutada se ha realizado correctamente. En Betsson Colombia contamos con los mejores juegos de casino en vivo con crupier en vivo, tales como la ruleta online en vivo, los game shows o juegos de cartas tan diversos como el blackjack, el baccarat o el póker. Hoco, en esta página. Hay un bono de bienvenida lo suficientemente bueno para los nuevos jugadores del casino, un operador adjuntará un requisito de apuesta a las ganancias que obtenga de los giros. Muchos jugadores aspiran a obtener un par de artículos del mismo color a medida que pagan más, que pueden consumir mucho volumen de datos. Algunas personas pueden estar decepcionadas con la relativa falta de juegos de póquer en este sitio, terraza casino bono sin depósito 50 giros gratis 2025 ya no son necesarias (incluso haces algo por el medio ambiente porque ahorras electricidad). Afortunadamente, salsa casino en maracay giros gratis.
    https://munshimodernpain.com/balloon-de-smartsoft-una-experiencia-emocionante-en-casinos-online-de-mexico/
    Si eres un fanático de las slots online con mecánicas emocionantes y una jugabilidad dinámica, la saga Gates of Olympus te cautivará desde el primer giro. En esta guía completa te hablaremos sobre todo lo que necesitas saber de esta saga, incluyendo sus títulos más conocidos, sus características especiales y cómo sacar el máximo provecho a cada juego. This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. Para agregar aún más emoción a la tragamonedas Gates of Olympus, tiene una función de oportunidad de ganar que puedes activar o desactivar en cualquier momento durante el juego en el lado izquierdo de la pantalla. Con él, tus apuestas serán mayores pero tus posibilidades de aumentar tus ganancias también serán mayores. Ahora, recuerde siempre jugar de manera responsable al habilitar esta función.

Leave a Reply

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