PHP

Watch out for PHP shorthand

November 20th, 2010    2 Comments

Coders of a certain persuasion love shorthand: where two or three characters can work the same magic as six or seven characters. This frame of mind has a venerable history in UNIX programming (and before) where commands, tools and programs got names like rm, ls, man, cat, vi and so on.

Giving commands cryptic names just to save a few key presses might seem weird but if everything has to be typed at a command line, then the shorter the command the better – once you’ve memorised them. And the cryptic names have the added benefit of bolstering the guru culture that ruled in programming until IDEs like Visual Studio spoiled the party by allowing any snot-nosed kid to create great software just by selecting from IntelliSense popups. [I’m joking – just in case that isn’t clear.  :-) ]

PHP also has its shorthand, and today – thanks to this fact – I wasted a good 10 minutes scratching my head over a broken PHP script I wrote back in 2006.

The script was outputting this in a form field on the Web page:

<?=trim($fields['issuetext'])?>

I couldn’t figure out why. I knew it had been working before. And, yes, I was running the PHP from a different Web server – but my phpinfo.php page showed me that PHP was working okay. I realised that <?=trim was non-standard, but changing it to <?php =trim broke the page entirely, and I knew it had been working okay before.

The answer, this page eventually reminded me,  is that <?=WHATEVER?> is the PHP shorthand for <?php echo(WHATEVER) ?> and to make it work you need to set short_open_tag to “On” in the server’s php.ini file.

Scrolling down my phpinfo.php page confirmed that I didn’t have this enabled:

short_open_tag

Memo to self:
Think twice before doing stuff that’ll save me seconds today if it might cost me (or someone else) minutes of aggravation in 6 or 12 months time.

