Ir ao conteúdo

Criando seu Proprio Tiny-URL.

Boa noite a todos,

Ontem pela madrugada estava pensando no Twitter e que ele reduz urls grandes automaticamente para um sistema escolhidos por eles. Então, estava a pensar em como fazer o meu próprio sistema criação de urls pequenas (tiny url) e pesquisei um pouco no Google. Achei várias referências que utilizei como base para elaboração do meu e os links das mesmas você poderá encontrar no final deste post.

Primeiramente você deve criar uma tabela em seu banco de dados com as seguintes características:

# 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`)
# );

Este código foi pego do Abhise no seu post “Create your own tinyurl with php and mySQL” que foi minha maior referência, da mesma peguei várias funções mas realizei algumas alterações para melhor eficiência e também tradução para você. Como no código acima foi adicionado o ‘BINARY’ para o unique reconhecer diferença entre AAAA e aaaa, por exemplo.

O Abhise diz para criarmos tais e tais arquivos, eu particularmente, criei um arquivo de funções onde adicionei as diversas funções utilizadas e simplesmente chamei as mesmas nos seus respectivos arquivos.

—- Para ler o artigo inteiro acesse o link abaixo.

Inicialmente precisamos de uma função para conectar/desconectar do mysql e também adicionei algumas variáveis e “diretivas”

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
}

Segundo passo foi criar uma função para redirecionamento, ou seja, uma função que redirecionasse para URL original

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

Logo em seguida utilizei a função já criada por Abhise para gerar a sequencia de caracteres. (Adicionei algumas letras que ele não estava utilizando elevando assim muito a quantidade de combinações possíveis)

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; }

Utilizamos também um método para verificar se a chave é única:

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;
}
}

E outro para verificar se a URL já existe no banco de dados:

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;
}
}

Por fim, a função para gerar as urls:

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.
}
}

Olhando o código algum tempo depois resolvi criar outra função para Pegar o endereço:

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;
}

Criei o arquivo “functions-little-url.php” com os códigos anteriores e os demais arquivos dessa maneira:

index.php:

create.php:

Até aqui tranquilo, logo em seguida devemos adicionar o Mod_Rewrite no Apache e adicionar as seguintes linhas no .htaccess


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

Eu fiz o meu dessa maneira, como foi descrito nas referências, realizando algumas modificações. Tudo funcionou bem.

Como eu utilizo o sistema wordpress e gostaria de utilizar o mesmo (que já usava mod_rewrite) junto dessa minha nova funcionalidade tive que pesquisar mais sobre este módulo para apache. Então caso você deseje utilizar este sistema junto ao seu sistema WordPress faça da seguinte maneira:


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]

Para criar URLs acesse o endereço create.php?u=ENDEREÇO_DO_SITE
Para acessar URLs o arquivo index.php cuidara disso para você.

Você pode baixar estes arquivos de Como criar seu proprio sistema de TinyURL aqui.

Qualquer dúvida, sinta-se a vontade para entrar em contato comigo. E em breve estou pensando em disponibilizar esse “compressor” de URL como um serviço do meu blog. Lembrando que você não deve ter pastas com nomes do mesmo tamanho que o utilizado pelo L-Url.

Abraço a todos,
Matheus Bratfisch

PS: Eu tinha feito algo mais bonito, com Objetos e tudo mais, porém após ter feito os códigos e tentar testar descobri que o meu PHP não estava atualizado, então assim que eu atualizar o mesmo eu testo e posto as modificações para você.

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

Publicado emAprendendoMySQLphp

