handling Twitter API response codes (cURL, PHP)

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

<?php
$val = $resultArray['http_code'];
switch ($val) {
case "200":
echo "Tweet sent.";
break;
case "304":
echo "There was no new data to return.";
break;
case "400":
echo "The request was invalid."
break;
case "401":
echo "Invalid login credentials.";
break;
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.
break;
case "404":
echo "Invalid user name.";
break;
case "406":
echo "Not Acceptable."; //Returned by the Search API when an invalid format is specified in the request.
break;
case "500":
echo "Twitter internal server error.";
break;
case "502":
echo "Twitter is down or being upgraded.";
break;
case "503":
echo "The Twitter servers are up, but overloaded with requests. Try again later.";
break;
default:
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’;
else
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:

<?php
if(isset($_REQUEST['rd'])) {
$new = $_REQUEST['rd'];
// DB access
include("db.php");
$sql = "SELECT rdURL FROM rd WHERE rdName='".$new." LIMIT 1';";
$result = mysql_query($sql);
mysql_close($conn);
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:

"http:⁄⁄YOURSITENAME⁄go.php?rd=LINKCODE"

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:

<?php
if(isset($_REQUEST['rd'])) {
$new = $_REQUEST['rd'];
switch($new) {
case "ABC":
$newURL = "http://google.com";
break;
case "XYZ":
$newURL = "http://example.com";
break;
default:
$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).

<html>
<head>
....
</head>
<body>
<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">

</form>
</body>
</html>

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).

<?php
$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:

<?php
$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:

<?php

$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");

fclose($xyz);

?>

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:

<?php

$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.

validate email in PHP

Here’s a simple script to validate an email address. This only checks for structure, and doesn’t confirm the validity of the address (ie does it actually exist).

<?php
function validate($email) {
// First, we check that there's one @ symbol, and that the lengths are right
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
return false;
}
}
}
return true;
}
?>

[Edit – 24.07.09: I’ve updated this script as I found some more detail of email address definitions, ie RFC 2822]

I’m working on a “confirmation” script which will ping or otherwise check the submitted email address for validity as an actual existing address.

This post here also has an even better email validator script (Listing 9) which also tests the email domain against a DNS.

generate random password in PHP

Just thought I’d share this little script for generating a random password with PHP. You can customise the length and strength of the password when calling the method.

<?php
function generatePassword($length, $strength) {
$vowels = 'aeiouy';
$consonants = 'bcdfghjklmnpqrstvwxz';
if ($strength == 1) {
$consonants .= 'BCDFGHJKLMNPQRSTVWXZ';
}
if ($strength == 2) {
$vowels .= "AEIOUY";
}
if ($strength == 4) {
$consonants .= '123456789';
}
if ($strength == 8 ) {
$consonants .= '@#$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
}
else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}
?>

you then simply call the function from within your script as:

<?php
$newPass = generatePassword(length, strength);
?>

And there you have it, a randomly generated password. You can play with the strength factros and variables if you wish; entirely up to you.

a new semester begins

Today is Tuesday (duh!), and uni started back yesterday. I am lucky enough to start my week at 8am on a Monday, so no easing into the lecture schedule for me. I was pleasantly surprised to find that one of my papers has already released the first assignment. This means that I will actually be able to get onto it in a timely manner. Normally they all wait until third/fourth week to all release them at the same time, and then are all due at the same time. I’m a bit sick today, so I’ll be starting on this assignment tomorrow and trying to get it done by the end of the weekend.

Also discovered that one of my other papers get to play with Windows source code (WRK). Very cool!! It’s only the WRK for Server 2003 but, as they say, that’s pretty much the same as XP, which is almost the same as Vista; so there we go. My schedule isn’t too bad for my – touch wood – final semester before returning to the real world, so I’m not stressing over possible time issues at all. I’m doing mainly CompSci papers to finish off, but most of them are network related, so I’m really weighing towards mainly InfoSys in reality. I’ll also be completing my CCNA semesters 3 & 4 as part of one of my InfoSys papers which is a bonus. And, I believe my other InfoSys paper allows me to sit an Oracle certification at the end too. Look at me the uber-student.

Check this link out for a bit of a laugh when you get the chance (make sure you have sound!). It is safe for work. Also, notpron.com is classic. It’s also safe for work, but the url my cause filters to trigger, so best to do it at home. I have to put in the following video, just because I hadn’t seen it for ages, and I re-watched it again over the weekend. It’s still as ridiculously funny as it was when it first came out!!

As you’ll soon see, I’ve been going through my favourites folder on YouTube, and I went right to the very back end for the oldest (possibly forgotten) vids I could track down. Here’s Best Baby Break Dance:

and this one of a guy catching glasses with his face:

I’ll end the queue of videos with this one. It’s actually quite heart-touching, so enjoy and be happy for him:

I’ll be doing some more tuts this afternoon, or tomorrow. Something to do with XML and HTTP now that I’ve had a bit of fun setting that up for my site (launch will be within the next two weeks I think!!) and coordinating it with JS so that other sites can call to mine and get responses back. I’ll also look at something to do with dynamic JS creation from PHP.