Comments

  1. User Gravatar Matt said:

    February 2nd, 2011 at 5:25 pm (#)

    I respectfully disagree. Only use variables in your shorthand echo's, never function calls ... otherwise they're very useful.

  2. User Gravatar Ivan said:

    November 20th, 2011 at 6:25 am (#)

    I spent two hours on net trying to find this solution. That shothand was driving me nuts specially the short_open_tag in the php.ini file.

    Thank you.

Leave a comment

 

YOURLS: Your Own URL Shortener

October 24th, 2010    2 Comments

Shorteners in brief

If you use twitter you'll be familiar with the concept of URL shortening. You want to tweet about that video where the dog thinks its own leg is trying to steal the bone but you've only got 140 characters to say what the video is and include the link to YouTube. URL shorteners allow you to change:

http://www.youtube.com/watch?v=tJgMueh-zLM&feature=youtu.be
to:
http://bit.ly/dfzFE6

Even if you don't use twitter URL shorteners can come in handy. For example, at the beginning and end of the ITauthor podcast I use some music by Amplifico and I like to put a link to their page on musically.com in the MP3 description that you can read on your iPod when you're listening to the podcast. It's much nicer to give the URL http://tinyurl.com/amplifico, rather than http://www.musicalley.com/music/listeners/artistdetails.php?BandHash=cdef1ecef0d12844ed816b922fcada5d.

Some popular URL shorteners

  • tinyurl – This was the first URL shortener most of us will have come across - way back before twitter appeared and ramped up demand for short URLs, leading to a proliferation of shortening services.
  • bit.ly – twitter supported use of bit.ly which made it a popular service. Recently there have been doubts raised about the wisdom of using a Libyan registered domain (.ly) as the Libyan government have said they will take down domains that contain immoral content.
  • j.mp – This is just bit.ly but with 2 fewer characters. If you already have a bit.ly URL you can use the same shortened path, stick it on the end of the j.mp domain and save yourself those 2 precious characters. For example, the dog video gets shortened to http://j.mp/dfzFE6.
  • goo.gl – Google are one of the many big companies that have now got into the URL shortening business.
  • is.gd – just a nice simple Web page that produces nice short URLs.
  • ... I could go on, but there's not a whole lot of difference between these services.

Your very own URL shortener

Shortening URLs isn't difficult to do and there are a selection of free URL shorteners that allow you to produce your own short URLs. All you need is your own Web site and your own domain name. So, for example, I own the domain name itauthor.com, so I can produce short URLs like http://itauthor.com/1 or (more descriptively) http://itauthor.com/podcast36.

imageThe solution I'm using is called yourls. It's a series of PHP scripts with a MySQL database behind it. So if you're already running a Web site based on PHP and MySQL (for example, a WordPress blog) then you've already got everything you need. Just upload it and browse to the admin page. The yourls contains all the instructions you need.

The only problem I had was as a result of some changes not getting written to my .htaccess file in my root Web directory. I had to go and manually add the following at the start of the .htaccess file :

# BEGIN YOURLS
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !^itauthor.com$
RewriteRule . - [S=3]
RewriteRule ^([0-9A-Za-z]+)/?$ /yourls-go.php?id=$1 [L]
RewriteRule ^([0-9A-Za-z]+)\+/?$ /yourls-infos.php?id=$1 [L]
RewriteRule ^([0-9A-Za-z]+)\+all/?$ /yourls-infos.php?id=$1&all=1 [L]
</IfModule>
# END YOURLS

You don't need the two lines highlighted in red if you're not running WordPress, or anything similar that relies on being able to rewrite URLs. The yourls documentation says, in this situation, you need to put all the yourls files and directories in a subdirectory of your root Web directory (e.g. in a directory called "u"). However, this means that you need to include the subdirectory in the YOURLS_SITE configuration setting and it'll then be part of the shortened URL (e.g. http://itauthor.com/u/123, which kind of defeats the purpose. So the two red lines get around this by diverting URLs without "www" to yourls.

The first of the red lines says "only apply the following rule if the URL doesn't begin http://itauthor.com". The second red line says "if the previous condition resolved as true then skip the following three rules".

This seems a bit like a double negative but it's necessary because RewriteCond only applies to the RewriteRule that immediately follows it, so we need the skip rule. The result is that, on my site, the three RewriteRules that divert page requests to the yourls PHP scripts are only applied to URLs beginning http://itauthor.com. The "[L]" means "last" - in other words, if this RewriteRule is applied don't go any further, so we never reach the rules that WordPress uses, which are further down the .htaccess file. If a URL begins http://www.itauthor.com then the yourls rules are skipped and the URL is processed using the WordPress rules.

This means that http://itauthor.com/2 is sent to yourls to retrieve the original, long URL from its database, whereas http://www.itauthor.com/podcasts is sent to WordPress to create a Web page using content from its database.

What's the point?

Well, okay, there's really no point other than a bit of personal domain name vanity. Why have your tweets full of bit.ly or goo.gl URLs when you could have your own domain name showing up – even if clicking the link doesn't take your tweet readers to your Web site.

And to finish, just because I find it very funny, here's that video of the back leg bone thief:

Potentially similar posts

Leave a comment



PHP: swapping round columns & rows in field/record data

July 20th, 2010

I'm blogging this just because I couldn't find a solution via Google so I had to figure this out myself and it might save you some time if you're trying to do the same thing.

I have some PHP script that grabs some data out of a MySQL table. However, rather than display it in the normal way:

resultField1 resultField2 resultField3 resultField4 resultField5
2010-12-24 55 red 1 Miles Davis
2011-03-30 65 yellow 0 Kevin Coyne
2011-06-16 82 purple 1 Kate Bush

I want to swap round the rows and columns so that I display it like this:

resultField1 2010-12-24 2011-03-30 2011-06-16
resultField2 55 65 82
resultField3 red yellow purple
resultField4 1 0 1
resultField5 Miles Davis Kevin Coyne Kate Bush

The thing to be aware of is that when you use mysql_fetch_assoc to get stuff out of a database, for example:

while($resultArray = mysql_fetch_assoc($selectQuery)) {
    Do stuff here ...
}

what you get back is an associative array (that's a hash for folks like me who learnt this stuff in Perl before arriving at PHP). So in the above example $resultArray is an associative array - that is, a set of key/value pairs where the key is the field name and the value is the value in that field for that record. Each iteration through the while loop you get a different record.

So, in effect, it's like an array of associative arrays.

However, what you want in order to be able to swap round fields and columns is an associative array of arrays - that is, a set of key/value pairs where each key is a field name and each value is an array of the values for that field in each record in the data set. So what you need to do is:

  • Iterate through each record in the data set (i.e. each row in your results) .
  • For each field in the record, assign the field value to an array, a reference to which is the value of the key/value pair in the outer associative array.

If it sounds complicated, then I'm glad I'm not the only one. Actually, it's probably easier to understand by looking at the code:

assocArrayOfArrays-example-PrettyPrinting.html - This is a syntax-highlighted representation of the PHP.
assocArrayOfArrays-example.php.txt - This is the actual PHP saved as a .txt file so that you can see and download it.

And here's the PHP in action:
assocArrayOfArrays-example.php

Potentially similar posts

Leave a comment



PHP (or Perl) one line if/then/else statements

August 8th, 2009

If you're toggling something between two states in PHP or Perl it's often handy to use an if/then/else one liner.

In pseudocode this goes like this:

<if this evaluates to TRUE> then <parse this> else <parse this>

All you need to do is replace the "then" with a question mark and the "else" with a colon:

<if this evaluates to TRUE> ? <parse this> : <parse this>

For example:

print  $trueOrFalse ? "you're telling the truth" : "you're lying";

Ignore the print command, it's not part of the if/then/else statement, it's just here to do something with the outcome of that statement.

The expression immediately to the left of the question mark is evaluated. The expression between the question mark and the colon is parsed if the expression evaluates to TRUE, otherwise the expression immediately to the right of the colon is parsed. So in the above example, either "you're telling the truth" or "you're lying" is printed, depending on whether $trueOrFalse is ... you guessed it ... TRUE or FALSE.

But perhaps a more common situation is toggling the value assigned to a variable. For example, toggling between TRUE and FALSE:

$trueOrFalse = $trueOrFalse ? FALSE : TRUE;

Here's a practical example of the use of if/then/else one liners. There's two in this chunk of PHP. The scroll box list below the code is the kind of thing this PHP produces.

<div style="overflow:auto; height:100px; width:300px; border:3px groove #DDD; padding:0">
<?php
    $alternateLine = FALSE;
    while($presidentsArray) {
        print "<div style=\"background-color:";
        print $alternateLine ? "#F5F8F9" : "white";
        print "; padding-bottom: 1px\"> &nbsp; &nbsp; <a href=\"someURL\" title=\"This link goes nowhere\">" .
          $presidentsArray['name'] . "</a></div>";
        $alternateLine = $alternateLine ? FALSE : TRUE;
    }
?>
</div>

Leave a comment



^ back to top ^

Page 1 of 11