Shortening URLs on the fly in PHP
May 1, 2009
For a project I’m currently working on, I wanted to parse input strings looking for URLs and convert them to shortened URLs. The best service to do this in is CR.AM, which is like competing URL shortening services but with some extra features like phishing/spam protection, Twitter integration, and more. If you are doing anything involving Twitter, I highly recommend using cr.am for your URL shortening, as they’ve got some really neat things on the horizon involving Twitter.
More importantly, though, getting it set up was easy. There are two functions: one tokenizes the string to search the string for URLs (in my case, I’m looking for a string that begins with http:// or www. but your needs may vary). Many people would use regular expressions here, I didn’t. My strings are short and easy to parse this way. This post isn’t about how to find URLs in a string, it’s about how to shrink them.
The second function calls up cr.am and requests a hash for the URL. To convert URLs in a string to cr.am URLs, you just pass the string to cramify() and use the output.
-
function cram ($url) {
-
$cramHash = @file_get_contents(‘http://api.cr.am/create/’ . $url);
-
-
list($httpVersion, $statusCode, $message) = explode(‘ ‘,$http_response_header[0], 3);
-
-
if ($statusCode == 200) {
-
return "http://cr.am/".$cramHash;
-
} else {
-
return "";
-
}
-
}
-
-
function cramify ($string) {
-
$tokens = explode(" ",$string);
-
-
foreach ($tokens AS $t) {
-
if (substr($t,0,7) == "http://") {
-
$string = str_replace($t, cram($t), $string);
-
} else if (substr($t,0,4) == "www." && substr($t,4,1) != " ") {
-
$string = str_replace($t, cram("http://".$t), $string);
-
}
-
}
-
-
return $string;
-
}
PHP Scripting in Win32 Apps
March 22, 2008
This is a repost of something I put together a couple years ago, and as such it may be out of date. There are much better ways to add scripting support to your apps these days, but if you are dead-set on using PHP, this may help you do it.
In order to use the cli version of php for scripting in your win32 app, you’ll need to connect your app to PHP, send it PHP code, and read the processed output. Read more
Making Money on the Internet
March 1, 2008
It’s been almost a year and a half since I started making enough money with Glowfoto to allow myself to work on it full time. In that time, the question I’m most often asked is how can I do it too? So I guess it’s time to talk a little bit about how to take that website of yours and bring more in than you are putting out.





