Google URL Shortener PHP Class - David Walsh Blog

文章推薦指數: 80 %
投票人數:10人

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:Wrapyourcodeintags,linktoaGitHubgist,JSFiddlefiddle,orCodePenpentoembed! ContinuethisconversationviaemailGetonlyrepliestoyourcomment,thebestoftherest,aswellasadailyrecapofallcommentsonthispost.Nomorethanafewemailsdaily,whichyoucanreplyto/unsubscribefromdirectlyfromyourinbox.UseCodeEditor



請為這篇文章評分?