Skip to content

Instantly share code, notes, and snippets.

@aaronpk
Created March 25, 2011 18:45
Show Gist options
  • Select an option

  • Save aaronpk/887361 to your computer and use it in GitHub Desktop.

Select an option

Save aaronpk/887361 to your computer and use it in GitHub Desktop.
anth.ro URL shortener
// Read more: http://neverusethisfont.com/blog/2011/03/url-shortener-as-a-search-interface/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/search?btnI=I\'m+Feeling+Lucky&q=' . urlencode($_GET['code']) . '+site%3Acyborganthropology.com');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); // Don't follow redirects, we want the first Location header
curl_setopt($ch, CURLOPT_HEADER, TRUE); // Return the headers in the output curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla"); // Set the user agent to Mozilla so Google doesn't block the query
curl_setopt($ch, CURLOPT_NOBODY, TRUE); // Don't include the response body in the output
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return the response in a variable instead of printing it out
$response = curl_exec($ch);
// If there was a Location header found, use it, otherwise, Google couldn't find a match
if(preg_match('/Location: (.+)/', $response, $match)) {
$url = parse_url(trim($match[1]));
if($url && is_array($url)) {
$query = array();
// If the search result included query string parameters, parse those out
if(array_key_exists('query', $url)) {
parse_str($url['query'], $query);
}
// Add the search term as the "q" parameter. This is so Google Analytics will treat this as a "site search" query
// and include it in the search analytics. You'll also need to add "q" to the "include site search" section in Google Analytics
$query['q'] = $_GET['code'];
// Add "anth.ro" as the utm_source
$query['utm_source'] = 'anth.ro';
// Add "ShortURL" as the medium. These end up appearing in the "Traffic Sources" list as "anth.ro / ShortURL"
$query['utm_medium'] = 'ShortURL';
$q = http_build_query($query);
// Redirect the user to the page specified by google with our additional parameters included
$location = 'http://cyborganthropology.com' . $url['path'] . '?' . $q;
header('HTTP/1.1 302 Moved Temporarily');
header('Location: ' . $location);
die();
}
}
// If there were no results returned from Google's I'm feeling lucky button, redirect to a Google search page
// This most likely happens on a typo
header('HTTP/1.1 302 Moved Temporarily');
header('Location: http://www.google.com/search?q=' . urlencode($_GET['code']) . '+site%3Acyborganthropology.com');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment