Google API - URL Shortener with PHP - Stack Overflow

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

$shortLink = get_object_vars($json); echo "Shortened URL is: ".$shortLink['id'];. It could be just my php installation, but the original line ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore GoogleAPI-URLShortenerwithPHP AskQuestion Asked 9yearsago Active 3years,3monthsago Viewed 35ktimes 20 7 Mycodeisbelow.TheURLshorteningserviceworks,butitdoesn'twhenIinsertmy$POST.Doesanyoneknowhowtofixthismylookingatthecode? //ThisistheURLyouwanttoshorten $longUrl='http://www.mysite.com/XXXXX/XX/$_POST['qrname']'; //GetAPIkeyfrom:http://code.google.com/apis/console/ $apiKey='MyAPIKey'; $postData=array('longUrl'=>$longUrl,'key'=>$apiKey); $jsonData=json_encode($postData); $curlObj=curl_init(); curl_setopt($curlObj,CURLOPT_URL,'https://www.googleapis.com/urlshortener/v1/url'); curl_setopt($curlObj,CURLOPT_RETURNTRANSFER,1); curl_setopt($curlObj,CURLOPT_SSL_VERIFYPEER,0); curl_setopt($curlObj,CURLOPT_HEADER,0); curl_setopt($curlObj,CURLOPT_HTTPHEADER,array('Content-type:application/json')); curl_setopt($curlObj,CURLOPT_POST,1); curl_setopt($curlObj,CURLOPT_POSTFIELDS,$jsonData); $response=curl_exec($curlObj); //Changetheresponsejsonstringtoobject $json=json_decode($response); curl_close($curlObj); echo'ShortenedURLis:'.$json->id; phpurlcurlqr-code Share Improvethisquestion Follow editedOct20'13at16:03 GottliebNotschnabel 9,0181717goldbadges7070silverbadges109109bronzebadges askedOct25'12at10:47 ItsJoeTurnerItsJoeTurner 48722goldbadges66silverbadges2121bronzebadges 2 Removeorcommentecho'ShortenedURLis:'.$json->id;aftercheck.!Itworks. – NiravRanpara Oct25'12at10:49 1 Idon'tknowwhereyoufindthiscodeintheAPIdoc,butthanks! – Macbernie Nov26'14at15:49 Addacomment  |  8Answers 8 Active Oldest Votes 11 Tryasbelow $longUrl='http://www.mysite.com/XXXXX/XX/'.$_POST['qrname']; Theabovewillwork. Share Improvethisanswer Follow editedOct25'12at10:56 answeredOct25'12at10:50 HackablewebHackableweb 37211goldbadge55silverbadges1616bronzebadges 2 9 YourproblemisnothingaboutcURL,it'saboutconcatenatingvariablesandstringinPHP,seephp.net/manual/de/language.types.string.php – GottliebNotschnabel Oct20'13at16:00 MayIknowwhyIcan'tuseOP'sPhpcodeandshortentheurl?Itreturnmeerrormessagedomain":"usageLimits","reason":"dailyLimitExceededUnreg","message":"DailyLimitforUnauthenticatedUseExceeded.Continueduserequiressignup."?I'dcheckmyHttpReferrer,Quota,everythinglooksgood.... – Mavichow Jun14'16at6:19 Addacomment  |  7 $longUrl="http://www.xxxxxxx.com"; $postData=array('longUrl'=>$longUrl); $jsonData=json_encode($postData); //4 $curlObj=curl_init(); curl_setopt($curlObj,CURLOPT_URL,'https://www.googleapis.com/urlshortener/v1/url?key=yourappkey'); curl_setopt($curlObj,CURLOPT_RETURNTRANSFER,1); curl_setopt($curlObj,CURLOPT_SSL_VERIFYPEER,0); curl_setopt($curlObj,CURLOPT_HEADER,0); curl_setopt($curlObj,CURLOPT_HTTPHEADER,array('Content-type:application/json')); curl_setopt($curlObj,CURLOPT_POST,1); curl_setopt($curlObj,CURLOPT_POSTFIELDS,$jsonData); //5 $response=curl_exec($curlObj); $json=json_decode($response); //echo"

";
//print_r($json);exit;
//6
curl_close($curlObj);

//7
if(isset($json->error)){
echo$json->error->message;
}else{
echo$json->id;
}













