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:
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(); ?>
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
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
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.
[…] tempo atrás eu mostrei como criar um sistema próprio de Tiny-URL, estava curioso para saber como andavam os acessos aos meus links distribuidos por outros […]
[…] Como criar seu próprio tiny url Estatísticas no seu Tiny URL […]
[…] 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” […]
Não consigo usar o sisteminha, pois ponho ele numa pasta e naum funciona.
Criei a tabela e nada
Voce precisa ter o modrewrite instalado. Precisa configurar ele com o codigo que esta no post no arquivo .htaccess se nao estou enganado.
Nao eh soh colocar numa pasta e pronto.
ставки кыргызстан mostbet12034.ru
скачать мостбет казино http://www.mostbet12033.ru
جرثقیل سقفی دو پل
mostbet приложение https://www.mostbet12035.ru
رفع افتادگی پلک در سعادت آباد تهران –
بهترین لیزر تهران
мостбеь mostbet12037.ru
мостбет скачать на компьютер мостбет скачать на компьютер
торкретирование москва http://www.torkretirovanie-1.ru/ .
официальный сайт mostbet http://mostbet12039.ru
mostbet скачат http://mostbet12038.ru
صندلی پلاستیکی پولاد – صندلی پلاستیکی ناصر
mostbet. mostbet.
что такое 1win http://1win12019.ru
1вин верификация http://1win5521.ru
как делать ставки на 1win http://1win5520.ru/
Приветствую всех! Хотел поделиться простым лайфхаком по определению печенья в браузере. Часто бывает, что нужно незамедлительно найти отдельные файлы куки, чтобы понять кэшированными данными или стереть целевые cookie-файлы. Для этого следует задействовать специализированными программами и утилитами, которые существенно улучшают процесс.
Когда захотите использовать что-то удобное, предлагаю ознакомиться с данный ресурс Поиск печенек , где досконально освещены методы определения и регулирования печеньем в многообразных браузерах. Это на самом деле рационализирует время и способствует точнее разбираться, что в частности сохраняется на личном устройстве. Полагаю, некто признает это ценным!
melbet какое зеркало melbet какое зеркало
melbet bonus rules melbet5008.ru
melbet mobil http://melbet5012.ru/
melbet download https://melbet5011.ru/
melbet „verificare documente” https://melbet5015.ru
melbet игровые автоматы http://melbet5004.ru/
melbet официальный сайт https://melbet5009.ru/
1вин регистрация и вход на сайт 1вин регистрация и вход на сайт
дайсон стайлер купить официальный http://www.fen-d-2.ru .
пин ап как вывести деньги https://pinup5010.ru
пин ап сайт на узбекском pinup5012.ru
pin up kazino o‘yinlari bepul pin up kazino o‘yinlari bepul
one win 1win5522.ru
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
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/
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/
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!
1win texnik yordam https://www.1win5511.ru
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/