如何建立本身的短網址服務

因爲如今使用Twitter服務的愈來愈多,短網址服務也愈來愈受歡迎。 所以愈來愈多的第三方的短網址服務開始大批量建立。  
若是你有興趣,那麼請跟隨本文,這裏將教你們如何使用Google短網址的API來建立咱們本身簡單的短網址服務。 Let's go! php

如下是本文的目錄

  1. 1. 準備
  2. 2. 建立 index.php
  3. 3. 建立gen.php
  4. 4. 演示
  5. 5. 下載
  6. 6. 結束

 

內容

1. 準備html

建立兩個PHP文件,並命名爲 "index.php" 和"gen.php"。jquery

  1. 1 index.php: 首頁。
  2. 2 gen.php: 服務端調用Google短網址服務API。 咱們不能使用JavaScript直接(跨域)從谷歌得到數據。
  3. 3 從http://code.google.com/apis/urlshortener/v1/getting_started.html#APIKey , 得到谷歌的API密鑰,此密鑰將用於從谷歌查詢數據,這個是關鍵點。
  4. 4 複製和粘貼圖片"load.gif" 到"index.php"同目錄下。 此圖片將用於AJAX的等待加載提示。

 

2. 建立 index.phpgit

先建立一個簡單的HTML原型的index.php頁面:github

01 <html
02 <head
03 </head
04 <body
05 <div id="container">
06     <h1>Google URL Shortener</h1>
07     <div id="generator">
08         <form id="form" action="#" method="post">
09             <fieldset>
10                 <input type="text" name="url" id="short">
11                 <input type="submit" value="Shorten"></input>
12                 <div class="loading"></div>
13             </fieldset>
14         </form>
15     </div>
16 </div>
17 </body>
18 </html>

這裏將建立一個簡單的文本框和提交按鈕。
效果以下:ajax

google-url-shorten

接下來,讓咱們添加一些CSS樣式,使它更好看些。代碼以下: json

