Archive

Archive for the ‘php’ Category

php: Checking if a directory is empty

February 21st, 2008 ^Lestat No comments

I found myself working with text files a little more recently and was looking for a way to tell if a directory was empty. Why? In my case I wanted to check if a directory was empty. If it wasn’t, to grab the data in those files and put them in a database.

What I didn’t want to do was have the expense of connecting to a database if the directory didn’t have any files in it to begin with. After chatting with my good friend TDavid at php-scripts.com, I decide to run with his suggestion…

Fill (or don’t fill) a variable with information if there were files in the directory. Then test the var to confirm or deny if there are files in the directory. It’s really a small bit of code…

//----- Check if ticket dir has files. If it has files,
// set a variable to hold the list of file names.

$dir = "../path/to/my/textfiles";      // set directory

if($handle = opendir($dir)){           // open directory

	while(($file = readdir($handle)) !== false){
		if($file != "." && $file != ".."){
			$file_list[] = $file;  // Set file list variable
		}

	}

	closedir($handle);      // Close directory
}

If there are files in this directory, the variable $file_list would not only exist, but also contain files. For example…

Array
(
    [0] => 195972.txt
    [1] => 196027.txt
    [2] => 196053.txt
    [3] => 196067.txt...
)

If there aren’t any files in this directory, the variable $file_list would not even exist because no $file would be inserted into it. At this point we can check/ test the variable to output or do further processing…

if(isset($file_list)){
    echo "This dir has files!";
    // perform further processing
    // eg: collect each files contents
} else {
    echo "This dir has NO files!";
    // stop processing
    // Not much do do with this since there are no files
}

Of course there are a few ways of checking to see if a directory is empty, but this way seemed to be the most simplistic to me. If you wanted to you could turn the entire lot into a function for reuse, and less script code clutter.

Comments? Questions?

php, empty directory

Categories: Computing, Programming, php Tags:

MySQL Conditional Insert

December 20th, 2007 ^Lestat No comments

I came across a situation where I needed to pull records from 1 db to another on a recurring basis. I read many different ways to do it via searching around the net. Some of the suggestions included creating a temporary table and copying it over. What was lacking was that sometimes the new table also needed to be UPDATED, as the information changed from the original table.

I’ve come up with a dirty little example to show this can be done. There are more keywords that can enhance the ON DUPLICATE KEY UPDATE function even more. The Example is assuming an “employees” table that looks like so:

employees
id (PK)
first_name

For brevity, I’ve left out connection data etc;

$myArray = array(0 => array('id' => '1', 'fname' => 'Steve'),
                      array('id' => '2', 'fname' => 'sara'),
                      array('id' => '3', 'fname' => 'Matt')
                 );

// Don't forget to validate & clean your data
// Connect to db here 

foreach($myArray as $key => $value){
          $query = "INSERT INTO employees
          (id, first_name) VALUES ('$value[id]', '$value[fname]')
          ON DUPLICATE KEY UPDATE first_name = '$value[fname]'";

          $result = mysql_query($query);

          if(!$result){

                    print("Problem: " . mysql_error() . "");
          } else {

                    print("Success !");
          }

}

Read the manual on this for more information. This snippet will INSERT if a UNIQUE (in this case ‘id’) does not exist. It will UPDATE any existing unique. In this case any existing ‘id’s, the ‘first_name’ column will get updated.

One could also use the REPLACE function. As I understand the difference, REPLACE will DELETE any matching uniques, and INSERT a new record in it’s place.

Comments? Better ways? I’m always up for learning something new so please chime in ;-)

Categories: MySQL, Programming, php, php Snippets Tags:

php: Installing imagick extension on WindowsXP

October 12th, 2007 ^Lestat No comments

This may seem simple enough to many programmers out there but this threw me for a few days. This is how you install imagick on a windows server. If your site is on a shared host, you need to ask your host to install the extension for you.

For this example I am running php 5.2.4 on Abyss/Apache web server

Download the matching pecl5 Binary from php.net. In this case its pecl5.2-win32-200710121230.zip (matching my current php version).

