Google URL Shortener PHP Class - David Walsh Blog
文章推薦指數: 80 %
The class features two main methods: shorten and expand. Each method takes the long or short URL, contacts Google, and returns its ...
HomeMainContentPopular:JavaScriptPromisesfetchAPIReact.jsCacheAPIES6FeaturesNode.jsJavaScriptjQueryGoogleURLShortenerPHP Class
BuildingResilientSystemsonAWS:Learnhowtodesignandimplementaresilient,highlyavailable,fault-tolerantinfrastructureonAWS.GoogleURLShortenerPHPClass
By
DavidWalsh on
February2,2011
54GooglehashadaURLshorteningdomainforquiteawhilenowbutitwasn'tuntilrecentlythatGoogleexposedtheURLshorteningAPItothepublic. ItookafewminutestoreviewtheirAPIandcreatedaverybasicGoogleUrlApiclassthatwillshortenlongURLsandexpandshortenedURLs.
ThePHP
Theclassitselfisquitecompactandthecodeshouldbeeasytoread:
//Declaretheclass
classGoogleUrlApi{
//Constructor
functionGoogleURLAPI($key,$apiURL='https://www.googleapis.com/urlshortener/v1/url'){
//KeeptheAPIUrl
$this->apiURL=$apiURL.'?key='.$key;
}
//ShortenaURL
functionshorten($url){
//Sendinformationalong
$response=$this->send($url);
//Returntheresult
returnisset($response['id'])?$response['id']:false;
}
//ExpandaURL
functionexpand($url){
//Sendinformationalong
$response=$this->send($url,false);
//Returntheresult
returnisset($response['longUrl'])?$response['longUrl']:false;
}
//SendinformationtoGoogle
functionsend($url,$shorten=true){
//CreatecURL
$ch=curl_init();
//Ifwe'reshorteningaURL...
if($shorten){
curl_setopt($ch,CURLOPT_URL,$this->apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type:application/json"));
}
else{
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//Executethepost
$result=curl_exec($ch);
//Closetheconnection
curl_close($ch);
//Returntheresult
returnjson_decode($result,true);
}
}
TheconstructorrequiresyourGoogleAPIkey. AsecondargumentmaybeprovidedtotheURLoftheGoogleAPI. AstheAPIiscurrentlyinversion1,changingthisURLwouldbemoreharmfulthanuseful. Theclassfeaturestwomainmethods: shortenandexpand. EachmethodtakesthelongorshortURL,contactsGoogle,andreturnsitscounterpart. Ifnocounterpartisfound,ortheGoogleURLShortenerAPIisdown,aresultoffalseisreturned,sopleasebesuretouseyourownerrorhandling.
Nowlet'screateaninstanceofGoogleUrlApi toshortenandthenexpandaURL:
//Createinstancewithkey
$key='xhjkhzkhfuh38934hfsdajkjaf';
$googer=newGoogleURLAPI($key);
//Test:ShortenaURL
$shortDWName=$googer->shorten("https://davidwalsh.name");
echo$shortDWName;//returnshttp://goo.gl/i002
//Test:ExpandaURL
$longDWName=$googer->expand($shortDWName);
echo$longDWName;//returnshttps://davidwalsh.name
Theshorten()andexpand()methodsreturntheircounterparts,asexpected. Quitepainless,no?
TheGoogleURLShortenerAPIprovidesmuchmorethanwhatmyclassprovides,includinguserURLlistingandusagetracking. Myclassprovidesonlythebasics; I'massumingthat90%+careonlyaboutgettingtheURLshortenedsoI'vecateredtothataudience. Ihadalsothoughtaboutaddingacachingmechanismtotheclassbutsincemosteveryonehastheirownmethodofcachinginformation,Ithoughtitbesttoleavethatout. Hopefullythisclasshassomeuseforyouall!
RecentFeaturesByDavidWalshSeptember18,2017ConqueringImpostor SyndromeTwoyearsagoIdocumentedmystruggleswithImposterSyndromeandtheresponsewasimmense. Ireceivedmessagesofsupportandcommiserationfromnewwebdevelopers,veteranengineers,andevenpersonsofallexperiencelevelsinotherprofessions. I'veevencaughtmyselfreadingthepost...ByDavidWalshMay18,2011CSS Gradients WithCSSborder-radius,IshowedyouhowCSScanbridgethegapbetweendesignanddevelopmentbyaddingroundedcornerstoelements. CSSgradientsareanotherstepinthatdirection. NowthatCSSgradientsaresupportedinInternetExplorer8+,Firefox,Safari,andChrome...IncredibleDemosByDavidWalshJune24,2008Multi-SelectTransfersUsingMooTools 1.2WhileIwasaZoneLeaderforDZone'sAJAX,CSS,andPHPZones,DZone'sRickRossaskedmetocontactJeremyMartinwithregardtoahotblogposthecreated:EasyMultiSelectTransferwithjQuery.Both...ByDavidWalshApril2,2008GetSlickwithMooTools KwicksWhenIfirstsawMooToolsgraphicalnavigation,Iwasimpressed.IthoughtitwasaverysimpleyetcreativewayofusingFlash.WhenIright-clickedandsawthatitwasJavaScript,Iwasfloored.Howcouldtheyachievesuch...DiscussionFrancisGreat!youbeatmetoit,thanks
AvinashGood,thiswillhelpalot….
mortezaIt’suseful.thankyouforsharingthis.
RaymondtrangiaWhatanicetutorialjustlike
thetinyurlandthebitly
Hopeicanputthatinmysiteconcept
http://goo.gl/YK54o
chrisnice,iwroteashellscripttousegoo.glurlshortenandreverse,beforeyouneededanapikey
DavidWalshDidyouupdateittopushtheAPIkey?Ifso,I’dlovetoseeit.
EduardoMatosSincetheAPIKeyisuniqueforeachwebsite,doesn’titmakesensetoimplementthesingletonpattern?
DavidWalshIwasgoingto,butsinceyourURLsaresavedtoyouraccount,Ithoughtitsomewhatpossibletowanttousedifferentkeysinthesamescript.In99%ofcases,you’reprobablyright.
ErikAwesome..
Withyourpermission,I’lldoa.NETversionofthis..
Erik
ErikHere’sthe.NETversion:https://github.com/erikzaadi/GoogleUrlApi.net
Thanks!
ErikThereyougo:https://github.com/erikzaadi/GoogleUrlApi.net|http://erikzaadi.com/blog/2011/02/06/GoogleUrlShortenerApiForDotNET.xhtml
Thanks!
AlexYouareawesome!Thanksalot!!
PolsVeryAwesome..nicetutorial..:)
MarkIdonotwork.returnsmeblankpage.
DavidWalshDoyouhaveanAPIkey?Canyoushareyourcode?
BanhawiVerynice,thanksdavid
markmasonYOUROCK
IsearchedalloverGoogleforanexample(imahack)
THANKTHANKYOU
VronItdoesn’twork.Itreturnsablankpage.I’musingmyAPIkeyofcourse.
screamworkit’sprobablyaPHPVersionproblem…requires5.3?!?!?!
BernardoGuiPerhapsyourwebspaceproviderblockscURLrequests(allthoughphpinfo()shows“cURLsupport=enabled”)likeminedoes.
BenistonForallthosewhogetblankpages:
1.Tryincludingthebelowinthecurl
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
2.Intheapis/consolepageofyourgooglecodeaccountenabletheurlshortenservice.
taniaThisisanicearticle..
Itsveryeasytounderstand..
Andthisarticleisusingtolearnsomethingaboutit..
c#,dot.net,phptutorial
Thanksalot..!
EndijsLisovskisIfforyouthiscodedoesnotwork–checkoutwhatyougetfromcurl_exec()ifyougetFALSE,thentryaddingonemorecurloption:
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
Thishelpedme.WithoutthisSSLconnectionisdropped(showsthatcertificatevalidationfailed).
DavidFoxIwentthroughcountlesstutorialsandonlygotmycodetoworkafterreadingyourcomment.Thankyou!!!
ChrisConnorGreatpostman,thanksforthis!
kannanGreatPostDavid,Thankyouverymuch!!
Endijs,yourpostisveryusefulforme!!Thanks.
LucidoMedia,HardCodePHPThissavedmeatleast0:45h.Theremustbeafairytonight–thankssomuch!Butplease,updateyourcode-viewerplugin.Ifipress“copy”itencodes“>”as“>”allthetime(FireFox6.0).CheersfromGermany.
VarunJainHeyDavid,
INeedSomeHelpinimportingcontactlistofgmail,hotmail
isomehowgottheyahooone
canyousuggestsomething?
VarunJainandniceworkwithinbox:)
KhanhThankyousomuchforthisclass!!Yourock!!!
JuanSorrybutcanyouhelpme??WhenItrytogettheshortURLIget
{“error”:{“errors”:[{“domain”:“global”,“reason”:“invalid”,“message”:“InvalidValue”,“locationType”:“parameter”,“location”:“resource.longUrl”}],“code”:400,“message”:“InvalidValue”}}
Doyouknowwhichcanbetheproblem?Thanksalot!
VasimPadhiyarwhichapikeyshouldipasswithrequest?
eGurusThisissweet!!Iwilltrytousethisgoo.glserviceonmysite
thanksforsharing
BabarNooutputshowing!!
DanielJ.Greatscript,thanks.
JayI’veendeduponyourblogsomanytimes…italmostfeelslikeaskinganoldfriend;)
Thanksforthisclass,perfect.
p.s.yourtemplatehasissueswithgooglechrome…
NikhilDixitAwesomepost…workedperfectlyfineforme.
Canyoupleaseexplain,howapikeyworks.ShouldIalwaysgeneratekeyfromGoogleAPIconsole?Thekeyyouprovideddidn’tworkforme.
DavidWalshAPIkeyscanbecreatedatGoogle’swebsite.
Prijmthanks,itworksjustlikeacharm.bythewayisthereanylimitationsusingthefreeapikey?
dharmesh{“error”:{“errors”:[{“domain”:“global”,“reason”:“required”,“message”:“Required”,“locationType”:“parameter”,“location”:“resource.longUrl”}],“code”:400,“message”:“Required”}}
RajpalIfallconfigurationisokandstillyouaregettingblankpagethentrytogenerateAPIkeyusingnewgoogleaccount….
NipunGreatscript!Excellentworking.
FrBillyDIt’sGREAT!Thanksalotforthat!
QwrtHi,I’veaquestion!
IfI’musingApikey,Iamcertainthattheshorturlcreatedisuniqueand“eternal”?
Thx!
JamesThanksforthiscode.theshortenisworkingwellbuttheexpandisreturningempty.whatshouldidotomaketheexpandfunctionwork?
alokbanjareReallyAwesome,Ithelpedmealot,wonderfulpost…..
JoseAlejandroRealzaNowork!!Inthissiteexplainotherwayhttp://stackoverflow.com/questions/13066919/google-api-url-shortener-with-php
VickiDoyoumindifIquoteacoupleofyourpostsaslongasIprovidecreditandsourcesbacktoyoursite?Myblogsiteisintheexactsamenicheasyoursandmyuserswoulddefinitelybenefitfromalotoftheinformationyouprovidehere.Pleaseletmeknowifthisokaywithyou.Cheers!
ringoHi,I’musingthislibraryandwhenIputinalooptogeneratethousandsofshortaddresses,itstartstoreturnemptyvalues.
Whatcouldbehappening?
DavidWalshGoogle’sprobablycuttingyouoff,you’remakingtoomanyrequestsatonce.
AudasCouldnotgetthistoworkwith#marksondeeplinking–googlerejectedtheformat.
BhumiDavid,Imusttellyouthatyouareindeeddoingaverygoodjob.Thanks
MarocThanksforthisarticle:)I’musinganotherurlshortenerscriptcalledshrinkybutI’lltrythisscripttoseehowitworks.Thanksagain
komayafterincludingthiscurl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);itworksthanks
Name:Email:Website:Wrapyourcodein
延伸文章資訊
- 1Google shorten url php在PTT/Dcard完整相關資訊 - 星娛樂頭條
提供Google shorten url php相關PTT/Dcard文章,想要了解更多Short URL API有關娛樂/明星文章或書籍,歡迎來星娛樂頭條提供您完整相關訊息.
- 2Google URL Shortener PHP类 - 代码先锋网
I took a few minutes to review their API and created a very basic GoogleUrlApi class that will sh...
- 3Google URL Shortener PHP Class - David Walsh Blog
The class features two main methods: shorten and expand. Each method takes the long or short URL,...
- 410個最佳PHP網址縮短腳本 - Tuts+ Code
有大量的PHP URL縮短腳本可以開發成壹個完全可靠的貨幣化鏈接縮短服務, ... 使用Google Shortener API,這個PHP URL縮短器腳本既漂亮 又強大。
- 5Google API - URL Shortener with PHP - 中文— it-swarm.cn
Google API - URL Shortener with PHP. 我的代码如下。 URL缩短服务有效,但是当我插入 $POST 时它不会。有谁知道如何修复这个我看代码? // This ...