Share




Improvethisanswer




Follow















editedOct25'17at6:16

















answeredApr20'17at4:56





debasishdebasish

70511goldbadge88silverbadges1414bronzebadges






















	


Addacomment
 | 















6
























youarepassingthephpvariablebetweenthesinglequotessoitwillnotbeparsed.
passitbetweendoublequoteslike

$longUrl="http://www.mysite.com/XXXXX/XX/$_POST['qrname']";


ORconcatinatelikethis

$longUrl='http://www.mysite.com/XXXXX/XX/'.$_POST['qrname'];













Share




Improvethisanswer




Follow















editedOct20'13at15:57





kleopatra

49.8k2727goldbadges9393silverbadges193193bronzebadges









answeredOct20'13at15:55





MahakChoudharyMahakChoudhary

8651313silverbadges1212bronzebadges
















1







2





IpreferthisansweroverHackableweb'sasitdoesnotjustsolvetheproblem,butalsotellstheOP,why!


– GottliebNotschnabel

Oct20'13at16:01





	


Addacomment
 | 















6
























Youhaveakey,butyouarenotusingitcorrectly

Youshouldappendittotheurl,don'tsendthekeyinthepost

https://www.googleapis.com/urlshortener/v1/url?key='.$apiKey


Pleasecheckhttps://developers.google.com/url-shortener/v1/url/insert












Share




Improvethisanswer




Follow















editedMar19'15at20:00

















answeredFeb10'15at22:48





ursuleacvursuleacv

1,0391212silverbadges1616bronzebadges
















1







4





Thissolveditforme,someoftheexistingdocumentationisoutofdate.


– MarcF

Mar19'15at13:41





	


Addacomment
 | 















1
























Don'thaveenoughreputationpointsyettocomment,butIgotthisworkingfinebyreplacingtheline:

echo'ShortenedURLis:'.$json->id;


with:

$shortLink=get_object_vars($json);
echo"ShortenedURLis:".$shortLink['id'];


Itcouldbejustmyphpinstallation,buttheoriginallinekeptthrowinga500InternalErrorforme.












Share




Improvethisanswer




Follow

















answeredJan22'14at21:02





mittramittra

2911silverbadge1111bronzebadges






















	


Addacomment
 | 















1
























$longUrl,'key'=>$apiKey);
$curlObj=curl_init();
$jsonData=json_encode($postData);
curl_setopt($curlObj,CURLOPT_URL,'https://www.googleapis.com/urlshortener/v1/url?key='.$postData['key']);
curl_setopt($curlObj,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlObj,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curlObj,CURLOPT_HEADER,0);
curl_setopt($curlObj,CURLOPT_HTTPHEADER,array('Content-type:application/json'));
curl_setopt($curlObj,CURLOPT_POST,1);
curl_setopt($curlObj,CURLOPT_POSTFIELDS,$jsonData);
$response=curl_exec($curlObj);
$json=json_decode($response);
curl_close($curlObj);
if(isset($json->error)||$json==null){
return$longUrl;//retrunsameurlincaseoferrorornullresponse
}else{
return$json->id;//returnshortedurl
}
}
//usethisfunctionhere
$longUrl='https://www.w3schools.com/';
echoshort_url($longUrl);//printshorturl

