Archive for the ‘PHP’ Category

PHP – Calculating execution time

Monday, January 25th, 2010

Here is an easy way of calculating the time elapsed during some script execution in PHP, using microtime() :

1
2
3
4
5
$exec_start = microtime(true); // 'true' returns the seconds of type double

// ... do stuff

echo (microtime(true) - $exec_start) . ' seconds';

Email validation RegEx

Thursday, October 8th, 2009
1
/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g

Found at http://gskinner.com/RegExr/

PHP – Loop through files in folder

Wednesday, April 22nd, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$files = array();
$path = getcwd();
$supported_ext = array('gif', 'jpg', 'jpeg');
$dir = @opendir($path);

while ($file = @readdir($dir)){
      if (!is_dir($path.$file)){
            $splitted = explode('.', $file);
            $ext = strtolower($splitted[count($splitted)-1]);
            if (in_array($ext, $supported_ext)) $files[] = $file;
      }
}

@closedir($dir);
sort($files);

for ($i=0; $i<count($files); $i++){
      $output .= '<img alt="'.$files[$i].'" src="'.$files[$i].'" height="16" width="16" />';
}

echo $output;

PHP – Write to File

Wednesday, April 22nd, 2009
1
2
3
4
5
function writeFile($data, $path, $targetname){
    $fp = fopen($path.'/'.$targetname, "w", 0);
    fputs($fp, $data);
    fclose($fp);
}