php常用代码

$total_count = mysql_num_rows($rslt);//返回记录条数

date("ymdHis");//130618104741 注:年份没有前两位 PHP手册:y 2 位数字表示的年份 例如:99 或 03

date("I");//是否为夏令时

date("U");//从 Unix 纪元(January 1 1970 00:00:00 GMT)开始至今的秒数;同time();

date_default_timezone_set('PRC'); //默认时区     
echo "今天:",date("Y-m-d",time()),"<br>";     
echo "今天:",date("Y-m-d",strtotime("18 june 2008")),"<br>";     
echo "昨天:",date("Y-m-d",strtotime("-1 day")), "<br>";     
echo "明天:",date("Y-m-d",strtotime("+1 day")), "<br>";     
echo "一周后:",date("Y-m-d",strtotime("+1 week")), "<br>";     
echo "一周零两天四小时两秒后:",date("Y-m-d G:H:s",strtotime("+1 week 2 days 4 hours 2 seconds")), "<br>";     
echo "下个星期四:",date("Y-m-d",strtotime("next Thursday")), "<br>";     
echo "上个周一:".date("Y-m-d",strtotime("last Monday"))."<br>";     
echo "一个月前:".date("Y-m-d",strtotime("last month"))."<br>";     
echo "一个月后:".date("Y-m-d",strtotime("+1 month"))."<br>";     
echo "十年后:".date("Y-m-d",strtotime("+10 year"))."<br>";

