SoFunction
Updated on 2025-03-02

PHP method to call Sina short link API

<?php
//Sina App_Key
define('SINA_APPKEY', '31641035');
function curlQuery($url) {
//Set up additional HTTP headers
 $addHead = array(
 "Content-type: application/json"
 );
//Initialize curl, of course, you can also use fsocopen instead
 $curl_obj = curl_init();
//Set the URL
 curl_setopt($curl_obj, CURLOPT_URL, $url);
//Add Head content
 curl_setopt($curl_obj, CURLOPT_HTTPHEADER, $addHead);
// Whether to output the return header information
 curl_setopt($curl_obj, CURLOPT_HEADER, 0);
//Return the result of curl_exec
 curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, 1);
//Set the timeout time
 curl_setopt($curl_obj, CURLOPT_TIMEOUT, 15);
//implement
 $result = curl_exec($curl_obj);
//Close curl reply
 curl_close($curl_obj);
 return $result;
}
//After simple processing of url, sina will return an error for addresses that do not start with protocol (http://) and are not standardized.
function filterUrl($url = '') {
 $url = trim(strtolower($url));
 $url = trim(preg_replace('/^http:///', '', $url));
 if ($url == '')
 return false;
 else
 return urlencode('http://' . $url);
}
//Get short URL based on long URL
function sinaShortenUrl($long_url) {
//Split request address, you can view this address in the official document
 $url = '/short_url/?source=' . SINA_APPKEY . '&url_long=' . $long_url;
//Get the request result
 $result = curlQuery($url);
//The following line of comments is used for debugging. You can remove the comments and see what the information returned from sina is.
 //print_r($result);exit();
//Analysis json
 $json = json_decode($result);
//Exception returns false
 if (isset($json->error) || !isset($json[0]->url_short) || $json[0]->url_short == '')
 return false;
 else
 return $json[0]->url_short;
}
//Get long URLs based on short URLs. This function reuses a lot of code in sinaShortenUrl to facilitate your reading and comparison. You can merge two functions by yourself
function sinaExpandUrl($short_url) {
//Split request address, you can view this address in the official document
 $url = '/short_url/?source=' . SINA_APPKEY . '&url_short=' . $short_url;
//Get the request result
 $result = curlQuery($url);
//The following line of comments is used for debugging. You can remove the comments and see what the information returned from sina is.
 //print_r($result);exit();
//Analysis json
 $json = json_decode($result);
//Exception returns false
 if (isset($json->error) || !isset($json[0]->url_long) || $json[0]->url_long == '')
 return false;
 else
 return $json[0]->url_long;
}
//The URL to be shortened
$url = $long; //You can do it yourself here, modify it to the URL you want to shorten, get the post data, or what to do.
$url = filterUrl($url);
$short = sinaShortenUrl($url);
$ulong = sinaExpandUrl($short);
?>