01 <html
02 <head>
03 <style
04 body{    
05     width:100%;  
06     margin:0px;  
07     padding:0px; 
08
09 #container{
10     font-family: Arial, serif;  
11     font-size:12px;    
12     padding-top:20px;  
13     width:700px;   
14     margin: auto;  
15
16 form{  
17     width:100%;   
18     padding: 0px; 
19     margin: 0px;
20 }
21 form fieldset{  
22     padding:20px; 
23
24 form input{ 
25     padding:5px;   
26     font-size:14px; 
27
28 form input[type=text]{  
29     float:left;  
30     width:80%;   
31     border: 1px solid #CCCCCC; 
32 }
33 form input[type=submit]{  
34     width:10%;   
35     margin-left:5px;  
36     float:left; 
37     border: 1px solid #CCCCCC;   
38     background: #DDDDDD;  
39     cursor: pointer; 
40
41 div.loading{   
42     display:none; 
43     margin:5px;  
44     float:left;  
45     width:16px;   
46     height:16px;   
47     background-image: url("load.gif");  
48     background-repeat: no-repeat; 
49     background-position: top left;  
50     background-color: transparent;
51 }
52 </style>
53 </head
54 <body
55 <div id="container">    
56     <h1>Google URL Shortener</h1
57     <div id="generator">      
58         <form id="form" action="#" method="post">    
59             <fieldset>              
60                 <input type="text" name="url" id="short">       
61                 <input type="submit" value="Shorten"></input>        
62                 <div class="loading"></div>        
63             </fieldset>  
64         </form>  
65     </div
66 </div>
67 </body>
68 </html>

咱們這裏就不對CSS樣式進行說明了。api

請注意,咱們還要建立了一個"class='loading'"的"DIV" 層,這用於Ajax的加載;默認狀況它是不顯示的,咱們使用jQuery控制它的隱藏顯示。跨域

google-url-shorten-2

完成"index.php"的最後一步,也是最重要的一步,咱們將導入jQuery庫來完成Ajax操做。
複製並粘貼如下的JavaScript代碼到CSS樣式下面。咱們稍後將做解釋。服務器

01 <html
02 <head>
03 <style
04 body{    
05     width:100%;  
06     margin:0px;  
07     padding:0px; 
08
09 #container{
10     font-family: Arial, serif;  
11     font-size:12px;    
12     padding-top:20px;  
13     width:700px;   
14     margin: auto;  
15
16 form{  
17     width:100%;   
18     padding: 0px; 
19     margin: 0px;
20 }
21 form fieldset{  
22     padding:20px; 
23
24 form input{ 
25     padding:5px;   
26     font-size:14px; 
27
28 form input[type=text]{  
29     float:left;  
30     width:80%;   
31     border: 1px solid #CCCCCC; 
32 }
33 form input[type=submit]{  
34     width:10%;   
35     margin-left:5px;  
36     float:left; 
37     border: 1px solid #CCCCCC;   
38     background: #DDDDDD;  
39     cursor: pointer; 
40
41 div.loading{   
42     display:none; 
43     margin:5px;  
44     float:left;  
45     width:16px;   
46     height:16px;   
47     background-image: url("load.gif");  
48     background-repeat: no-repeat; 
49     background-position: top left;  
50     background-color: transparent;
51 }
52 </style>
54 <script>     
55     $(document).ready(function(){       
56         $('#form').submit(function(){      
57             $.ajax({             
58                 type: "POST",    
59                 url: "gen.php",   
60                 data: $(this).serialize(),  
61                 beforeSend: function(){     
62                     $('.loading').show(1);      
63                 },          
64                 complete: function(){  
65                     $('.loading').hide(1);  
66                 },       
67                 success: function(data){     
68                     $('#short').val(data);    
69                 }          
70             });      
71             return false;  
72         });   
73     });
74 </script>
75 </head
76 <body
77 <div id="container">    
78     <h1>Google URL Shortener</h1
79     <div id="generator">      
80         <form id="form" action="#" method="post">    
81             <fieldset>              
82                 <input type="text" name="url" id="short">       
83                 <input type="submit" value="Shorten"></input>        
84                 <div class="loading"></div>        
85             </fieldset>  
86         </form>  
87     </div
88 </div>
89 </body>
90 </html>

讓咱們來仔細看看,上面添加在那些的JavaScript代碼:

01 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <!-- setp 1 --> 
02 <script
03     $(document).ready(function(){    
04         $('#form').submit(function(){           //step 2      
05             $.ajax({                            //step 3           
06                 type: "POST",         
07                 url: "gen.php",          
08                 data: $(this).serialize(),         
09                 beforeSend: function(){         //step 4              
10                     $('.loading').show(1);            
11                 },              
12                 complete: function(){           //step 5      
13                     $('.loading').hide(1);            
14                 },            
15                 success: function(data){        //step 6              
16                     $('#short').val(data);              
17                 }            
18             });        
19             return false;     
20         });    
21     }); 
22 </script>
    • 第1步:使用谷歌提供的jQuery庫。
    • 第2步:一個提交的事件處理程序。
    • 第3步:使用「POST」方法的數據序列化形式,提交表單數據到「gen.php」。
    • 第4步:發送數據時,顯示加載的DIV層。
    • 第5步:AJAX操做完成時,隱藏加載的DIV層 。
    • 第6步:將AJAX完成的數據顯示在文本框中。

接下來,咱們繼續完成「gen.php」,它涉及Google的短網址API。 

3. 建立 gen.php

複製並粘貼如下代碼,完成「gen.php」。

01 <?php 
02 //1 
03 if(isset($_REQUEST['url'])&&!empty($_REQUEST['url'])){           
04     //2    
05     $longUrl = $_REQUEST['url'];   
06     $apiKey  = 'Your-Api-Key';      
07     //3   
08     $postData = array('longUrl' => $longUrl, 'key' => $apiKey);  
09     $jsonData = json_encode($postData);      
10     //4     
11     $curlObj = curl_init();    
12     curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');  
13     curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);   
14     curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);   
15     curl_setopt($curlObj, CURLOPT_HEADER, 0);    
16     curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));  
17     curl_setopt($curlObj, CURLOPT_POST, 1);  
18     curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);     
19     //5   
20     $response = curl_exec($curlObj);   
21     $json = json_decode($response);     
22     //6    
23     curl_close($curlObj);   
24     //7   
25     if(isset($json->error)){     
26         echo $json->error->message;     
27     }else{       
28         echo $json->id;    
29     }     
30 }else{  
31     echo 'Please enter a URL';
32
33 ?>

在我解釋這段代碼以前,請先在第6行處提供你的「Google API密鑰」。

  1. 1. 當提交的數據($_REQUEST ['URL'])不存在,則它會響應一個錯誤消息(「請輸入網址」)。
  2. 2. 從$_REQUEST中獲得URL。
  3. 3. 建立一個JSON數據,包含URL和谷歌API密鑰。這個JSON數據將被髮送到Google做爲請求參數。
  4. 4. 使用PHP的cURL鏈接谷歌API服務器。
  5. 5. 從谷歌獲取數據,並解碼JSON對象。
  6. 6. 關閉cURL鏈接。
  7. 7. 若是返回數據有錯誤,就返回錯誤信息,不然顯示短URL。

大功告成。如今你能夠去體驗如下本身的短網址服務了。 

4. 演示

從這裏你能夠 現場演示 .

5. 下載

你也能夠從GitHub賬戶,下載此 腳本

6. 結束

感謝您看完這篇文章,但願它能對你有所幫助。

關鍵字: 短網址服務
相關文章
相關標籤/搜索