Programming:Terrible code

From Robupixipedia
Jump to navigationJump to search

3 June 2008

Bad news: broken chdir

Warning chdir- no such file etc on line 283.png

Worse news: continuing after broken chdir

File list after not checking broken chdir on line 283.png

I saw the above, so I was like, WTF? and went to find the code below, which runs on our live server. The same code runs on our test server which uses different data. And runs on our other test server which uses a different directory structure.

<source lang="php"> <?php

// snip

$cwd = getcwd(); chdir('/var/apache/ssl/htdocs/admin/csv/user/'); $fileList = array(); $dateList = array();

if ($dir = opendir(".")) {

      $i = 0;
      while (false !== ($file = readdir($dir))) {
              if ($file != "." && $file != "..") {
                      $fileList[$i] = $file;
                      $dateList[$i] = date("Y/m/d H:i:s", fileatime($file));
                      $i++;
              }
      }
      closedir($dir);

} chdir($cwd);

// snip

?> </source>

There are some redeeming qualities to this code:

  1. it's indented per block level
  2. it doesn't allow . nor .. to be processed
  3. it closes its file handle $dir
  4. it saves and restores its working directory after it's done.

There are also, however, a couple of points that are not as redeeming.

  1. hard coding '/var/apache/ssl/htdocs/admin/csv/user/'
  2. not checking to see if the hard code worked

In preparing to fix them, I found this, or should I say these:

Omg a whole slew of hardcoded paths.png