//Ifyouwanttoreturnshorturltolongurlusebelowfunction
functionlong_url($shortUrl){
$apiKey='***********';//putyourGOOGLEAPISHORTENINGKey
$params=array('shortUrl'=>$shortUrl,'key'=>$apiKey,'projection'=>"ANALYTICS_CLICKS");
$final_url='https://www.googleapis.com/urlshortener/v1/url?'.http_build_query($params);
$curlObj=curl_init($final_url);
curl_setopt($curlObj,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlObj,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curlObj,CURLOPT_HEADER,0);
curl_setopt($curlObj,CURLOPT_HTTPHEADER,array('Content-type:application/json'));
$response=curl_exec($curlObj);
$json=json_decode($response);
curl_close($curlObj);
if(isset($json->error)||$json==null){
return$shortUrl;
}else{
return$json->longUrl;
}
}
//FunctionUsehere
echo"
";//Fornextline $shortUrl='';//puttheshorturlgeneratedfromabovefunction echolong_url($shortUrl);//getlongurl ?> Share Improvethisanswer Follow editedApr23'18at11:28 answeredApr13'18at13:35 MukeshKumarMukeshKumar 933bronzebadges Addacomment  |  0 Trywiththiscode.Iisworkingforme. $api_key='YOUR_KEY'; $request_data=array( 'longUrl'=>'YOUR_LONG_URL' ); $curl_obj=curl_init(sprintf('%s/url?key=%s','https://www.googleapis.com/urlshortener/v1',$api_key)); curl_setopt($curl_obj,CURLOPT_RETURNTRANSFER,true); curl_setopt($curl_obj,CURLOPT_POST,true); curl_setopt($curl_obj,CURLOPT_HTTPHEADER,array('Content-type:application/json')); curl_setopt($curl_obj,CURLOPT_POSTFIELDS,json_encode($request_data)); curl_setopt($curl_obj,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($curl_obj,CURLOPT_SSL_VERIFYHOST,false); $response=curl_exec($curl_obj); $json=json_decode($response); curl_close($curl_obj); var_dump($json); die(); Share Improvethisanswer Follow answeredJun21'17at7:20 UWU_SANDUNUWU_SANDUN 9071010silverbadges1818bronzebadges Addacomment  |  0 replace$longUrl='http://www.example.com/XXXXX/XX/$_POST['qrname']'; withthefollowing $longUrl='http://www.example.com/XXXXX/XX/{$_POST['qrname']}'; Share Improvethisanswer Follow answeredAug5'18at16:11 kylefardykylefardy 1 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedphpurlcurlqr-codeoraskyourownquestion. TheOverflowBlog BuildingaQAprocessforyourdeeplearningpipelineinpractice Podcast393:250wordsperminuteonachordedkeyboard?Onlyifyoucan... FeaturedonMeta Nowlive:Afullyresponsiveprofile PleasewelcomeValuedAssociates#999-BellaBlueϩ-SalmonofWisdom Linked 1 whyiamgettingforbiddenerroringoogleurlshotnerapi? Related 4673 WhatisthedifferencebetweenaURI,aURLandaURN? 2660 EncodeURLinJavaScript? 1970 GetcurrentURLwithjQuery? 5289 WhatisthemaximumlengthofaURLindifferentbrowsers? 2724 HowdoImodifytheURLwithoutreloadingthepage? 3369 GetthecurrentURLwithJavaScript? 2614 HowdoIgetaYouTubevideothumbnailfromtheYouTubeAPI? 4925 HowtochangetheURI(URL)foraremoteGitrepository? 4821 Reference—WhatdoesthissymbolmeaninPHP? 3383 HowdoIPOSTJSONdatawithcURL? HotNetworkQuestions Howcanasinglecreaturesafelyfleefromacombat? Maintaininganadvantageinaworldofreactionlessdrives Uselessmemoryandmakeitrunsfaster(ifitispossible) ExplainhowtheThiefRogue'sUseMagicDeviceisn'toverpowered HowisCaptainAmericaabletowieldMjölnirexpertlyinEndgame? Whatisthistacticcalled? HowisTheCulture'suniversepopulatedbyhumansifcurrenthumancultureonearthexistscontemporaneouslywithit? Oldsubpanelhasdual60Abreakerfeedinglighting TraveledonaninvalidESTA.HowscrewedamI? In"TheMartian",whydidtheycatchtheprobe? Escapecharactersinsedtransliterate IsanegativePCRCovid-19testvalidforsatisfyingthetestingrequirementoftravellingtotheUSA? "Temporarynew"MacOSinstallationfortestinginmyownmachine IsBabeRuth'sstatementmeaningful? Whydon'twefindplanetoidsatL4/L5? Isthereanywhereyoucangotothe180thmeridianonfoot? WhatareATSinBetjeman'sHenley-upon-Thamespoem(beefyATSwithouttheirhats) Supervisoraskedforzoommeetingdidn’tshowup Howtorestoreabrokensudoersfilewithoutbeingabletousesudo? DoesPredators'Hourapplytocreaturesthatcomeintoplayafteritresolves? WhydoAmericanschoosewirenutsoverreusableterminalblockslikeWagooffers? 'Failtotake'interpretation Whatmakesanendingtragic? IsSO(4)asubgroupofSU(3)? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-php Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  


請為這篇文章評分?