Miscellaneous How-To
System Independent EOL, Directory Separator, etc
You can get the system independent EOL, directory separator via these constants:
- Newline (or End-of-Line):
PHP_EOL
- Directory Separator:
DIRECTORY_SEPARATOR
For example,
<?php
var_dump(DIRECTORY_SEPARATOR);
var_dump(bin2hex(PHP_EOL)); // print string in hex
?>
How to Get the Filename from Full Path?
Use the built-in function basename()
. For example,
<?php $path = "/var/www/html/index.php"; $filenameExt = basename($path); // "index.php" var_dump($filenameExt); $filename = basename($path, ".php"); // "index" var_dump($filename); ?>
The Current Page Filename
The current full-path filename is kept in system variable $_SERVER['PHP_SELF']
. You can use function basename()
to get the filename without the path; or basename(path, suffix)
to get the filename without the extension. For example,
<?php var_dump($_SERVER['PHP_SELF']); // e.g., 'test/test.php' var_dump(basename($_SERVER['PHP_SELF'])); // e.g., 'test.php' var_dump(basename($_SERVER['PHP_SELF'], '.php')); // e.g., 'test' ?>
Redirect to Another Page
Use the header()
function, followed by an exit
command (not too continue the current script). For example,
<?php
header('Location: http://www.example.com/');
exit;
// Remember to place an exit, so that the rest of the script will not be executed.
?>
To reload (refresh) the current page, you may:
<?php
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
// Remember to place an exit, so that the rest of the script will not be executed.
?>
Printing Array
Use built-in function implode()
to join the elements of the array into a string, e.g.,
$a = array(11, 22, 33);
echo implode(',', $a); '11,22,33'
On the other hand, the explode()
splits a string into an array.
$str1 = 'apple,orange,banana'; var_dump(explode(',', $str1)); $str2 = 'apple orange banana'; var_dump(explode(' ', $str2));
Negative Array Index vs. Negative String Positional Index
You can use negative array key in an associative array. For example,
$a = array(-1 => 5); echo $a[-1]; var_dump($a);
Negative array key is difference from negative positional index for string, which indexes position from the rear of the string. For example,
$rest = substr("abcdef", -1); // returns "f" $rest = substr("abcdef", -2); // returns "ef" $rest = substr("abcdef", -3, 1); // returns "d"
Send mail from PHP
[TODO]
REFERENCES & RESOURCES
- PHP mother site @ http://www.php.net; "PHP Manual" @ http://php.net/manual/en/index.php; "PHP Language Reference" @ http://www.php.net/manual/en/langref.php.
- PHP MySQL extension @