yes i love technology

PHP monitor server log

June 28th, 2007 by Pete

PHP monitor server log

Occasionally you'll be working on a webserver and not have SSH access to it. Below is a simple script I've written that reads a server log (in this case the error log) and outputs a portion of it to a webpage.

PHP:
  1. $no_lines = 25;
  2.  
  3. $filename = $_SERVER['DOCUMENT_ROOT']."/../logs/error.log";
  4. $handle = fopen($filename, "r");
  5. $contents = fread($handle, filesize($filename));
  6. fclose($handle);
  7.  
  8. $contents = trim($contents, "\n");
  9. $contentsArr = explode("\n", $contents);
  10. $size = sizeof($contentsArr);
  11. $n = $size - $no_lines;
  12.  
  13. <h1>monitor log</h1>
  14. ";
  15. <ol start=\"$n\">";
  16.  
  17. for ($n; $n<$size; $n++)
  18. {
  19.     <li>".$contentsArr[$n]."</li>
  20. ";
  21. }
  22.  
  23. echo "</ol>
  24. ";

Obviously in a production environment you'd want to add some sort of password protection to such a script.

/* Pete Graham */

Posted in Uncategorized, Website Development, php | 2 Comments »

PHP: File Downloads HTTP Headers

May 16th, 2007 by Pete

In PHP you can provide file downloads by using a PHP page to “pass through” the file. Of course you could just link to the actual file, however this technique means your file can kept outside of your website root. Another advantage is you can integrate this system into a PHP based user/password system easily.

Now this technique is fairly straightforward, but you need to make sure you get the HTTP Headers correct for it to run smoothly. Here’s the code:

PHP:
  1. $file = "/path/to/file.txt";
  2. $file_extension = strtolower(substr(strrchr($basename,"."),1));
  3.  
  4. //This will set the Content-Type to the appropriate setting for the file
  5. switch ($file_extension)
  6. {
  7. case "htm":
  8. case "xhtml";
  9. case "txt";
  10. case "html": $ctype="text/html"; break;
  11. case "pdf": $ctype="application/pdf"; break;
  12. case "doc": $ctype="application/msword"; break;
  13. case "exe": $ctype="application/octet-stream"; break;
  14. case "zip": $ctype="application/zip"; break;
  15. case "xls": $ctype="application/vnd.ms-excel"; break;
  16. case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  17. case "gif": $ctype="image/gif"; break;
  18. case "png": $ctype="image/png"; break;
  19. case "jpeg":
  20. case "jpg": $ctype="image/jpeg"; break;
  21. case "mp3": $ctype="audio/mpeg"; break;
  22. case "wav": $ctype="audio/x-wav"; break;
  23. case "mpeg":
  24. case "mpg":
  25. case "mpe": $ctype="video/mpeg"; break;
  26. case "mov": $ctype="video/quicktime"; break;
  27. case "avi": $ctype="video/x-msvideo"; break;
  28. default: $ctype="application/force-download";
  29. }
  30.  
  31. //Begin writing headers
  32. header("Pragma: public");
  33. header("Expires: 0");
  34. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  35. header("Cache-Control: public");
  36. header("Content-Description: File Transfer");
  37. //Use the switch-generated Content-Type
  38. header("Content-Type: $ctype");
  39. header("Content-Length: ".filesize($file));
  40.  
  41. // regex stops download prompt for browser associated types
  42. if (!preg_match('/(htm|xhtml|txt|html|gif|png|jpeg|jpg)/', $file_extension, $matches))
  43. header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
  44.  
  45. // output the file
  46. readfile("$file");
  47. exit();

I will be writing a follow up article in the future that shows how this technique can be improvement using Apache's mod-rewrite to provide cleaner URLs for file downloads.

Note: The regular expression on line 42 will make files normally associated with the browser (images, webpages, etc) open inside the browser. If you want to get the “open/save” download prompt for all types of files then comment out this line.

Note: Make sure you use: “Content-Type: image/jpeg” for JPGs, IE doesn’t seems to like “Content-Type: image/jpg”

# Pete Graham

Posted in Website Development, php, regular expressions, programming | 2 Comments »

PHP: Get First Index in Associative Array

May 15th, 2007 by Pete

The other day I was programming in PHP and needed to get the first index in an associative array. There doesn’t appear to be a built in function to deal with this so I wrote my own.

PHP:
  1. function getArrayFirstIndex($arr)
  2. {
  3. foreach ($arr as $key => $value)
  4. return $key;
  5. }

Here's a bit of code you can test it on:

PHP:
  1. $arr['banana'] = "yellow";
  2. $arr['apple'] = "apple";
  3. $arr['orange'] = "orange";
  4.  
  5. $first_index = getArrayFirstIndex($arr);
  6.  
  7. echo "first index =".$first_index;

The above code will output 'first index = banana'.

/* Pete Graham */

Posted in Website Development, php, programming | 4 Comments »

PHP: Swap Variables One Liner

March 29th, 2007 by Pete

Here's a nifty one liner in PHP which let's you swap 2 variables values.

PHP:
  1. list($a,$b) = array($b,$a);

Much like the PHP XOR swap there's no real reason this is any better than using a temporary variable, but you might be able to impress chicks with it or something.

/* Pete Graham */

Posted in Tech, php, programming | 3 Comments »

Drupal: Hide Navigation on Forum

March 29th, 2007 by Pete

