How to realize omnipotent restoration of short URL by PHP
Today, I will talk to you about how PHP can achieve omnipotent short URL restoration. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Common short URLs are redirected to the target site through 301or 302 redirects, so we can use PHP's curl_getinfo to get the redirect address in header, that is, the original URL corresponding to the short URL (well, the principle is that simple... )
/ *
* Universal short URL restore function
* @ param $shortUrl short URL
* @ return original URL | empty (failed to restore or is not a short URL)
, /
Function restoreUrl ($shortUrl) {
$curl = curl_init ()
Curl_setopt ($curl, CURLOPT_URL, $shortUrl)
Curl_setopt ($curl, CURLOPT_RETURNTRANSFER, true)
Curl_setopt ($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0')
Curl_setopt ($curl, CURLOPT_HEADER, true)
Curl_setopt ($curl, CURLOPT_NOBODY, false)
Curl_setopt ($curl, CURLOPT_TIMEOUT, 15)
Curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, false)
Curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 2)
Curl_setopt ($curl, CURLOPT_ENCODING, 'gzip')
$data = curl_exec ($curl)
$curlInfo = curl_getinfo ($curl)
Curl_close ($curl)
If ($curlInfo ['http_code'] = = 301 | | $curlInfo [' http_code'] = = 302) {
Return $curlInfo ['redirect_url']
}
Return''
}
-
How to use it:
$shortUrl = 'https://url.cn/54VbB8h'; / / short URL to restore
$orinalUrl = restoreUrl ($shortUrl)
If ($orinalUrl) {
Echo "restore result of short URL {$shortUrl}: {$orinalUrl}"
} else {
Echo "short URL restore failed"
}
After reading the above, do you have any further understanding of how PHP can achieve the universal short URL? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.