file_get_contents

PHP:CSI - Improving Bad PHP Logging Code

I read The Daily WTF every now and then and one story about bad logging code in PHP stood out to me. The post looked at some PHP code that was created to log a string to a file, but would have progressively slowed down the application every time a log was generated.

PHP is a great language as it allows you to put together code without easily shooting yourself in the foot. One downside of this ease of access is that it can allow beginners to put together code that works, but will ultimately cause problems in the long run. The PHP code given in the post is certainly an example of this.

I know that the goal of The Daily WTF isn't to fix problems found in code and is more of a satirical look at bad coding examples. I thought, however, that it would be good to look at the code and fix the issues it had.

Using Authentication And file_get_contents()

Using file_get_contents() to fetch the contents of a file is quite a common practice. This might be just to get the contents of a text file or to get the ImageCache module in Drupal to pre-cache images. The file_get_contents() function can get a local or remote file and is usually run like this.

$data = file_get_contents($url);

However, when trying to use this function to communicate with an authenticated server you will see the following error appearing.

PHP Function To Get TinyURL

TinyURL is a service where you can convert a long URL string to a really small one. For instance, the following URL, which points to the Googleplex on Google Maps.

http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=googleplex&sll=37.579413,-95.712891&sspn=34.512672,45.615234&ie=UTF8&cd=1&z=16

Can be converted to the following.

http://tinyurl.com/qpkor2

This is perfect for posting to Twitter or similar microblogging platforms as it saves lots of character space.