Skip to content

Instantly share code, notes, and snippets.

@nhalstead
Forked from dchomicz/api-test.php
Last active June 10, 2017 01:27
Show Gist options
  • Save nhalstead/72ea5c82c580253262ef04c575b1d647 to your computer and use it in GitHub Desktop.
Save nhalstead/72ea5c82c580253262ef04c575b1d647 to your computer and use it in GitHub Desktop.
Shorte.st Sample API File. Works with V1 of their API
<?php
if(!isset($authKey)) { $authKey = "YOUR KEY HERE"; }
if(!isset($longURL)) { $longURL = "http://join-shortest.com/ref/46cc802beb?user-type=new"; }
$storeShortLink = "linkout";
DEFINE("apiBaseAddress", "https://api.shorte.st/v1/data/url");
function formatURLPostData($url){ return "urlToShorten=".$url; }
function http_exist($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { return "https://" . $url; }
else { return $url; }
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, apiBaseAddress);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( "public-api-token: ".$authKey ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,formatURLPostData(http_exist($longURL)));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,0);
$result = curl_exec($ch);
$statusCode = curl_getInfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $result."\n";
if($statusCode == 200){
$json = json_decode($result, true);
if($json["status"] == "ok"){ $$storeShortLink = $json["shortenedUrl"]; }
else{ echo "Some errror On the Server Side of Shorte.st! Recived Header 200 but did not recive the Shortened URL!!"; }
}
elseif($statusCode == 400){ echo "Sorry! The URL you want to shorten is invalid, or the API has changed!"; }
elseif($statusCode == 302){ echo "Sorry! The Api key you supplied is invalid!"; }
elseif($statusCode == 500) { echo "Shorte.st has an internal Error!"; }
else{ echo "Sorry! Unknown error"; }
?>
@nhalstead
Copy link
Author

nhalstead commented Jun 10, 2017

Just define $authKey and $longURL to convert the $longURL to $linkout (The Short Link)
If you don't want to define the API Key every Time just set it in the file.

This Gist also handles the User Providing non-specified Request Scheme.

$longURL = "verylongurl.com/hello/test/havefun";
require_once("api-shorte.php");
echo $linkout;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment