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:
ob_start(); //Inicia Buffer de saida include("functions-little-url.php"); connect_db_lurl(); $lurl = $_GET["u"]; //Sequencia de caracteres $url = take_lurl($lurl); redirect($url); close_db_lurl(); ob_end_flush(); // Fecha buffer de saida ?>
create.php:
include("functions-little-url.php"); connect_db_lurl(); create(); close_db_lurl(); ?>
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
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
Все самое свежее здесь: https://kapremontufa.ru
Только лучшие материалы: https://remontokonufa.ru
Больше на нашем сайте: https://okna-domostroy.ru
monopoly big bazaar live result monopoly big bazaar live result .
casino scores monopoly big baller today live casino scores monopoly big baller today live .
Hey there, You have done a fantastic job. I?ll definitely digg it and personally recommend to my friends. I am confident they will be benefited from this web site.
monopoly live score india https://monopoly-live-in.com/ .
monopoly big baller live score monopoly big baller live score .
khelo24bet monopoly big baller results today live khelo24bet monopoly big baller results today live .
послуги ремонту квартир ремонт квартир ключ ціна
послуги ремонту квартир ремонт квартир недорого
monopoly live casinos monopoly live casinos .
Can I just say what a relief to find somebody who really knows what theyre speaking about on the internet. You positively know learn how to carry a problem to gentle and make it important. Extra individuals need to read this and understand this facet of the story. I cant believe youre not more fashionable since you definitely have the gift.
перевозка автомобилей дешево перевозка авто москва стоимость
Looking for the Best Drive School of Motoring? Get expert driving lessons at best driving school for affordable and quality driving instruction.
перевозка авто услуги перевозки машин
Things Worth Watching: שירותי נערות ליווי
Обновлено сегодня: https://spainslov.ru/site/word/word/%D0%91%D0%9E%D0%A1%D0%9E%D0%99
Bettors gain an advantage by accurately seeing what their bets could yield.
free bet calculator https://single-betcalculator.com/
free bet calculator single https://www.singlebet-calculator.uk .
double calculator https://single-bet-calculator-free.uk/bet-calculator/double/
With insights into expected winnings, bettors can better manage their stakes.
bet double https://single-betcalculator.uk/bet-calculator/double/
Wow, superb blog layout! How long have you been blogging for? you made blogging glance easy. The overall look of your website is wonderful, let alone the content!
Seks is breed beschikbaar op speciale platforms voor
volwassenen. Kies voor gegarandeerde bronnen voor veiligheid.
Here is my homepage – BUY VIAGRA ONLINE
санитарная служба дезинфекции сайт
crazy time deno https://crazy-time-stats.com/
crazy time starts crazy time starts.
crazy time stats https://crazy-time-gratis.com/
crazy time online casino https://crazy-time-stats.com/
Do you love excitement? https://jerseysbeststore.com/glossary offers premium pre-match and live sports betting, as well as a legal online casino. Try your luck on modern slots, table games, or with live dealers. We guarantee complete data security, fair results, and 24/7 player support.
лента стальная мягкая лента стальная гост цена
bitcoin video poker tips bitcoin video poker tips .
crazy time game crazy time game .
monopoly live casino https://monopoly-casino-in.com/
monopoly live game tracker monopoly live game tracker.
win bitcoin playing poker win bitcoin playing poker .
888starz.bet https://888starzuz4.com/
bitcoin poker spielen bitcoin poker spielen .
888strz https://888starzuz1.com/
рабочее зеркало 888starz https://888starzuz2.com/
Рекомендации по прохождению
секс игрушки купить
8 starz https://justpaste.me/2tgm1/
Nieuwste adult websites brengen innovatieve inhoud voor volwassen entertainment.
Ontdek gegarandeerde porno hubs voor een moderne ervaring.
Here is my web site BUY CONCERTA ONLINE
салон тату и пирсинга тату салон питер
салон татуировок тату https://taty-salon-spb.ru
888starz https://dronesimpro.com/stmt-blb-lkzynw-br-lntrnt-l-888starz-khdm-ry-fy-msr/
monopoly big brother https://monopolyy.live/
I was recommended this website by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem. You’re incredible! Thanks!
solana nft casino https://solcasinodeutschland.de/
bestes solana online casino https://solkryptocasino.de/