echo (strtotime('2020-5-20′)-strtotime(date(“Y-m-d”)))/86400; //php判断一个日期距今天还有多少天

$efp = fopen ("/tmp/debug.txt", "a");//可用于ajax调试中记录变量的值,file_put_contents("/tmp/debug.txt",$temp,FILE_APPEND);也可做同样的功能
fwrite($efp, "222222222\n");
fclose($efp);

$_SERVER['HTTP_HOST'];//服务器ip

getenv("REMOTE_ADDR");//客户端ip

substr(strrchr($str,'/'),1);//取url中的文件名 如:http://www.test.com/a.txt,将取出a.txt

#从命令行读取数据

$stdin = fopen ('php://stdin', 'r');
while (true)
{
$command = trim (fgets ($stdin, 1024));
echo $command ."\n";
}

#将windows下的换行替换成linux下的换行

file_put_contents('/tmp/test.txt',str_replace("\r\n","\n",$str));

#输出当前函数的调用关系

foreach(debug_backtrace() as $key => $value)
{
        echo $value['file'] . "\011" . $value['line'] . "\011" . $value['function']. "\n";
}
 
#在命令行执行一条php语句
php -r "echo time();"
 
#Yii中CListView类的renderItems()方法说明:

//除非数组是被引用,foreach 所操作的是指定数组的一个拷贝,而不是该数组本身。[php手册中对foreach的说明]
$data = array("a","b","c","d","e");
foreach($data as $i=>$item)
{
  var_dump($data);
  $data=array();          //虽然这里清空了变量,但是循环还是照常进行
  $data['index']=$i;
  $data['data']=$item;
  $data['widget']=$this;
  echo "$item===\n";
}

#zend5.5中文乱码

配置文件中的desktop_options.xml中的editing.encoding选项修改成"UTF-8"(必须大写)

C:/Documents and Settings/用户名/ZDE/config_5.5/desktop_options.xml

#获取刚插入数据的id

$stmtA = "select LAST_INSERT_ID() LIMIT 1;";
$rslt = mysql_query($stmtA, $link);
$row = mysql_fetch_array($rslt);
$id = $row[0];

#php cli下接收参数数组

$argv

#mysql 获取一小时前时间

select date_sub(now(), interval 1 hour);

select date_sub(now(), interval -1 hour);      //一小时后

select date_add(now(), interval 1 hour);       //一小时后, 更多可选值参考[1] [2]

#查看数据库中所有表的记录数 [1]
select table_name,table_rows from information_schema.tables
where TABLE_SCHEMA = 'test'
order by table_name desc; #php检测字符串编码
echo mb_detect_encoding($str);
echo mb_detect_encoding($str, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
echo iconv('GB2312', 'UTF-8', $str); //将字符串编码从gbk转换成utf-8 #php判断中文文件名
$realname = iconv('UTF-8','GB2312',"C:\Documents and Settings\用户名\My Documents\下载\CentOS-6.5-i386-minimal.iso");
var_dump(file_exists($realname));
#php求文件的sha1sum
echo sha1_file($realname);
#php求文件的sha256
echo hash_file("sha256", $realname); #简单性能测试
function run_count_one_sec()
{
$time = time();
$i = 0;
while ($time == time())
{
//================Code Begin
//push_info(); //1806
//file_exists("config.php"); //318556
//include_once("config.php"); //323724
//================Code End
$i++; //2660728
}
return $i;
} $run_times_sec = array();
for($j = 0; $j <3; $j++)
{
$run_times_sec[$j] = run_count_one_sec();
}
var_dump($run_times_sec);
echo intval(($run_times_sec[1] + $run_times_sec[2])/2) . "\n"; #显示表中的所有字段
SHOW FULL FIELDS FROM users;
SHOW KEYS FROM users; #CI中上传文件时生成随机文件名的方法
$filename = md5(uniqid(mt_rand()));
echo uniqid('php_' . mt_rand()) . "<br />";//生成一个php前辍 #curl使用seesion和cookie
function get_url_content($url,$post_data = null,$time_out = 30,$cookie_file = ''){
$cookiefile = dirname(__FILE__).DIRECTORY_SEPARATOR.'tmp'. DIRECTORY_SEPARATOR ."test_$cookie_file.txt";
if(!file_exists($cookiefile)){file_put_contents($cookiefile,"");} $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt( $ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookiefile); //指定保存cookie和session的文件
curl_setopt( $ch, CURLOPT_COOKIEFILE,$cookiefile); //指定发送给服务器的cookie和session文件 // POST数据
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_TIMEOUT,$time_out);
$output = curl_exec($ch);
curl_close($ch); return $output;
} function get_url_content($url, $post_data = null, $time_out = 30, $cookie_file = '', $request_type = 'GET'){
$cookiefile = dirname(__FILE__).DIRECTORY_SEPARATOR.'tmp'. DIRECTORY_SEPARATOR ."cookie_$cookie_file.txt";
if(!file_exists($cookiefile)){file_put_contents($cookiefile,"");} $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //$user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36';
//curl_setopt( $ch, CURLOPT_USERAGENT, $user_agent/*$_SERVER['HTTP_USER_AGENT']*/); //Curl增加 header
$headers = array(
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65",
//"Accept: application/json, text/javascript, */*; q=0.01",
);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers); curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookiefile); //指定保存cookie和session的文件
curl_setopt( $ch, CURLOPT_COOKIEFILE,$cookiefile); //指定发送给服务器的cookie和session文件 //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE); //不认证证书
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE); if($request_type == 'POST'){
curl_setopt($ch, CURLOPT_POST, 1); // 标识要POST数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // 把POST的变量加上
}
curl_setopt($ch, CURLOPT_TIMEOUT,$time_out);
$output = curl_exec($ch); //$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 如果返回非200可做日志记录 curl_close($ch); return $output;
} #格式化成等宽字符串,不足前面补0
echo sprintf("%04d", 1); #通过file_get_contents函数Post数据
function http_post($post_data,$url)
{
$context = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($post_data)
)
); $stream_post_data = stream_context_create($context); $result = file_get_contents($url, false, $stream_post_data);
return $result;
} #mysql时间戳转时期时间
SELECT *, FROM_UNIXTIME( created_at, '%Y-%m-%d %H:%i:%s' ) as date1 FROM `user`; #新建表
CREATE DATABASE `test2` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; #php通过Zip打包文件
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->addFile('info.txt', 'entryname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
} #获取当前目录
define('APP_PATH', dirname(__FILE__) . '/'); #获取php的输出缓存
ob_start();
phpinfo();
$out = ob_get_contents();
ob_end_clean(); file_put_contents(APP_PATH . 'phpinfo.txt', $out); #将表的自增ID修改成指定数字
alter table user auto_increment = 1001; #Chrome 自带了一个功能非常强大的 HTTP 抓包系统 [1]
chrome://net-internals/#events #mysql将行中的字段连接
SELECT GROUP_CONCAT(taskNumber SEPARATOR "' , '") AS taskNumber FROM workorder where id < 12510 #如果在命令行换行符不需要br标签
if(PHP_SAPI == 'cli'){
$br = "\n";
} else {
$br = "<br />\n";
} #json字符串decode时如果里面存在很大的数字可以添加转换标识将大数转换成字符串
json_decode($json_str, true, 512, JSON_BIGINT_AS_STRING) #只能为中文的简单过滤
if($name != "" && !preg_match('/^[-a-zA-Z0-9\x{4e00}-\x{9fa5}]{1,20}$/u', $name)){
//
} #取文件扩展名
function getFileExt($filename)
{
return strtolower(strrchr($filename, '.'));
} function get_file_ext($file_name = '')
{
if ($file_name != '' && strpos($file_name, '.')) {
$file_path_info = pathinfo($file_name);
return $file_path_info['extension'];
}
return '';
} echo getFileExt("/img/20180606/u_1528251036985944.jpg");//.jpg #去除json配置文件中的"/**/"注释
json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("config.json")), true) #PHP中浮点数处理 [1]
echo intval(9.7 * 100); //969
echo intval(strval(9.7 * 100)); //970
上一篇:Lambda表达式演变


下一篇:install phpexcel using composer in thinkPHP