- 遍历目录下的所有文件及文件夹
function fileShow($dir){
$handle = opendir($dir);
while ($file = readdir($handle)) {
if ($file !== '..' && $file !== '.') {
$f = $dir . '/' . $file;
if (is_file($f)) {
echo '|--' . $file . '
';
} else {
echo '--' . $file . '
';
fileShow($f);
}
}
}
}
- 单例模式创建 mysqli 链接
class db
{
private $con;
private static $instance;
private function __construct($host, $username, $password, $database)
{
$this->con = mysqli_connect($host, $username, $password);
if (!$this->con) die("连接失败!");
mysqli_select_db($database);
}
public static function getInstance($host, $username, $password, $database)
{
if (self::$instance) return self::$instance;
self::$instance = new db($host, $username, $password, $database);
}
public function close()
{
return mysqli_close($this->con);
}
private function __clone()
{
}
}
- 获取一个网页地址的内容
$url = "http://www.phpres.com/index.html";
$str = file_get_contents($url);
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_exec($ch);
curl_close($ch);
- 从 url 获取文件的扩展名
function getExt1 () {
$url_path = "http://www.sina.com.cn/abc/de/fg.php?id=1";
$temp = pathinfo($url_path, PATHINFO_EXTENSION);
$temp = explode("?", $temp);
echo $temp[0];
}
function getExt2 () {
$url_path = "http://www.sina.com.cn/abc/de/fg.php?id=1";
$temp = parse_url($url_path);
echo pathinfo($temp['path'], PATHINFO_EXTENSION);
}
- 获取一个文件的扩展名
function get_ext1 ($file_name) {
return strrchr($file_name, '.');
}
function get_ext2 ($file_name) {
return substr($file_name, strrpos($file_name, '.'));
}
function get_ext3 ($file_name) {
$tmp = explode('.', $file_name);
return array_pop($tmp);
}
function get_ext4 ($file_name) {
return pathinfo($file_name, PATHINFO_EXTENSION);
}
- 转换驼峰式字符串
function conversion1 () {
$str = "open_door";
return ucwords(str_replace('_',' ',$str));
- header( ) 跳转页面
header('location:index.php');
header("HTTP/1.1 404 Not Found");
- 使用正则表达式去除其中的所有js脚本
$pattern = '/.*<\/script>/i';
preg_replace($pattern,'',$str);
- 将一个数组里的空值去掉\S 匹配任何非空白字符。i不区分大小写
$arr = array("",1,2,3,"");
$ptn = "/\S+/i";
print_r(preg_grep($ptn,$arr));
- 给出年份和月份,输出指定月份的天数
function dayCount($year, $month) {
echo date('t', strtotime($year . '-' . $month . '-1'));
}
- 编写函数取得上一月的最后一天
function get_last_month_last_day(){
$date = "2021-2-18";
$time = strtotime($date);
$day = date('j',$time);
return date('Y-m-d',strtotime("-{$day} days",$time));}
- 确保多个进程同时写入同一个文件成功
$fp = fopen("lock.txt","w+");
if(flock($fp, LOCK_EX)) {
fwrite($fp, "write something");
flock($fp, LOCK_UN);
} else {
echo "file is locking";
}
fclose($fp);
- 将字符串08/26/2003替换为2003-08-26
$str = '08/26/2003';
$pattern = '/(\d+)\/(\d+)\/(\d+)/';
$rep = '$3-$1-$2';
echo preg_replace($pattern, $rep, $str);
- 求两个日期的差数
$day1 = '2003-09-16';
$day2 = '2011-11-23';
$d1 = new dateTime($day1);
$d2 = new dateTime($day2);
echo $d1->diff($d2)->days;
echo (strtotime($day2) - strtotime($day1))/(86400);