PHP Functions Library

1. Get user ip address:

 

[codesyntax lang=”php” lines=”no”]

/**
 * get current visitor's ip address
 *
 * @return string - ip string
 */
function getUserIp()
{
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

[/codesyntax]

 


 

2. Function to create recursive dirs

 

[codesyntax lang=”php” lines=”no”]
/**
* create recursive dirs by given path
*
* @param string $path – /home/kim/path1/path2/path3
* @return void|true
*/
function createDirs($path)
{
if (!is_dir($path)) {
if (createDirs(dirname($path))) {
mkdir($path, 0777);
return true;
}
} else {
return true;
}
}
[/codesyntax]

 


 

3. Function that save remote files(photos) to local

 

[codesyntax lang=”php” lines=”no”]
/**
* save photo from remote to local
*
* @param string $img – the remote url, for example http://aff.bstatic.com/images/hotel/max300/532/5329930.jpg
* @param string $targetPath – lcoal path, for example /home/kim/photo/max300/532/5329930.jpg
* @return boolean – return false when no overwrite, return true when download successfully
*/
function saveImage($img, $targetPath, $forceRefresh = true)
{
if (file_exists($targetPath) and !$forceRefresh) {
return false;
}

$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata = curl_exec($ch);
curl_close($ch);
if (file_exists($targetPath)) {
unlink($targetPath);
}
if ($fp = @fopen($targetPath, ‘x’)) {
fwrite($fp, $rawdata);
fclose($fp);
}
return true;
}
[/codesyntax]

 


 

4. Transform array to sql binds:

 

[codesyntax lang=”php” lines=”no”]
/**
* transform array to sql binds
*
* @example
* $bind = array(‘value_1’, ‘value_2’, ‘value_3’);
* $sql = “DELETE FROM content WHERE cid IN (” . arrayToBinds($bind) . “)”;
*
* @param mixed $data
* @return string
*/
function arrayToBinds($data)
{
if (!is_array($data)) {
return “‘” . (string)$data . “‘”;
} else {
$count = count($data);
$return = ”;
for ($i = 0; $i < $count; $i++) {
$return .= “‘” . $data[$i] . “‘”;
if ($i != $count – 1) {
$return .= ‘, ‘;
}
}
return $return;
}
}
[/codesyntax]

 


 

5. List dirs tree – 1

 

[codesyntax lang=”php” lines=”no”]
function listTree($dir)
{
if (!$dirHandler = @dir($dir)) {
return;
}

while (false !== ($object = $dirHandler->read())) {
if ($object == ‘.’ || $object == ‘..’) {
continue;
}

$file = $dir . DIRECTORY_SEPARATOR . $object;

if (is_dir($file)) {
listTree($file);
} else if (is_file($file)) {
echo $file . ”;
}
}

$dirHandler->close();
}
[/codesyntax]

 


 

6. List dirs tree – 2

 

[codesyntax lang=”php” lines=”no”]
function listTree($dir)
{
if (!$dirHandler = @opendir($dir)) {
return;
}

while (false !== ($object = readdir($dirHandler))) {
if ($object == ‘.’ || $object == ‘..’) {
continue;
}

$file = $dir . DIRECTORY_SEPARATOR . $object;

if (is_dir($file)) {
listTree($file);
} else if (is_file($file)) {
echo $file . ”;
}
}

closedir($dirHandler);
}
[/codesyntax]

 


 

7. Safe encoding for utf-8

 
[codesyntax lang=”php” lines=”no”]
/**
* safe encoding to utf-8, especially for chinese
*
* @param string $string
* @param string $outEncoding
* @return unknown|string
*/
function safeEncoding($string, $outEncoding = ‘UTF-8’)
{
$encoding = “UTF-8”;
for ($i = 0; $i < strlen($string); $i++) { if (ord($string{$i}) < 128) continue; if ((ord($string{$i}) & 224) == 224) { // 第一个字节判断通过 $char = $string{++$i}; if ((ord($char) & 128) == 128) { // 第二个字节判断通过 $char = $string{++$i}; if ((ord($char) & 128) == 128) { $encoding = "UTF-8"; break; } } } if ((ord($string{$i}) & 192) == 192) { //第一个字节判断通过 $char = $string{++$i}; if ((ord($char)&128) == 128) { // 第二个字节判断通过 $encoding = "GB2312"; break; } } } if (strtoupper($encoding) == strtoupper($outEncoding)) { return $string; } else { //return iconv($encoding,$outEncoding,$string); return mb_convert_encoding($string,$outEncoding, $encoding); } } [/codesyntax]  


 

8. Get http request headers

 
[codesyntax lang=”php” lines=”no”]
/**
* @return array
*/
function getHeaders()
{
$headers = array();
foreach ($_SERVER as $k => $v) {
if (substr($k, 0, 5) == “HTTP_”) {
$k = str_replace(‘_’, ‘ ‘, substr($k, 5));
$k = str_replace(‘ ‘, ‘-‘, ucwords(strtolower($k)));
$headers[$k] = $v;
}
}
return $headers;
}
[/codesyntax]

 


 

9. Check if ip match the CIDR(array)

 

[codesyntax lang=”php” lines=”no”]
/**
* check if the ip within the cidr(array)
*
* @param string $ip – example: 218.206.78.45
* @param array|string $cidr – example: $chinamobilenet = array(
‘112.0.0.0/10’,
‘117.128.0.0/10’,
‘120.192.0.0/10’,
‘211.103.0.0/17’,
‘211.136.0.0/14’,
‘211.140.0.0/15’,
‘211.142.0.0/17’,
‘211.143.0.0/16’,
‘218.200.0.0/14’,
‘218.206.0.0/15’,
‘221.130.0.0/15’,
‘221.176.0.0/13’,
);
* @return bool
*/
function matchCIDR($ip, $cidr)
{
$output = false;
if (is_array($cidr)) {
foreach ($cidr as $cidrlet) {
if (matchCIDR($ip, $cidrlet)) {
$output = true;
}
}
} else {
list($net, $mask) = explode(‘/’, $cidr);

$ip_b_string = sprintf(“%032b”, ip2long($ip));
$net_b_string = sprintf(“%032b”, ip2long($net));

$result = substr_compare($ip_b_string, $net_b_string, 0, $mask);
$output = ($result === 0);
}
return $output;
}
[/codesyntax]

 


 

10. Standard I/O example

 

[codesyntax lang=”php” lines=”no”]
/**
* standard I/O
*
* @example
* /usr/bin/php t.php string1
*
* @return void – output trimed input
*/
if (isset($argv[1])) {
$output = trim($argv[1]);
fwrite(STDOUT, $output);
fclose(STDOUT);
}
[/codesyntax]