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
I have been using this casino for about four months now, so I have enough sessions behind me to judge. Found it through a mate, because I wanted somewhere that actually pays out on time. The game library at True Fortune is larger than I expected, though honestly I rotate between maybe twenty games.
Software comes from the usual names: Pragmatic Play, NetEnt, Play’n GO, with Nolimit City and Hacksaw in the mix. Gates of Olympus and Sweet Bonanza are there of course, though personally I prefer the higher volatility stuff. Live tables come from Evolution, so Crazy Time, Lightning Roulette and the rest of the game shows. Dealers are on 24/7, although the ?1 tables can be crowded after nine.
The welcome offer is nothing extraordinary but fair: a first deposit match with a batch of free spins, with the spins dripping in over several days. Rollover is 35 times the bonus, so nothing predatory but no gift either. The live offers and promo codes are listed over at true fortune casino online before you commit any money. There is a small no deposit thing that appears now and then, although you will not retire on it.
Opening an account took a few minutes, minimum deposit is ?10. I fund it by card or Skrill, they also take crypto. Money reached the wallet within a day, bank transfers ran longer, two to three days. The document check was the only hassle – my first upload got rejected, and after that it was fine.
Mobile is browser based for me so no install needed. It loads quickly, though live tables need decent data. The chat team is English speaking and they are not just copy-pasting, wait times were three to five minutes. They hold a Curacao licence meaning no UK licence, which is the trade-off. The main thing is the money came back every time I asked.
«Похмельная служба» ориентирована на комплексное оказание наркологической помощи взрослым людям с алкогольной зависимостью. Выездной нарколог может приехать на дом, провести медицинский осмотр, определить тяжесть интоксикации и решить, допустим ли вывод из запоя в домашних условиях. При тяжелых нарушениях, угрозе осложнений или выраженных психических расстройствах необходима госпитализация. В клинике доступен полный комплекс диагностических и лечебных процедур, а при необходимости дальнейшее лечение алкоголизма включает психотерапию, кодирование, реабилитацию и профилактику срыва.
Подробнее – https://4.vyvod-iz-zapoya-moskva1-13.ru/