السَّلاَمُ عَلَيْكُمْ وَرَحْمَةُ اللهِ وَبَرَكَاتُهُ

KuyLa Blog - Hai semuanya Dipostingan kali ini saya akan berbagi tutorial membangun URL Shortener sendiri. OK langsung saja kita mulai dari pembuatan database.

1. Anda buat sebuah database dan buat satu table bernama 'url_shortener', lalu buatlah structure seperti berikut.



Jika ingin lebih gampang dan ngga perlu ketak-ketik :v pake cara berikut: (khusus CPanel / bukan Localhost) Pertama anda masuk ke cpanel, lalu klik MySql Databases.



Lalu anda masukkan nama database dikolom New Database: (Contoh: short) dan klik Create Database.



Jika sudah, silahkan anda klik Admin pada database yg sudah terbuat.



Selanjutnya anda klik tab SQL dan anda copas code berikut:


CREATE TABLE IF NOT EXISTS `url_shorten` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` text NOT NULL,
  `code` text NOT NULL,
  `date_shorten` int(11) NOT NULL,
  `total_visitors` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;

Untuk localhost saya lagi males :v silahkan search di mbah Google :D
2. Anda buat satu file .php bernama koneksi.php, Dan masukkan code berikut


<?php
date_default_timezone_set("Asia/Jakarta");

$dbhost = 'localhost'; // MySQL Host Name
$dbuser = 'root'; // MySQL User Name
$dbpass = 'password'; // MySQL Password
$dbname = 'short'; // MySQL DB Name

if(!([email protected]_connect($dbhost, $dbuser, $dbpass))) {
	die('Not connected to database!');
}
if ([email protected]_select_db($dbname, $db)) {
	die('Not connected to database!');
}

mysql_query('set charset utf8',$db);
mysql_query('SET names utf8',$db);

?>


3. Selanjutnya anda buat file lagi bernama index.php lalu copas juga code berikut. Btw jangan copas copas aja ya :v sekalian pelajari hehe :D

<?php

include 'koneksi.php';

?>

<html>
<head>
<title>URL Shortener - KuyLa Blog Tutorial</title>
</head>
<body>
<form action="" method="post">
<p>Simplify Yours Link</p>
<p><input type="text" name="url" value="Paste Your Long URL In Here!"></p>
<p><button name="short" type="submit">Short!</button></p>

<?php

if (isset($_POST['short'])) {
    
    $url = $_POST['url'];
    $date_shorten = time();
    $chars = "aAbBcCdDeEfFgGhHiIjJkKlL1234567890mMnNoOpPqQrRsStTuUvVwWxXyYzZ";
    $code = substr(str_shuffle($chars), 0, 5);
    
    $urlresult = 'http://yourdomain.com/'.$code;
    
    $check = mysql_query("SELECT * FROM url_shorten WHERE url = '$url'");
    $row = mysql_fetch_array($check);
    
    if (mysql_num_rows($check) > 0) {
        
        echo "<p><strong>Your long URL is</strong> <span class='url'>$url </span></p>";
        echo "<p><strong>Your short URL is</strong> <span class='url'>http://yourdomain.com/".$row['code']." </span></p>";
        echo "<p><strong>Try your shorten URL:</strong> <a href='http://yourdomain.com/".$row['code']."' target='_blank'>http://yourdomain.com/".$row['code']."</a></p>";
        
    } else {
        
        $insertdata = mysql_query("INSERT INTO url_shorten VALUES('','$url','$code','$date_shorten','0')");
        
        if ($insertdata) {
            
            echo "<p><strong>Your long URL is</strong> <span class='url'>$url </span></p>";
            echo "<p><strong>Your short URL is</strong> <span class='url'>$urlresult </span></p>";
            echo "<p><strong>Try your shorten URL:</strong> <a href='$urlresult' target='_blank'>$urlresult</a></p>";
            
        } else {
            
            echo "There is something wrong when execute the query. Please contact Administrator for this problem";
            
        }
        
    }
    
}

?>

</form>
</body>
</html>

4. Kalian buat file go.php dan copas juga code berikut


<?php

include 'koneksi.php';

// cek code url
$code = $_GET['c'];
$cek_url = mysql_query("SELECT * FROM url_shorten WHERE BINARY code = '$code' LIMIT 1");
$row = mysql_fetch_assoc($cek_url);

//ambil url asli yang dishorten
$url_asli = $row['url'];

// cek total code
$num = mysql_num_rows($cek_url);

if ($num > 0) {
    
    function getTitle($url) {
        $page = file_get_contents($url);
        $title = preg_match('/<title[^>]*>(.*?)<\/title>/ims', $page, $match) ? $match[1] : null;
        return $title;
    }
    
    function getDescription($url) {
        $tags = get_meta_tags($url);
        return @($tags['description'] ? $tags['description'] : "NULL");
    }
    
    //update total visitor url
    $update_total_visitor_url = mysql_query("UPDATE url_shorten SET total_visitors = total_visitors + 1 WHERE code = '$code'");

?>
<html>
<head>
<title><?php getTitle($url_asli); ?></title>
<meta name="description" content="<?php getDescription($url_asli); ?>">
</head>
<body>
</body>
</html>

<?php

header("Location: ".$url_asli);

} else {

echo "URL Not Found!";

}

?>


5. Nah, sudah jadi tinggal buat htaccessnya berikut codenya

<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>

RewriteEngine On
RewriteBase /
RewriteRule ^([a-zA-Z0-9_-]+)$ /go.php?c=$1


Sip, semua perjuangan sudah dilalui aseek wkwk. OK Jika ada kesalahan atau ada yg mau ditanyakan tentang scriptnya silahkan komentar pada kolom dibawah, Terimakasih udah nyimak ya..

وَ السَّلاَمُ عَلَيْكُمْ وَرَحْمَةُ اللهِ وَبَرَكَاتُهُ