handling Twitter API response codes (cURL, PHP)

A quick switch structure in PHP for handling Twitter error codes when using the Twitter API.

$val = $resultArray['http_code'];
switch ($val) {
case "200":
echo "Tweet sent.";
case "304":
echo "There was no new data to return.";
case "400":
echo "The request was invalid."
case "401":
echo "Invalid login credentials.";
case "403":
echo "The request is understood, but it has been refused."; // An accompanying error message will explain why. This code is used when requests are being denied due to update limits.
case "404":
echo "Invalid user name.";
case "406":
echo "Not Acceptable."; //Returned by the Search API when an invalid format is specified in the request.
case "500":
echo "Twitter internal server error.";
case "502":
echo "Twitter is down or being upgraded.";
case "503":
echo "The Twitter servers are up, but overloaded with requests. Try again later.";
echo "Communication error. Please try again.";

This script can be used to handle the return codes from tweeting via cURL. Simply replace the

if ($resultArray['http_code'] == 200)
echo ‘Tweet Posted’;
echo ‘Could not post Tweet to Twitter right now. Try again later.’;

section of the tweeting script with the script from this post, and you’ll be sorted. Nothing much more to say, I couldn’t even think of comments for the script because it’s self-explanatory.


using PHP to make external links appear to be internal

External redirects from your site trigger web-bots in different ways. If you want to hide them from the web-bots, and have all links on you site point internally, this script is a simple way to do so. You can either run it through a database, which makes it easy to add more links; or you can hard-code the redirects as a switch/if-else statement. The code is very simple:

if(isset($_REQUEST['rd'])) {
$new = $_REQUEST['rd'];
// DB access
$sql = "SELECT rdURL FROM rd WHERE rdName='".$new." LIMIT 1';";
$result = mysql_query($sql);
if($result) {
$row = mysql_fetch_array($result);
$newURL = $row['rdURL'];
header("Location: $newURL");
else {
header("Location: home.php");
header("Location: home.php");

The variation above looks to a database, finds the corresponding external URL, and sends the user there. To use this, just set your links within your site to be:


This keeps the links pointing within your site, but dynamically ending up externally. Obviously, replace “YOURSITENAME” and “LINKCODE” with the appropriate values. If you aren’t running a database, you can instead have a switch such as:

if(isset($_REQUEST['rd'])) {
$new = $_REQUEST['rd'];
switch($new) {
case "ABC":
$newURL = "http://google.com";
case "XYZ":
$newURL = "http://example.com";
$newURL = "home.php";
header("Location: $newURL");
else {
header("Location: home.php");
header("Location: home.php");

And there you have it.
[Edit: I missed a brace to end the switch, so I have added it in now.]

06 August 2009….

I didn’t get a chance to even plan much to say here today. Busy at uni, and steady at work tonight. I’ve been looking into OAuth and letting users sign in with Twitter. I’ve  managed to nut out the PHP side of it all for single login apps, and I’ve just got to sort out domain before launch. I’m also in the middle of chatting to Twitter about allowing me to use an additional parameter in cURL calls to their API. They’ve deprecated the source parameter, but are maintaining it for existing users of it and are willing to register new users of it if a case for justification can be made. We shall see soon.

Other than that, I’m plugging away at C# manipulation of WBMP files to PNG for uni; as well as messing with the WRK for Server 2003. This semester is turning out to be a lot of fun already. Also prepping to set up a Linux box at home, and run it as a LAMP server (or possibly just go the Ubuntu Server path) – feel free to shout out thoughts and suggestions at me if you have them.

For a bit of the YouTube thing, I found this guy recently, so I’ve posted a couple of his videos. He’s well worth the watching:

So cool. He’s got over a hundred of these and similar….I also managed to track down another copy of the video from this post, which I mentioned had been pulled the other day. So, that’s all edited and back displaying now.

Anyways, it’s late, I’m tired tonight, so I’m off to bed and I’ll put together a bit of a spiel tomorrow; as well as some more tutorials.

a brief discussion of securing PHP input

A very brief tutorial/comment on securing inputs in your PHP script to prevent HTML, JavaScript, SQL or other injection type attacks. There is basically nothing to this, it is more a matter of using a bit of common sense and not leaving open doors which are extremely simple to close without effort.

A PHP input takes in variables from a user either from a form, or directly from the URL linking to the page. In either case, a malicious user can insert data which contains scripting elements and distorts your page or, much worse, alters or gives access to your database and/or site admin. General input error checking works, but only for data entered through your site (example form.php below).

<form action="action.php">
<input type="text" name="urlfield" maxlength="80" length="20">
<br />
<input type="text" name="inputfieldtext" maxlength="40" length="20">
<br />
<input type="password" name="inputfieldpass" maxlength="40" length="20">
<br />
<input type="submit" name="submit" value="submit">


A malicious user can point a URL to your site, which they then populate with data themselves from their end. For example they make a form on their own site, which points to your results page, thereby avoiding your data integrity check before submission. In order to “allow” for this, and prevent the malicious user’s efforts getting through and doing damage, sterilising should be performed on the input before using it (example action.php below).

$url= htmlspecialchars($_REQUEST['urlfield']);
$text = htmlspecialchars($_REQUEST['inputfieldtext']);
$pass= htmlspecialchars($_REQUEST['inputfieldpass']);

or to apply it to a more “dangerous” scenario where a fuller spectrum of special characters are used:

$input= htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $input; // &lt;a href='test'&gt;Test&lt;/a&gt;

What this does is take any input data and use PHP’s inbuilt htmlspecialchars($str[, ENT_QUOTES]) function to encode HTML’s special characters so that they are not interpreted by the browser. I use the ENT_QUOTES option in order to include single quotes in the encoding. For absolute encoding use PHP’s htmlentities($str[, ENT_QUOTES]) function. This encodes ALL HTML special characters, while htmlspecialchars($str[, ENT_QUOTES]) only encodes the basic HTML special characters, which is normally useful enough for most everyday web programming.

some cool stuff, and an update from me

I found a few cool things on my perusal of Uncrate recently, so I thought I’d share them with you. They’re ALL stuff I would love to have, either for their cool, or just ’cause I could. First off we have the space trampoline which is basically two courts on a trampoline where you bounce and compete against someone to get a ball through a tunneled, netted gantry and past them. Essentially a cross between volley-ball and trampolining, the game of Spaceball was invented in the early 1960s by trampoline pioneer George Nissen. It has been hailed by Scott Carpenter, one of NASA’s original Mercury Seven astronauts, as

the best conditioning exercise for space travel

The game requires hand-eye coordination, balance, timing, and trickery to get your ball past your oponent to the other side.

Next up is the predator pool table from Hurricaine Billiards. Nothing much to say here really, just plain awesome, and it would great in any Man Cave. Also looking perfect in any man cave would be the markham console bar from Pottery Barn. Just a very stylish, rustic look bar for the man who is a man. To serve your drinks from the bar, a real man’s set of tumblers is required, and these concrete tumblers from Charles and Marie are just the thing. Rugged, sturdy, and solid.

For going a little over the top you could get yourself a fully chromed lamborghini murcielago which has been seen in London. Not quite my cup of tea (but I wouldn’t say no to a Lamborghini of any sort!), but sure to tempt somebody if it comes up for sale. [thanks to jalopnik.com for the Lambo tip off]

Back in the real world, ie stuff I may actually get in the semi-near future, I had a couple of monologues over the past week regarding Apple and their App Store so I thought I’d better have a little spiel about good Apple stuff. I did say that I don’t hate Apple and, while I’m not a fan-boi, I do love their products. They are definitely class. An excellent combining of aesthetics and design, with functioning products that definitely achieve their purpose. While generally more expensive than their counterparts, I personally feel that the price is somewhat justified. That said, I think computers (and most consumer goods) do cost a little too much for the most part. Because I am well aware that my opinion carries a massive amount of weight, and influences everyone that matters, I just thought I’d out this out there and balance my past rants about Apple. I still think they are being a bit out of synch with reality but, that said, who knows what cunning plan Apple has and is working towards with their latest actions. We all know that Apple has to be one of the slickest PR and marketing operations in the world, and they would have expected the backlash they are currently receiving.

I spent quite a bit of time today playing with T-SQL and SQL Server, and had a fair amount of fun, I have to say. While at first the vaguaries and slight variations between MySQL (my native SQL for all my PHP work) and T-SQL syntax were “fluffy”, I cam around pretty quick and caught on to some nice tricks for my coding there. Admittedly I hadn’t done a great amount of Prepared Statements and Stored Functions in MySQL either, but between T-SQL and SQL Server they really came together tidily and easily. I’m liking Microsoft’s efforts there so far. I’ll have to put up a few little tricks tomorrow as a mini-tutorial, just to share something.

I also noticed today that one of my YouTube videos from a prior post has been removed at owner’s request. A bit stink really as it’s been on YouTube for a couple of years, and only just got pulled on the last few days. I’m pretty certain it’s not my massive viewership stats on here that have pushed traffic over to it and had it pulled, but I’ll be trying to find another copy of it in the next few days to get it back in action.

Enough from me now, back to the study thing now that I’m home (I wrote most of this in breaks at work!!).

Dynamic JavaScript generation with PHP

Creating dynamic JavaScript on the fly can be useful when needing to target differing dynamically generated xml files for example. In my example below, I am creating the xml as I do here, and then using the dynamic JS to pass this new xml to a Flash template for display on the fly. The necessity for a dynamic JS script in this case is that the name of the xml changes dynamically, and also the JS script is named dynamically with a random value in order to prevent caching of the script.

To begin, the script is predominantly static, and is simply written to a JS file. Make sure every line is ended with the \r\n chararcters in order to be correctly written to the file. Essentially as below. I am using dynamic variables for the Flash height and the xml name:


$xyz = fopen("xml/".$jsname, "w");

fwrite($xyz, "<!--\r\n");
fwrite($xyz, "if (AC_FL_RunContent == 0 || DetectFlashVer == 0) {\r\n");
fwrite($xyz, " alert(\"This page requires AC_RunActiveContent.js.\");\r\n");
fwrite($xyz, "} else {\r\n");
fwrite($xyz, " var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);\r\n");
fwrite($xyz, " if(hasRightVersion) {\r\n");
fwrite($xyz, " AC_FL_RunContent(\r\n");
fwrite($xyz, " 'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',\r\n");
fwrite($xyz, " 'width', '870',\r\n");
fwrite($xyz, " 'height', '".$heightval."',\r\n");
fwrite($xyz, " 'scale', 'noscale',\r\n");
fwrite($xyz, " 'salign', 'TL',\r\n");
fwrite($xyz, " 'bgcolor', '#777788',\r\n");
fwrite($xyz, " 'wmode', 'transparent',\r\n");
fwrite($xyz, " 'movie', 'flash',\r\n");
fwrite($xyz, " 'src', 'flash',\r\n");
fwrite($xyz, " 'FlashVars', 'library_path=flash/librarypath&xml_source=xml/".$xmlname."',\r\n");
fwrite($xyz, " 'id', 'my_flash',\r\n");
fwrite($xyz, " 'name', 'my_flash',\r\n");
fwrite($xyz, " 'menu', 'true',\r\n");
fwrite($xyz, " 'allowFullScreen', 'true',\r\n");
fwrite($xyz, " 'allowScriptAccess','sameDomain',\r\n");
fwrite($xyz, " 'quality', 'high',\r\n");
fwrite($xyz, " 'align', 'middle',\r\n");
fwrite($xyz, " 'pluginspage', 'http://www.macromedia.com/go/getflashplayer',\r\n");
fwrite($xyz, " 'play', 'true',\r\n");
fwrite($xyz, " 'devicefont', 'false'\r\n");
fwrite($xyz, " );\r\n");
fwrite($xyz, " } else {\r\n");
fwrite($xyz, " var alternateContent = 'This content requires the Adobe Flash Player. '\r\n");
fwrite($xyz, " + '<a href="http://www.macromedia.com/go/getflash/">Get Flash</a>.';\r\n");
fwrite($xyz, " document.write(alternateContent);\r\n");
fwrite($xyz, " }\r\n");
fwrite($xyz, "}\r\n");
fwrite($xyz, "// -->\r\n");



As you can see, I pass in variables $jsname, $xmlname, and $heightval which are used to construct the script. This is then called by setting a dynamic call to the JS script within the webpage itself using PHP, as below:


$rndnum = rand(1234, 9876);
$jsname = "script_name_".$rndnum.".js";
// make the JavaScript here
echo '';


This can be linked to a script to create XML dynamically, as here, and there you have a truly dynamic display.

first post for August…..

Here’s my first post for August. Found this cool list of 20 technothriller tropes we hope never to see again on io9.com. Built a new site over the weekend, just getting the PHP/XML linking back to the other site I’ve been doing. So now I’ve got two to launch in the next week or two. Fun times to be had by all!!

Assignments are starting to be released at uni now, so the workload is actually beginning to kick in. Not too bad though, but it means I need to focus on that instead of fun projects. Ah, well.

Time to check out the beginnings of the Iron Man 2 hype here. That’s the Stark Industries website. Also, I just won tickets to GI Joe, so I guess I’ll be checking it out soon. Hopefully it lives up to the hype and isn’t destroyed by Hollywood marketing crap. GI Joe is an icon of our generation, so I’m hoping the movie gives it the respect it deserves and doesn’t turn it to $#@&. Hey, they made Iron Man work, so there is still hope.

I have a few opinions about various stuff that’s been going on, but I can’t be bothered pulling it all together now. So, I’ll do a big post tomorrow to catch up on my ranting and opinionating.

Peace, out.