903 Comentários

  1. Been using Tenobet for February, and I suppose I’ve got a fair bit of experience to actually comment. Came across it via a mate who was after a site with proper game coverage without all the affordability checks you run into now on the regulated UK ones. Worth saying up front: this isn’t UKGC licensed and it’s not on the GamStop scheme, which will matter to some of you a lot.

    Lobby’s pretty huge — roughly 3,000+ titles last I looked, with the names you’d want all turn up: Pragmatic Play, Net Ent, Play’n GO, Big Time Gaming, Betsoft, Microgaming. Personally I rinse Gates of Olympus and Sweet Bonanza, both load quick in browser. Live dealer’s Evolution, so it’s exactly what you expect — real croupiers, Crazy Time and Lightning Roulette for a change of pace. They do sports as well, and it gets a bit of use from me for the football, nothing special.

    Bonus-wise is a 100% match to ?125 and 100 spins thrown in, and you need the code JOIN002 — I nearly forgot it the first time. Read the wagering before depositing, the requirement is not amazing but not predatory either. No no-deposit freebie that I could find. For the what’s running currently, they’re listed at tenobet before you sign up. Minimum deposit is ?10, standard stuff, the form took maybe two minutes.

    Money side’s been the better half in my experience. Cards work, e-wallets like Skrill and Neteller are there, and crypto if you prefer. My Skrill cashouts have landed in under 24 hours; Visa took a bit longer. The one thing that annoyed me was the verification — they took 36-48 hours to clear my documents, and my first withdrawal just sat there the whole time. Nothing shady about it, but a bit of a wait.

    Couple of niggles: they don’t have an app, so you’re on browser only. It’s responsive enough on Android though an app would be nicer. The login is occasionally sluggish in the evenings. Support’s live chat, English, decent, though the first replies feel a bit scripted. Ask a specific question and someone competent turns up.

  2. Been punting on Tenobet since about March, and I suppose I have enough experience to actually comment. Stumbled on it through a mate who wanted somewhere with decent game coverage without all the affordability checks you see everywhere now on the UK licensed sites. Should flag early: this isn’t UK Gambling Commission licensed and it’s not on the GamStop scheme, and that will matter to some of you a lot.

    Game selection’s genuinely big — somewhere around 4,000+ games by my count, with the providers that matter are all there: Pragmatic, Net Ent, Play’n GO, BTG, Yggdrasil, Microgaming. I mostly stick to Sweet Bonanza plus Book of Dead, which both run fine on mobile browser. Live dealer’s Evolution, which means what you’re getting — actual dealers, Crazy Time for a change of pace. Sports betting’s bolted on as well, which I’ve dabbled in on footy, it’s fine, nothing more.

    Bonus-wise it’s a 100% match to ?125 and 100 free spins, you’ll want the code JOIN002 or it won’t trigger. Read the wagering before you commit, the requirement is not the loosest either. There’s no no-deposit bonus unfortunately. For the the live offers, have a look at tenobet casino rather than taking my word for it. Min deposit’s ?10, standard stuff, signing up took under five minutes.

    Payments have been generally fine in my experience. Visa and Mastercard work, e-wallets like Skrill and Neteller are there, and crypto if you prefer. My Skrill cashouts have come through within a day; card payouts took a bit longer. The one thing that annoyed me was KYC — took a day and a half to verify me, which held up the first payout just sat there until that cleared. Not dodgy, but slow.

    Couple of niggles: no native app, so you’re on browser only. Works fine on my iPhone but I’d prefer a proper app. The login can be a bit slow around weekend evenings. Live chat at Tenobet is English-speaking and reasonably quick, but the first replies read like templates. Ask a specific question and they sort it.

  3. I’ve been playing at Tenobet since about the spring, so I reckon I have enough experience to give an honest take. Stumbled on it through a mate who was chasing somewhere with half-decent lobby depth without the usual affordability checks you run into now on the UK licensed sites. Should flag early: it’s not UK Gambling Commission licensed and it isn’t on the GamStop scheme, which is either the point or a dealbreaker.

    The lobby is genuinely big — roughly 3,500+ slots last I looked, and the usual heavy hitters all turn up: Pragmatic, Net Ent, Play n GO, Big Time Gaming, Betsoft, Microgaming. Mainly I stick to Sweet Bonanza and Gates of Olympus, which both behave properly in browser. The live rooms are Evolution, which means exactly what you expect — proper croupiers, Crazy Time and Lightning Roulette if that’s your thing. There’s a sportsbook too, and it I’ve dabbled in for Premier League, decent odds, nothing groundbreaking.

    Bonus-wise it’s 100% up to ?125 with 100 free spins, you have to use the promo code JOIN002 or it won’t trigger. Check the playthrough first, the requirement is fairly standard either. There’s no no-deposit bonus that I could find. To check current promos, they’re listed at tenobet reviews if you’re curious. Min deposit’s ?10, registration took about three minutes.

    Payments have been generally fine for me. Visa/Mastercard go through, e-wallets like Skrill and Neteller are there, Bitcoin and a few other coins for anyone who wants that. E-wallet withdrawals have landed same day twice; cards were slower, 3-4 days. My main gripe was the verification — it took 36-48 hours to verify me, which held up the first payout just sat there the whole time. Not dodgy, but slower than I’d like.

    Few more things: they don’t have an app, which means browser only. Works fine on Android but I do miss having one. Logging in is occasionally sluggish in the evenings. Live chat at Tenobet is fine — maybe five minutes to get a human, though the opening messages are copy-paste. Ask a specific question and they sort it.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *