Archive for October, 2008
PHP File Listing Script
by Billy on Oct.28, 2008, under PHP, Web Design
I had a need for a script to read directories for users, listing only files and not sub-directories, so this is the script that ended up being what worked. One of the features was to exclude a few system files on the Linux file system that are present in directories and to list the last modified time so that the users uploading and downloading files could see the different timestamps to differentiate more recent files.
This script handled the uploading of files, after a user was logged into the system. Proper validation and security measures need to be taken before using a script such as this. This may include user logins, ip-restrictions or other measures.
The code explanation follows the code below:
<?php
//define the path
//using the "." sets it to the current path
//any relative or absolute path that the web
//server use can read with will work
$path = ".";
//using the opendir function
$dir_handle = @opendir($path) or die("Unable to open files.");
echo "<h3>List of items.</h3><p>";
//running the while loop
echo "<ul>";
while ($file = readdir($dir_handle))
{
//remove . and .. from the list
if($file!="." && $file!=".." && $file!=".htaccess")
{
$modified = date("F d Y H:i:s", filectime($path."/".$file));
echo "<li><a href='$path/$file'>$file</a> Last Modified: $modified</li>";
}
}
echo "</ul>";
//closing the directory
closedir($dir_handle);
echo "</p>"
?>
</div>
The script first sets up the directory path that we want to open, in this case I wanted to open the current path, so I used a period to signify the current working directory. Next, we open the directory using the opendir command passing in the $path variable. We have to loop through the entire directory to get all the files. **Note this script does not take in to account sub-directories.**
At this point, the script tests for the directories . and .. and also to not list the .htaccess file if it is present. Within the file check, we get the last modified date of the file, this is done by doing a date format on the filectime function, which accepts the path/filename combination. The script then simply adds each file to an unordered list, and makes each file name (represented by the $file variable) a link so that they can be clicked on to be viewed or downloaded.
The last important line of code closes the directory handle resource by calling the closedir function.
While simple, this script accomplished reading a directory of files and making a linked list of them. As I mentioned I had this was only presented to users who had successfully logged into the system, presenting them with a list of files they could easily download. It was created as a direct replace for an FTP system that was not working well for users - the entire package was a login control, the file listing control (presented here), a way for the user to upload files back and the automatic deletion of files that were older than a set time frame.
I will post about the other parts of the system in the future, and in the end, wrap it up with a complete user managed file transfer system.
PHP & ImageMagick Image Resize Script
by Billy on Oct.23, 2008, under Graphic Design, Internet Tools, PHP, Web Design
This simple script takes a source image, and up to two parameters to re-size the image using ImageMagick. This allows you to use a large source image that is suitable for a zoomed in view, and dynamically re-size it using the simple script which will make it fit the x,y constraints necessary for a site, and reduce the file size.
In testing the script, a sample PNG image with transparency was originally 500×500 pixels and 202.76kb in size. Using the script to set the x,y to 200×200 the file size was reduced to 44.73kb. The script could be easily extended to perform other ImageMagick functions, and to reduce the end result file size even more.
<?php
if(!extension_loaded('imagick'))
{
dl('imagick.so');
}
$img = strip_tags($_GET['imagename']);
if(isset($_GET['size']))
{
$size = strip_tags($_GET['size']);
}
else
{
$size = 0;
}
if(isset($_GET['vsize']))
{
$vsize = strip_tags($_GET['vsize']);
}
else
{
$vsize = 0;
}
$image = new Imagick($img);
$image->thumbnailImage($size, $vsize);
header("Content-type: image/png");
print $image;
?>
Quick synopsis of the code: It first checks to make sure the imagick PHP extension is loaded, and if it is not, it will dynamically load the extension. It then checks for the URL parameter ‘imagename’ and runs a simple strip_tags to clean any extraneous attempts to send in other code with the image name. The script then does two checks for the size (horizontal) and vsize (vertical). If either is set, it will strip_tags on them and assign them to a variable for use.
The script then takes the sizes and instantiates a new Imagick object passing in the image name as set from the URL parameter. It then calls the thumbnailImage function of the Imagick library and passes in the $size and $vsize variables. We then set the header type to be image/png since we worked only with PNG images in this version, and finally print the results, which are contained in the $image object.
The nice thing about the script, is thumbnail image will take two parameters for the size, and if only one is set, it will auto-constrain the image (eg. 200, 0 it will autoscale the 0 axis). The other nice thing is we can check the type of image so that we output the same type so we can work with GIF, JPEG, and PNG among others.
PHP 5, Twitter & XMLReader
by Billy on Oct.22, 2008, under Blogging, Internet Tools, PHP, Web 2.0
I was interested in using and experimenting with the XMLReader class that is part of PHP 5, and thought why not test it out using my Twitter feed. Turns out, the feed contained more information than I really wanted, so I had to find a way to extract only what I needed. To that, I present the following, simple and basic script to extract just the text of the latest update on Twitter.
A basic Twitter feed might appear like mine below:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Twitter / southplatte</title>
<link>http://twitter.com/southplatte</link>
<description>Twitter updates from southplatte / southplatte.</description>
<language>en-us</language>
<ttl>40</ttl>
<item>
<title>southplatte: working on database stuff with MySQL</title>
<description>southplatte: working on database stuff with MySQL</description>
<pubDate>Tue, 21 Oct 2008 05:35:21 +0000</pubDate>
<guid>http://twitter.com/southplatte/statuses/968543230</guid>
<link>http://twitter.com/southplatte/statuses/968543230</link>
</item>
</channel>
</rss>
As you can see we get a channel name with related information, and then the items, or Tweets. In this case, Twitter has used some duplicate XML tags, namely title, description and link in both the channel element and item elements, so our script should pull only the item information, unless we wanted to publish the channel information, which for this we will not.
1. <?php
2. $reader = new XMLReader();
3. $reader->open('http://twitter.com/statuses/user_timeline/twitterusernamehere.rss?count=1/');
4.
5. while ($reader->read())
6. {
7. if ($reader->nodeType == XMLREADER::ELEMENT)
8. {
9. $name = $reader->name;
10.
11. if($name == "item")
12. {
13. while($reader->read())
14. {
15. if($reader->nodeType == XMLREADER::ELEMENT)
16. {
17. $noName = $reader->name;
18. if($noName == "description" || $noName == "pubDate" || $noName == "link")
19. {
20. $reader->read();
21. $result .= $reader->value."<br>";
22. }
23.
24. }
25. }
26.
27. }
28.
29. }
30.
31. }
32.
33.
34. $reader->close();
35.
36. ?>
What the script does:
Line 2 creates a new instance of an XMLReader object
Line 3 opens the RSS feed from Twitter - the username will be your Twitter user name (or what ever Twitter user name you want to get updates for) and the count URL parameter tells it to only retrieve the latest Tweet. You can ommit the count and get all, or specify another number here.
Line 5 starts a while loop that will loop through the entire contents of the XML file returned from our open command.
Line 7 checks for the node type and if it is equal to an ELEMENT, takes action.
Line 9 sets the value of the Element.
Line 11 Validates the element to be equal to item, item being the element that contains our tweet.
Line 13 begins a new while loops (almost a recursive action here) and moves through the file again, to get the actual Tweet text from within the Item element.
Line 15 again checks that we are working with elements
Line 17 assigns each element to the variable
Line 18 checks the variable to be equal to the elements that we want, description, pubDate and link.
Line 20 tells the object to read the XML/RSS stream
Line 21 appends the $result variable with the values from our selected elements.
Line 34 closes our XMLReader stream.
Now all we need to do is include this into a PHP page, echo or print the $result variable and we will get an output like the following:
southplatte: working on database stuff with MySQL
Tue, 21 Oct 2008 05:35:21 +0000
http://twitter.com/southplatte/statuses/968543230
southplatte: Another interview setup for Wednesday, still waiting on the one from last week to decide, it is between myself and one other person!
Sat, 18 Oct 2008 15:28:30 +0000
http://twitter.com/southplatte/statuses/965216528
As you can see, we have some formatting issues to deal with, such as double spacing between Tweets, maybe formatting the date string, and encasulating the entire tweet with the link so it could be clicked and take the visitor to the individual Tweet on the Twitter web site.
The final page I have it in on my testing server is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: .8em;
color: #666666;
background-color: #FFFFFF;
}
-->
</style>
</head>
<?php
$reader = new XMLReader();
$reader->open('http://twitter.com/statuses/user_timeline/southplatte.rss?count=1/');
while ($reader->read())
{
if ($reader->nodeType == XMLREADER::ELEMENT)
{
$name = $reader->name;
if($name == "item")
{
while($reader->read())
{
if($reader->nodeType == XMLREADER::ELEMENT)
{
$noName = $reader->name;
if($noName == "description" || $noName == "pubDate" || $noName == "link")
{
$reader->read();
$result .= $reader->value."<br>";
//break;
}
}
}
}
}
}
$reader->close();
?>
<body>
<span class="style1"><?php echo $result;?></span>
</body>
</html>
This could definitely not be used for much, but you could also set up a very similar and though not quite as simplistic page to read any RSS feed, thus creating your own PHP RSS/XML reader. It could definitely be extended and enhanced to perform some very advanced functionality as well.
Available for Freelance and other work
by Billy on Oct.06, 2008, under E-Commerce, Graphic Design, Internet Tools, Off-Topic, PHP, Search Engines, Servers, Uncategorized, Web 2.0, Web Design
I am currently accepting new projects, either on a freelance basis or on an employment basis. The employment basis may be either a temporary, temp-to-hire, contract-to-hire or direct hire situation. At this time I am not available for relocation, so local opportunities (those that are not available via telecommuting/offsite work) must be within the Front Range to Southern Colorado area.
Use my contact page if you are interesting in discussing any potential opportunities.