php实现新浪短链接调用API代码
前面写过了一篇文章是图片反盗链的,我自己弄得单独的页面就采用了sina的短连接,对于短连接来说还是方便的,地址太长占地方,下面分享源码,有注释,非原创,代码如下:
- <?php
-
- define('SINA_APPKEY', '31641035');
-
- function curlQuery($url) {
-
- $addHead = array(
- "Content-type: application/json"
- );
-
-
- $curl_obj = curl_init();
-
-
- curl_setopt($curl_obj, CURLOPT_URL, $url);
-
-
- curl_setopt($curl_obj, CURLOPT_HTTPHEADER, $addHead);
-
-
- curl_setopt($curl_obj, CURLOPT_HEADER, 0);
-
-
- curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, 1);
-
-
- curl_setopt($curl_obj, CURLOPT_TIMEOUT, 15);
-
-
- $result = curl_exec($curl_obj);
-
-
- curl_close($curl_obj);
-
- return $result;
- }
-
-
- function filterUrl($url = '') {
- $url = trim(strtolower($url));
- $url = trim(preg_replace('/^http:///', '', $url));
- if ($url == '')
- return false;
- else
- return urlencode('http://' . $url);
- }
-
-
- function sinaShortenUrl($long_url) {
-
- $url = 'http://api.t.sina.com.cn/short_url/shorten.json?source=' . SINA_APPKEY . '&url_long=' . $long_url;
-
-
- $result = curlQuery($url);
-
-
-
-
-
- $json = json_decode($result);
-
-
- if (isset($json->error) || !isset($json[0]->url_short) || $json[0]->url_short == '')
- return false;
- else
- return $json[0]->url_short;
- }
-
-
- function sinaExpandUrl($short_url) {
-
- $url = 'http://api.t.sina.com.cn/short_url/expand.json?source=' . SINA_APPKEY . '&url_short=' . $short_url;
-
-
- $result = curlQuery($url);
-
-
-
-
-
- $json = json_decode($result);
-
-
- if (isset($json->error) || !isset($json[0]->url_long) || $json[0]->url_long == '')
- return false;
- else
- return $json[0]->url_long;
- }
-
-
- $url = $long;
-
- $url = filterUrl($url);
- $short = sinaShortenUrl($url);
- $ulong = sinaExpandUrl($short);
- ?>
本文中短连接已经附带的一个appkey不用再自己申请KEY当然你如果需要使用你自己的您也可以自己去替换,至于用法就看你了,镶入到其他程序使用啊?单独做个生成短连接的页面都不管我的事啊,使用方法不多说,最近比较懒.