Practically all web-applications use UUIDs for one purpose or another. This generates a 40 character UUID that you can substring to get whatever length you want.
function GenUUID() {
$uuid = uniqid(md5(rand()), false);
}
When you retrieve data from the database and spit it out to the screen through HTML, how often can you trust the data to not contain XSS (Cross-Site Scripting)? This blocks all simple XSS attacks that were submitted in input fields. Before displaying data, simply run it through this function.
function EscapeDisplay($str) {
return @htmlspecialchars($str);
}
When you’re writing XML blocks, some data needs to be encased with CDATA, but how do you know what to encase? This does it for you. It returns validly encoded XML content.
function XMLEncode($val) {
if (@htmlspecialchars($val,ENT_NOQUOTES) != $val) {
return @utf8_encode("<![CDATA[$val]]>");
} else {
return @utf8_encode($val);
}
}
Very often, you want to fire off a request to an arbitrary webpage, and not worry about the response. This shoots of the request, and within 1 second times out. Returns nothing.
function SubmitRequest($request) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Enable / Disable a timeout for connection
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_exec($ch);
curl_close($ch);
}
You retrieve 2 dates from MySQL, how do you know which date is more recent? The syntax and response is similar to Java’s compareTo(a,b) method. Returns -1 for a < b, 0 for a = b, 1 for a > b.
function CompareMySQLDates($a, $b) {
$strA = split("[- ]", $a);
$strB = split("[- ]", $b);
# Make the dates into timestamps of US formatted dates
$timeA = strtotime($strA[1] . "/" . $strA[2] . "/" . $strA[0]);
$timeB = strtotime($strB[1] . "/" . $strB[2] . "/" . $strB[0]);
# Compare timestamp integers
return $timeA < $timeB ? -1 : ($timeA == $timeB ? 0 : 1);
}
Regex expression to make sure an email address has the right syntax: word@word.ext
function ValidateEmail($email) {
return eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email) ? true : false;
}
Removes whitespace from a block of text
function CleanWhitespace($str) {
return ereg_replace("[ \t]","",$str);
}
General function for securing data sent in a SQL Statement.
Usage: $sql = “SELECT * FROM table1 WHERE name = ‘” . SQLEscape($name) . “‘”;
function SQLEscape($data) {
return mysql_real_escape_string($data);
}
Used for calling a Stored Procedure through a MySQLi connection ($database is a valid connection).
function CallSQLProcedure($sql) {
global $database;
# Create a temp array so we can free the result
$arr = array();
# Call the proc
if ($database->multi_query($sql)) {
$result = $database->store_result();
while ($row = $result->fetch_assoc()) {
$arr[] = $row;
}
while ($database->next_result()) {}
# You have to free the resultset
if ($result)
$result->close();
}
return $arr;
}
When you have a SQL statement that simply returns a single value, like the count of rows in a table, use this. ($database is a valid PearDB Connection)
function ScalarSQL($sql) {
global $database;
$result = $database->query($sql);
if ($result instanceof DB_Error) {
return false;
}
if ($row = $result->fetchRow()) {
return $row[0];
} else {
return false;
}
}
Everyone hates dealing with messy Apache error logs. Use this function to write to your own logs. It uses the current date to create a directory structure, and a new log file everyday. Make sure the directory pointed to by $ERROR_LOG_DIR has rights for the current user to create files and folders.
function LogError($str) {
global $ERROR_LOG_DIR;
$str = date("H:i:s") . " - " . $_SERVER["REQUEST_URI"] . " - $str\n";
$filename = date("Y-m-d") . ".log";
$logdir = "$ERROR_LOG_DIR/" . date("Y-m");
if (!@file_exists($logdir)) {
@mkdir($logdir);
}
@error_log($str,3,"$logdir/$filename");
}
The built-in PHP function does not return valid filesizes for large files, this does (only works on Linux).
function LinuxFilesize($filename) {
@exec("filesize $filename",$printout,$return);
return $return != '0' ? 0 : $printout[0];
}
Upload a file asyncronously to an FTP site. $locaFile and $remoteFile can be paths to files, or just filenames.
function FTPFileUploadAsync($localFile, $remoteFile, $ftpServer, $username, $password){
# Set up basic connection
$connID = ftp_connect($ftpServer);
if ($conn_id) {
# Login with username and password
$loginResult = ftp_login($connID, $username, $password);
if ($loginResult) {
# Upload the file
ftp_nb_put($connID, $remoteFile, $localFile, FTP_BINARY);
return true;
}
}
return false;
}
Makes a directory at the specified $path on an FTP server. It makes all directories in the $path to get to the last node in the $path. $conn has to be an active / open FTP connection.
function FTPMkDir($conn, $path) {
$dir = split("/", $path);
$path = "";
$ret = true;
for ($i=1;$i<count($dir);$i++) {
$path .= "/" . $dir[$i];
if(!@ftp_chdir($conn,$path)) {
@ftp_chdir($conn,"/");
if(!@ftp_mkdir($conn,$path)) {
$ret=false;
break;
}
}
}
return $ret;
}