{"id":221,"date":"2009-05-09T03:49:18","date_gmt":"2009-05-09T06:49:18","guid":{"rendered":"http:\/\/wordpress.matbra.com\/?p=221"},"modified":"2010-07-23T20:36:42","modified_gmt":"2010-07-23T23:36:42","slug":"criando-seu-proprio-tiny-url","status":"publish","type":"post","link":"https:\/\/wordpress.matbra.com\/en\/2009\/05\/09\/criando-seu-proprio-tiny-url\/","title":{"rendered":"Creating your own Url shortener."},"content":{"rendered":"<p>Good Night,<\/p>\n<p>Here I will show you how to create your own url shortener. <\/p>\n<p>First of all you need to create a table like this:<\/p>\n<blockquote><p>\n CREATE TABLE IF NOT EXISTS `urls` (<br \/>\n   `uid` int(11) NOT NULL auto_increment,<br \/>\n   `url` text default NULL,<br \/>\n   `unique_chars` varchar(25) BINARY NOT NULL,<br \/>\n   PRIMARY KEY  (`uid`),<br \/>\n   UNIQUE KEY `unique_chars` (`unique_chars`)<br \/>\n );  <\/p><\/blockquote>\n<p><em>This code was taken from Abhise in this post &#8220;<a href=\"http:\/\/ad1987.blogspot.com\/2008\/12\/create-your-own-tinyurl-with-php-and.html\" target=\"_blank\">Create your own tinyurl with php and mySQL<\/a>&#8221; 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)<\/em><\/p>\n<p>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. <\/p>\n<p><!--more--><\/p>\n<p>We need a fucntion to connect\/disconnect to mysql <\/p>\n<blockquote><p>\nerror_reporting(E_ALL);<br \/>\n$link;<br \/>\n$config;<br \/>\nfunction connect_db_lurl() {<br \/>\n\tglobal $link;<br \/>\n\tglobal $config;<br \/>\n\t$hostname = &#8220;localhost&#8221;;<br \/>\n\t$username = &#8220;USUARIO&#8221;;<br \/>\n\t$password = &#8220;SENHA&#8221;;<br \/>\n\t$dbname = &#8220;DATABASE&#8221;;<br \/>\n\t$link = mysql_connect($hostname, $username, $password);  \/\/ Conecta ao mysql.<br \/>\n\tmysql_select_db($dbname) or die(&#8220;Unknown database!&#8221;);   \/\/ Seleciona o Banco de dados.<br \/>\n\t$config[&#8220;domain&#8221;] = &#8220;http:\/\/seudominio.com&#8221;;  \/\/ Define a configura\u00e7\u00e3o da URL inicial<br \/>\n}<\/p>\n<p>function close_db_lurl() {<br \/>\n\tmysql_close(); \/\/ Fecha a conex\u00e3o com o banco de dados<br \/>\n}\n<\/p><\/blockquote>\n<p>After this I created a function to redirect to the URL.<\/p>\n<blockquote><p>function redirect($url) {<br \/>\n\theader(&#8220;Location:&#8221;.$url); \/\/ Redireciona para a url.<br \/>\n}<\/p><\/blockquote>\n<p>Than I used the function from Abhise to generate the char sequence. (I add some chars to elevate the number of combinations<\/p>\n<blockquote><p>function generate_chars() {<br \/>\n\t$num_chars = 6; \/\/ Tamanho que voc\u00ea deseja as strings<br \/>\n\t$i = 0;<br \/>\n\t$my_keys = &#8220;123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#8221;; \/\/ Caracteres que valem para forma\u00e7\u00e3o de endere\u00e7o<br \/>\n\t$keys_length = strlen($my_keys);<br \/>\n\t$url  = &#8220;&#8221;;<br \/>\n\twhile($i<$num_chars) {  \/\/ Gera sequencia aleatoria\n\t\t$rand_num = mt_rand(1, $keys_length-1);  \n\t   \t$url .= $my_keys[$rand_num];  \n\t\t$i++;  \n\t}  \n\treturn $url;  \n}  <\/p><\/blockquote>\n<p>Created a function to verify if the key is unique.<\/p>\n<blockquote><p>function isUnique($chars)  {<br \/>\n\tglobal $link;<br \/>\n\t$q = &#8220;SELECT * FROM `urls` WHERE `unique_chars`='&#8221;.$chars.&#8221;&#8216;&#8221;;<br \/>\n\t$r = mysql_query($q, $link);  \/\/ Verifica se a chave \u00e9 unica.<br \/>\n\tif( mysql_num_rows($r)>0 ) {<br \/>\n\t\treturn false;<br \/>\n\t} else {<br \/>\n\t\treturn true;<br \/>\n\t}<br \/>\n}  <\/p><\/blockquote>\n<p>And other to verify if the URL is in DB<\/p>\n<blockquote><p>function isThere($url) {<br \/>\n\tglobal $link;<br \/>\n\t$q = &#8220;SELECT * FROM `urls` WHERE `url`='&#8221;.$url.&#8221;&#8216;&#8221;;<br \/>\n\t$r = mysql_query($q);  \/\/ Verifica se j\u00e1 existe a url<br \/>\n\tif(mysql_num_rows($r)>0) {<br \/>\n\t\treturn true;<br \/>\n\t} else {<br \/>\n\t\treturn false;<br \/>\n\t}<br \/>\n}<\/p><\/blockquote>\n<p>Function to create<\/p>\n<blockquote><p>function create() {<br \/>\n\tglobal $link;<br \/>\n\tglobal $config;<br \/>\n\t$chars = generate_chars(); \/\/ Gera sequencia de caracteres.<\/p>\n<p>\twhile(!isUnique($chars)){ \/\/ Verifica se \u00e9 unico, se n\u00e3o for gera denovo.<br \/>\n\t  $chars = generate_chars();<br \/>\n\t}<\/p>\n<p>\t$url = $_GET[&#8220;u&#8221;]; \/\/ Pega o endere\u00e7o que est\u00e1 em ?u=endere\u00e7o<br \/>\n\t$url = trim($url); \/\/ Retira espa\u00e7os em branco do inicio e do fim<br \/>\n\t$url = mysql_real_escape_string($url);<\/p>\n<p>\tif(!isThere($url)) { \/\/ Caso n\u00e3o exista o endere\u00e7o no banco.<br \/>\n\t\t$q = &#8220;INSERT INTO `urls` (url, unique_chars) VALUES (&#8216;&#8221;.$url.&#8221;&#8216;, &#8216;&#8221;.$chars.&#8221;&#8216;)&#8221;;<br \/>\n\t\t$r = mysql_query($q, $link); \/\/ Insere o endere\u00e7o<br \/>\n\t\tif(mysql_affected_rows()) {<br \/>\n\t\t\t$q = &#8220;SELECT * FROM `urls` WHERE `url`='&#8221;.$url.&#8221;&#8216;&#8221;;<br \/>\n\t\t\t$r = mysql_query($q);<br \/>\n\t\t\t$row = mysql_fetch_row($r);<br \/>\n\t\t\techo $config[&#8220;domain&#8221;].&#8221;\/&#8221;.$row[2]; \/\/ Imprime endere\u00e7o para acesso da nova url<br \/>\n\t\t} else {<br \/>\n\t\t\t echo &#8220;Desculpe, problemas com o banco de dados.&#8221;;<br \/>\n\t\t}<br \/>\n\t} else { \/\/ Caso j\u00e1 exista<br \/>\n\t\t$q = &#8220;SELECT * FROM `urls` WHERE `url` = &#8216;&#8221;.$url.&#8221;&#8216;&#8221;;<br \/>\n\t\t$r = mysql_query($q); \/\/ Seleciona endere\u00e7o para URL<br \/>\n\t\t$row = mysql_fetch_row($r);<br \/>\n\t\techo $config[&#8220;domain&#8221;].&#8221;\/&#8221;.$row[2]; \/\/ Imprime endere\u00e7o para acesso da url.<br \/>\n \t}<br \/>\n}<\/p><\/blockquote>\n<p>Looking to the code I thought to create a function to get the url.<\/p>\n<blockquote><p>function take_lurl($lurl) {<br \/>\n\tglobal $link;<br \/>\n\t$q = &#8220;SELECT url FROM `urls` WHERE `unique_chars` = &#8216;&#8221;.$lurl.&#8221;&#8216;&#8221;;<br \/>\n\t$r = mysql_query($q, $link); \/\/ Pega endere\u00e7o original para tal string.<br \/>\n\tif(mysql_num_rows($r)>0) {<br \/>\n\t\t $info = mysql_fetch_array($r);<br \/>\n\t\t $url = $info[&#8220;url&#8221;];<br \/>\n\t} else {<br \/>\n\t\techo &#8220;Sorry, link not found!&#8221;;<br \/>\n\t}<br \/>\n\treturn $url;<br \/>\n}<\/p><\/blockquote>\n<p>Created the file &#8220;functions-little-url.php&#8221; with these functions.<\/p>\n<p>index.php:<\/p>\n<blockquote><p><?\nob_start(); \/\/Inicia Buffer de saida\ninclude(\"functions-little-url.php\");\nconnect_db_lurl();\n$lurl = $_GET[\"u\"]; \/\/Sequencia de caracteres\n$url = take_lurl($lurl);\nredirect($url);\nclose_db_lurl();\nob_end_flush(); \/\/ Fecha buffer de saida\n?><\/p><\/blockquote>\n<p>create.php:<\/p>\n<blockquote><p><?\ninclude(\"functions-little-url.php\");\nconnect_db_lurl();\ncreate();\nclose_db_lurl();\n?><\/p><\/blockquote>\n<p>We need to add some lines do .htaccess and enable mod_rewrite.<\/p>\n<blockquote><p><IfModule mod_rewrite.c><br \/>\nRewriteEngine On<br \/>\nRewriteRule   ^([1-9a-zA-Z]*)$ index.php\\?u=$1 [L]<br \/>\n<\/IfModule><\/p><\/blockquote>\n<p>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<\/p>\n<blockquote><p><IfModule mod_rewrite.c><br \/>\nRewriteEngine On<br \/>\nRewriteBase \/<\/p>\n<p>RewriteCond %{REQUEST_FILENAME} !-f # Verifica se a p\u00e1gina acessada n\u00e3o \u00e9 um arquivo real<br \/>\nRewriteCond %{REQUEST_FILENAME} !-d# Verifica se a p\u00e1gina acessada n\u00e3o \u00e9 um diret\u00f3rio<br \/>\nRewriteRule ^([A-Za-z0-9]{6})$ \/lurl\/index.php?u=$1 [L] # Caso coincida com a express\u00e3o regular redirecione para \/lurl\/index.php?u=$1 onde \/lurl\/ \u00e9 o diret\u00f3rio que est\u00e1 os meus arquivos de tiny-url e [L] indica que \u00e9 a ultima instru\u00e7\u00e3o a ser executada. <\/p>\n<p># Caso n\u00e3o feche com a parte em cima continua nas regras &#8220;padr\u00f5es&#8221; do WordPress<br \/>\nRewriteCond %{REQUEST_FILENAME} !-f # Verifica se a p\u00e1gina acessada n\u00e3o \u00e9 um arquivo real<br \/>\nRewriteCond %{REQUEST_FILENAME} !-d# Verifica se a p\u00e1gina acessada n\u00e3o \u00e9 um diret\u00f3rio<br \/>\nRewriteRule . \/index.php [L]<br \/>\n<\/IfModule><\/p><\/blockquote>\n<p>(my URL shortener is inside \/lurl\/ directory but the redirect was done in matbra.com\/XXXXXXX so it redirects to \/lurl\/<\/p>\n<p>To create URLs acess create.php?u=ADDRESS<\/p>\n<p><a href=\"http:\/\/wordpress.matbra.com\/?attachment_id=219\">URL-Shortener<\/a><\/p>\n<p>If you have any problem feel free to contact me. <\/p>\n<p>Best Regards,<br \/>\nMatheus Bratfisch<\/p>\n<p>References:<br \/>\n&#8212;- &#8220;Tiny Url&#8221;:<br \/>\n<a href=\"http:\/\/www.php.net\" target=\"_blank\">www.php.net<\/a><br \/>\n<a href=\"http:\/\/www.wynia.org\/wordpress\/2007\/05\/06\/making-your-own-tiny-urls-with-php\/\" target=\"_blank\">Wynia.org<\/a><br \/>\n<a href=\"http:\/\/www.htmlcenter.com\/blog\/make-your-own-tinyurl-service\/\" target=\"_blank\">htmlCenter<\/a><br \/>\n&#8212;- &#8220;Mod Rewrite&#8221;:<br \/>\n<a href=\"http:\/\/httpd.apache.org\/docs\/2.0\/mod\/mod_rewrite.html\" target=\"_blank\"> Apache Mod Rewrite<\/a><br \/>\n<\/p>","protected":false},"excerpt":{"rendered":"<p>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:<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"https:\/\/wordpress.matbra.com\/en\/2009\/05\/09\/criando-seu-proprio-tiny-url\/\">Continue reading<span class=\"screen-reader-text\">Creating your own Url shortener.<\/span><\/a><\/div>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[7,78,69],"tags":[81,11,9,80,82,325,323,13,79],"class_list":["post-221","post","type-post","status-publish","format-standard","hentry","category-aprendendo","category-mysql","category-php","tag-apache","tag-como-fazer","tag-howto","tag-little-url","tag-mod_rewrite","tag-mysql","tag-php","tag-programacao","tag-tinyurl","entry"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/psjGE-3z","_links":{"self":[{"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/posts\/221","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/comments?post=221"}],"version-history":[{"count":1,"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/posts\/221\/revisions"}],"predecessor-version":[{"id":222,"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/posts\/221\/revisions\/222"}],"wp:attachment":[{"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/media?parent=221"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/categories?post=221"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wordpress.matbra.com\/en\/wp-json\/wp\/v2\/tags?post=221"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}