If you want to hide certain Navigational Blocks on your Drupal sites forum(s) here’s how to do it:

1. Go to "Administer » Blocks"
2. Click "configure" on the block you want to hide.
3. On Page specific Visibility Settings click the option for "Show if the following PHP code returns TRUE"
4. Enter the following code in the text area:

PHP:
  1. if (arg(0) == 'node')
  2. {
  3. $node = node_load(array('nid' => arg(1)));
  4. return $node->type != 'forum';
  5. }
  6. elseif (arg(0) == 'forum')
  7. {
  8. return false;
  9. }
  10. else
  11. {
  12. return true;
  13. }
  14. ?>

This will hide the navigation on the forum hompage, when viewing lists of topics and when viewing individual posts (nodes).

# Pete Graham

Posted in Tech, Website Development, php, drupal | 11 Comments »

PHP: XOR swap

March 26th, 2007 by Pete

The XOR swap lets you swap the value of integer variables without using a temporary variable, it's also slightly faster.

PHP:
  1. $x ^= $y;
  2. $y ^= $x;
  3. $x ^= $y;

I can't actually think of a good reason Why you'd want to use this in PHP since memory isn't normally a big issue, however it might be good for showing off ;-) .

// Pete Graham xXx

Posted in Uncategorized, Website Development, php, computer science | 2 Comments »

PHP: Remove Values from Array

March 22nd, 2007 by Pete

If you need to remove elements from an array that have a particular value(s) here’s a neat way of doing it without any looping:

PHP:
  1. // our initial array
  2. $arr = Array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
  3. print_r($arr);
  4.  
  5. // remove the elements who's values are yellow or red
  6. $arr = array_diff($arr, array("yellow", "red"));
  7. print_r($arr);
  8.  
  9. // optionally you could reindex the array
  10. $arr = array_values($arr);
  11. print_r($arr);

This is the output from the code above:
Array ( [0] => blue [1] => green [2] => red [3] => yellow [4] => green [5] => orange [6] => yellow [7] => indigo [8] => red )
Array ( [0] => blue [1] => green [4] => green [5] => orange [7] => indigo )
Array ( [0] => blue [1] => green [2] => green [3] => orange [4] => indigo )

Pete Graham xXx

Posted in Tech, php, arrays, programming | 11 Comments »

Email Interaction with Web Applications (using PHP, Postfix and Regular Expressions)

February 9th, 2007 by Pete

One of the popular facilities on phuser.com is the ability to create polls. Once a poll has been created it can be sent to people by SMS or Email. The recipients can reply with their choice of answer and a optional comment using SMS, Email or phuser web interface, lovely!

Handling of emails replies has easy been the trickiest part of this process. Here is a very basic overview of the steps we have taken:

  1. Have postfix forward the email to a PHP command line script that saves the email to file. Details of how to do this can be found here.
  2. Cron runs a PHP script that processes the email files. It makes sure the emails are valid, strips the users reply from the body of the email, and then adds the email to a database table.
  3. Crons runs another script which queries the database table and processes the emails replies, this is where the actually interaction with the phuser system (the magic) happens!

Today I shall be describing the regular expression that we used for Step 3 as it took a bit of effort to get right. Step 2 will be covered at a later date.Warning: when I cover Step 2 I will be having a rant about my new found hatred of HTML emails!

Note: Steps 1 and 2 are separate because security precautions on our servers prevent the Postfix user from interacting with the Databases.

When someone gets a poll email from phuser the content looks like this:

pete (pete graham) wants your opinion:

Which is your favourite drink?

Vote for one of the options below:

1) Tea
2) Coffee
3) I love them both like they were my children
4) Urgh! I can’t stand either!

--------------------- YOUR REPLY BELOW THIS LINE ---------------------

--------------------- YOUR REPLY ABOVE THIS LINE ---------------------

Reply using one of the following methods:

o Reply to this email. Include the number of your vote at the start of your message. Any extra text will be added as a comment. (Please do not edit the Subject line).

Now due to the difference in the way email clients work and the ways people think here is a small selection of the possible replies we needed to be able to handle:

  • > 1 I like to drink tea since I am a English Gentleman!
  • 4 I’ll have whats going
  • 3 – I hate them all
  • > 2)
  • 1) tea because I love tea!!!
  • 1 I'm not a big drinker of either since I'm the no-caffs, but like a cup of decaff tea
  • > 1
  • 2

So what we required is a Regular Expression which would correctly grab the number if one was included at the beginning so we could log the voting option. We also needed to grab the text afterwards if any was included so it could be used as a comment. Here’s what we eventually came up with:

CODE:

  1. /^[^\w]*([0-9]+)[^\w]*(\w.*)/ms

And it works, yay! The 'm' flag is set so the Regex is multiline , the 's' flag makes the dot character match every character including newlines. Here is the page that describes all the PHP regular expression modifiers.

If you want to learn more about regular expressions (and who doesn’t) then loads of information can be found on this site. Another great site is the one that we used to testing our regular expressions, it lets you supply up to 10 different test strings at once.

If you’d like to see this system in action then go to phuser.com and request an invite we are still looking for Beta testers currently, if you sign-up now you can have a real input into the site as it develops and grows.

Ps. The regular expression is in an if statement. If it fails the entire message is put in the comments section on the poll.

# Pete Graham

Posted in Uncategorized, phuser, postfix, php, regex, regular expressions | 7 Comments »