You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

86 lines
2.9 KiB

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Steven
  5. * Date: 2016/8/4
  6. * Time: 14:25
  7. */
  8. //Sina App_Key
  9. //define('SINA_APPKEY', '31641035');
  10. define('SINA_APPKEY', '3271760578');
  11. //获取请求结果
  12. function curlQuery($url) {
  13. //设置附加HTTP头
  14. $addHead = array(
  15. "Content-type: application/json"
  16. );
  17. //初始化curl,当然,你也可以用fsockopen代替
  18. $curl_obj = curl_init();
  19. //设置网址
  20. curl_setopt($curl_obj, CURLOPT_URL, $url);
  21. //附加Head内容
  22. curl_setopt($curl_obj, CURLOPT_HTTPHEADER, $addHead);
  23. //是否输出返回头信息
  24. curl_setopt($curl_obj, CURLOPT_HEADER, 0);
  25. //将curl_exec的结果返回
  26. curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, 1);
  27. //设置超时时间
  28. curl_setopt($curl_obj, CURLOPT_TIMEOUT, 15);
  29. //执行
  30. $result = curl_exec($curl_obj);
  31. //关闭curl回话
  32. curl_close($curl_obj);
  33. return $result;
  34. }
  35. //简单处理下url,sina对于没有协议(http://)开头的和不规范的地址会返回错误
  36. function filterUrl($url = '') {
  37. $url = trim(strtolower($url));
  38. $url = trim(preg_replace('/^http:\//', '', $url));
  39. if ($url == '')
  40. return false;
  41. else
  42. return urlencode('http://' . $url);
  43. }
  44. //根据长网址获取短网址
  45. function sinaShortenUrl($long_url) {
  46. /*
  47. $access_url = "https://api-ssl.bitly.com/v3/shorten?access_token=".BITACCESSTOKEN."&longUrl=".$long_url;
  48. $result = httpRequest($access_url);
  49. $return_result = json_decode($result,true);
  50. if( $return_result["status_code"] == 200 ) {
  51. $url = $return_result["data"]["url"];
  52. $return_url = str_replace("http://", "https://", $url);
  53. return $return_url;
  54. }
  55. */
  56. //拼接请求地址,此地址你可以在官方的文档中查看到
  57. $url = 'http://api.t.sina.com.cn/short_url/shorten.json?source=' . SINA_APPKEY . '&url_long=' . $long_url;
  58. //获取请求结果
  59. $result = curlQuery($url);
  60. //下面这行注释用于调试,
  61. //print_r($result);exit();
  62. //解析json
  63. $json = json_decode($result);
  64. //异常情况返回false
  65. if (isset($json->error) || !isset($json[0]->url_short) || $json[0]->url_short == '')
  66. return false;
  67. else
  68. return $json[0]->url_short;
  69. }
  70. //根据短网址获取长网址,此函数重用了不少sinaShortenUrl中的代码,以方便你阅读对比,你可以自行合并两个函数
  71. function sinaExpandUrl($short_url) {
  72. //拼接请求地址,此地址你可以在官方的文档中查看到
  73. $url = 'http://api.t.sina.com.cn/short_url/expand.json?source=' . SINA_APPKEY . '&url_short=' . $short_url;
  74. //获取请求结果
  75. $result = curlQuery($url);
  76. //下面这行注释用于调试
  77. //print_r($result);exit();
  78. //解析json
  79. $json = json_decode($result);
  80. //异常情况返回false
  81. if (isset($json->error) || !isset($json[0]->url_long) || $json[0]->url_long == '')
  82. return false;
  83. else
  84. return $json[0]->url_long;
  85. }
  86. ?>