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