Hello! This is the official page of Wayne Sebastian Pereanu.

Software > Cheat Sheets > PHP


File operations
$fh=fopen("test.txt", "w") or die("Can't open file");
fwrite($fh, $string);
fclose($fh);

$fh=fopen("test.txt", "r") or die("Can't open file");
while($line = fgets($fh)) {
    echo $line;
}
fclose($fh);

//Check if a file exists
if ( file_exists("test.txt") ) {
        echo "file exists";
}

//Delete a file
unlink("test.txt");

Getting filenames in a directory
$dir = opendir($path);
$files = array();
while (($file = readdir($dir)) !== false) {
        if (strpos($file, ".jpg")) {
                $files[] = trim($file, ".jpg");
        } 
}
closedir($dir);
sort($files);

Format a date
echo date("F j, Y",strtotime("20111225"));
Outputs December 25, 2011

echo date("F j, Y",time());
Outputs: March 14, 2012
A basic FOR loop
for ($i=0; $i<=10; $i++) {
}

Get the HTTP host
echo $_SERVER['HTTP_HOST'];   // www.pereanu.com
echo basename( $_SERVER["PHP_SELF"] ); //gets the page name

Split a string into an array
$str = "A,B,C,D,E";
$arr = explode(",", $str);
echo $arr[2];   // outputs "C"

Get the IP address of the remote user
$ipaddress = $_SERVER["REMOTE_ADDR"];