I thought this would be a good idea. Let's share our PHP functions! Handy bits of code that can improve our work.
Here's some basic ones.
A function for determining the "end of line". Just echo $eol wherever you want a line break in your HTML source.
PHP Code:
if(strtoupper(substr(PHP_OS,0,3)=='WIN')) {
$eol="\r\n";
} elseif(strtoupper(substr(PHP_OS,0,3)=='MAC')) {
$eol="\r";
} else {
$eol="\n";
}
Or a function for cleaning post input - stripping tabs, carriage returns, and new lines and such. It also adds escaping slashes if get_magic_quotes_gpc is false.
PHP Code:
function clean_input($variable) {
if (!get_magic_quotes_gpc()) {
$cleaned = addslashes(trim($variable));
} else {
$cleaned = trim($variable);
}
return $cleaned;
}
And the MySQLi database connection function I usually use is...
PHP Code:
function db_connect($config) {
$db_conn = new mysqli($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
if (mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
} else {
return $db_conn;
}
}
Most of these functions are modified from various sources around the web.