This morning I published a tutorial and code for generating short URLs using the Baidu Short URL API. Then I discovered a better way to generate Baidu short URLs on CSDN, so I wanted to repost it here and share it with you. You can also compare it with the version in my previous article. Anyway, I think this one is relatively fast and convenient, and its design logic is also very sophisticated. Here is the code.

PHP Code

<?php
function send_post($url, $post_data) {
    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60
        )  
    );  
    $context = stream_context_create($options);  
    $result = file_get_contents($url, false, $context);  
    return $result;  
}
$post_data = array(
    'url' => 'URL'
);
$json_data =  send_post('http://dwz.cn/create.php', $post_data);
$arr = json_decode($json_data,true);
echo $arr['tinyurl'];
?>