» » Use PHP to generate short URLs

 

Use PHP to generate short URLs

Author: bamboo06 on 9-04-2017, 00:40, views: 676

6
The normal site to bring the kind of parameters may be very long, especially in the printing of paper products such as corporate brochures to be printed on a long url, then very ugly, and few people will go to remember this site, Although it is now possible to use a two-dimensional code to open a long URL. But people can use short URLs to achieve beautiful links, especially those with limited number of applications such as microblogging.
Use PHP to generate short URLs

Short URL implementation principle is that there is a data table configuration file will be short URL and the actual URL corresponding, when a short URL request, the program jump to the corresponding actual URL up, in order to achieve the URL of the visit.

Method 1: PHP + MySQl implementation of short URL generation and reading
Conventional program we will generate a good short URL and the original site corresponding to a data table, and then for reading use. Let's start by looking at how to generate a unique short URL.
//generate short urls
function code62($x){ 
    $show=''; 
    while($x>0){ 
        $s=$x % 62; 
        if ($s>35){ 
            $s=chr($s+61); 
        }elseif($s>9&&$s<=35){ 
            $s=chr($s+55); 
        } 
        $show.=$s; 
        $x=floor($x/62); 
    } 
    return $show; 
} 
function shorturl($url){ 
    $url=crc32($url); 
    $result=sprintf("%u",$url); 
    return code62($result); 
} 
echo shorturl('http://www.goocode.net/'); 
//1EeIv2 

Use the above PHP code can generate a unique 6-bit short URL, and then we will generate a short URL with the original URL to write to the MySQL table, insert the database code here I do not write, this is the PHP foundation.
Then we have a link.php used to receive the read url and implement a real jump.
include_once('connect.php'); //connet db
$url = $_GET['url']; 
if(isset($url) && !empty($url)){ 
    $sql = "select url from shorturl where codeid='$url'"; 
    $query = mysql_query($sql); 
    if($row=mysql_fetch_array($query)){ 
        $real_url = $row['url']; 
        header('Location: ' . $real_url); 
    }else{ 
        header('HTTP/1.0 404 Not Found'); 
        echo 'Unknown link.'; 
    } 
}else{ 
    header('HTTP/1.0 404 Not Found'); 
    echo 'Unknown link.'; 
} 

In code, if the short URL corresponding to the real url, will use the header to jump to the real page, or return 404 code. So we can use such as: http: //yourdomain/link.php? Url = xxx to achieve short URL access.
Continue, we use the URL rewrite rewrite function to achieve such as through the address: http: // yourdomain / xxx to visit.
The following is the rewrite rule:
#Apache rules:
RewriteRule ^/(.*)$ /link.php?url=$1 [L] 
 
#nginx rules: 
rewrite ^/(.*)$ /link.php?url=$1 last; 


Method 2: PHP + ini implements short URL technology
The benefits of using the database for scenario 1 are easy to use, and a large number of short URL queries need to be optimized. And program 2 to give up the database, use the ini configuration, we will be short URL and real URL configuration in the ini file, PHP directly through parse_ini_file () to read the ini file, a few lines of code can achieve short URL jump.
The links.ini file is configured like this:
google= https://www.google.com/ 
facebook= https://www.facebook.com/ 
youtube= https://www.youtube.com/ 
goocode= http://www.goocode.net 

The index.php code can be written like this:
$links = parse_ini_file('links.ini'); 
 
if(isset($_GET['l']) && array_key_exists($_GET['l'], $links)){ 
    header('Location: ' . $links[$_GET['l']]); 
} 
else{ 
    header('HTTP/1.0 404 Not Found'); 
    echo 'Unknown link.'; 
} 

Of course, we also need to configure the rewrite rule.
#Apache rules: 
RewriteRule ^/(.*)$ /index.php?l=$1 [L] 
 
#nginx rules:
rewrite ^/(.*)$ /index.php?l=$1 last; 

In contrast, the second program for small applications, you can also address the array to save the form, you can also do a management interface to maintain these short Web site.

Tags: php, short, url

Category: PHP Scripts / Plugins

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
<
  • 0 Comments
  • 0 Articles
21 June 2017 04:06

shawnkemp

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Ryan Gosling Blade Runner 2 Long Leather Fur Coat nice of you ot have let us know about it all, surely helped with You have done an amazing job with it all, keep up the good work! Please keep on sharing about such softwares in the future too but for that we need to be more flexible

<
  • 0 Comments
  • 0 Articles
22 July 2017 23:13

VidOneSAM

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
http://romantic-lovers.org.ua/movies/movies/3001114 смотреть фильм планета обезьян 2014 Цезаря и его обезьян втягивают в смертельное противостояние с человеческим войском почти предводительством безжалостного Полковника.
Потом того, как обезьяны понесли невероятные потери, Цезарь преодолевает собственные темные инстинкты и начинает личную войну,
чтобы отомстить изза особенный род.<a href=http://Romantic-Lovers.org.ua/movies/movies/3001114>смотреть мультик планета обезьян </a>
Напоследок Цезарь и Полковник сходятся лицом к лицу в эпохальной битве, которая должна решить судьбу обоих народов и будущее всей планеты.
смотреть онлайн фильм планета обезьян

<
  • 0 Comments
  • 0 Articles
23 July 2017 20:43

solarmovies.sc

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Watch the trending Movies Online and Watch Tv-Series online On Solarmovie without Registration. How many of you like to watch movies solarmovies.sc

<
  • 2 Comments
  • 0 Articles
25 July 2017 18:12

hammalarug

Reply
  • Group: Members
  • РRegistered date: 25.07.2017
  • Status: Currently Offline
 
An immensely comprehensive article on how to open a long url with short url or simply by just two dimensional code. Above mentioned methods provide extreme dissertation writing help. I used these in my online research for my thesis

<
  • 0 Comments
  • 0 Articles
21 September 2017 01:06

Stewartreuch

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
<
  • 0 Comments
  • 0 Articles
21 September 2017 01:24

Charlesnum

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 

Add comments

Name:*
E-Mail:
Comment:
Bold Italic Underline Strike | Align left Center Align right | Insert smilies Insert link URLInsert protected URL Select color | Add Hidden Text Insert Quote Convert selected text from selection to Cyrillic (Russian) alphabet Insert spoiler
Security Code: *