Unpack the file.

Copy the php_imagick.dll into php/ext/ directory

php pecl dll

Open your php.ini file and look for the “Dynamic Extensions” area. In there will be a list of items (some commented out). Add the following line to the bottom of the list: extension=php_imagick.dll

Add the extension to your ini

Save the changes you made.

Restart your web server.

If these steps were successful imagick will show up on any php page using the phpinfo() function.

imagick in the phpinfo()

imagick, pecl-extension, php-extension

Categories: Computing, Internet, Programming, php Tags:

php: Whats your commenting style?

August 14th, 2007 ^Lestat 1 comment

I was writing up a few scripts and as I was adding my commenting I noticed I tend to comment differently depending on the difficulty of the script and how many different parts or procedures there are to it. I don’t have a set convention, but I suppose as with all things it would make things easier on myself and others if I had some kind of standardization…

For larger ‘areas’ that contain functions or a series of procedures that extract or parse sections of data I’m now starting with this:

/***
*
* This is a comment.
* Here I leave notes about the section and what it does.
* I may also include notes to myself here.
* Note: This could probably be done more eficiently
*
*/

As there are more breakdowns within these sections I’m using this:

/*  [ Parse out the text file ]  */

And further drilled down I use the more inline commenting

/*  [ Print data]  */

$parts = explode("|", $the_array); // get the parts

$color = false; // set color var for shading every other row

print("<table>"); 

// loop through data & print
foreach($parts as $key => $row){ 

    // CSS Note: shading <tr>'s with css mostly works with nice browsers
    // For IE 6+ one needs to shade the <td>'s

    if($color){
        print("<tr class=\"rowColor1\"> "); // start row with color 1
        $color = !$color; // unset the color so it alternates next loop
    } else {
        print("</tr><tr class=\"rowColor2\"> "); // start row with color 2
        $color = true; // set the color so it alternates next loop
    }

    print("<td>$row[first_name]</td></tr>"); // print cell data and close the row
}

print("</td></tr></table>");

The inline comments still seem a bit ‘messy’ to me. But for now it will work.

One of the reasons I decided to standardize is because even with commenting and extra line spaces in the scripts it was still difficult to sort out what exactly was going on. Another thing that tripped my thought was having a glance at phpDocumentor. It seems to function on how you comment your code. I did try to install it but for some reason it was way over my head. It looks like a neat tool but I rarely seem to write more than 4 different files and those are often less than 300-400 lines.

I’ve yet to test it in comments but my plugin to allow code viewing is much like bbc code. [code lang="php"] // comment [/code]

So whats your style? Is there a standard? What have you seen that looks the cleanest? Leave a comment… with some comments ;-)

Update 12/3/07 Elizabeth Naramore has written a nice article on the effectiveness of comments in your code over at the Chris Shiflett blog. It’s a great read on WHY commenting is good in your code.

php, comment, code, script, php+script, php+comment

Categories: Programming, php Tags:

My Favorite Dev Tools

March 8th, 2007 ^Lestat 3 comments

I’ve recently reformatted my computer and started missing my favorite dev tools. In an attempt to record them, I can also share them with others.

A list of my current favorite web tools…

Text Editor:

Compression Utility:

  • IZARC – IMO, better than winzip

Localhost Server (Apache/mySQL):

  • Wamp – Run an Apache web server on your PC. You can configure it to run or not run on startup. It also includes mySQl and a few php extensions.

Firefox extensions:

  • measureit – Measure pixels right on your screen.
  • colorzilla – Grab colors off of web pages, zoom, and built in color picker.
  • web developer – CSS, XHTML, Screen resize, line guides, disable styles and much much more.
  • firebug – A great tool especially for pages created in php. You may have 100 lines of code before the html begins. This helps you debug xhtml issues on “line 12″ which is actually line 112. Works well with included php files as well.

IE Explorer Add On:

  • IE Dev Toolbar(For IE Similar to Firebug)
  • Tools, Dev, Developer, Dev Tools

Categories: Computing, Internet, Programming, css, php Tags: