1、超级简单的页面缓存
如果你的工程项目不是基于 CMS 系统或框架,打造一个简单的缓存系统将会非常实在。下面的代码很简单,但是对小网站而言能切切实实解决问题。
// define the path and name of cached file
$cachefile = 'cached-files/'.date('M-d-Y').'.php';
// define how long we want to keep the file in seconds. I set mine to 5 hours.
$cachetime = 18000;
// Check if the cached file is still fresh. If it is, serve it up and exit.
if (file_exists($cachefile) && time() - $cachetime include($cachefile);
exit;
}
// if there is either no file OR the file to too old, render the page and capture the HTML.
ob_start();
?>
output all your html here.
// We're done! Save the cached content to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// finally send browser output
ob_end_flush();
?>
点击这里查看详细情况:http://wesbos.com/simple-php-page-caching-technique/
2、在 PHP 中计算距离
这是一个非常有用的距离计算函数,利用纬度和经度计算从 A 地点到 B 地点的距离。该函数可以返回英里,公里,海里三种单位类型的距离。
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
使用方法:
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k")." kilometers";
点击这里查看详细情况:http://www.phpsnippets.info/calculate-distances-in-php
3、将秒数转换为时间(年、月、日、小时…)
这个有用的函数能将秒数表示的事件转换为年、月、日、小时等时间格式。
function Sec2Time($time){
if(is_numeric($time)){
$value = array(
"years" => 0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
return (array) $value;
}else{
return (bool) FALSE;
}
}
点击这里查看详细情况:http://ckorp.net/sec2time.php
4、强制下载文件
一些诸如 mp3 类型的文件,通常会在客户端浏览器中直接被播放或使用。如果你希望它们强制被下载,也没问题。可以使用以下代码:
function downloadFile($file){
$file_name = $file;
$mime = 'application/force-download';
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile($file_name); // push it out
exit();
}
点击这里查看详细情况:Credit: Alessio Delmonti
5、使用 Google API 获取当前天气信息
想知道今天的天气?这段代码会告诉你,只需 3 行代码。你只需要把其中的 ADDRESS 换成你期望的城市。
$xml = simplexml_load_file('http://www.google.com/ig/api?weather=ADDRESS');
$information = $xml->xpath("/xml_api_reply/weather/current_conditions/condition");
echo $information[0]->attributes();
点击这里查看详细情况:http://ortanotes.tumblr.com/post/200469319/current-weather-in-3-lines-of-php
6、获得某个地址的经纬度
随着 Google Maps API 的普及,开发人员常常需要获得某一特定地点的经度和纬度。这个非常有用的函数以某一地址作为参数,返回一个数组,包含经度和纬度数据。
function getLatLong($address){
if (!is_string($address))die("All Addresses must be passed as a string");
$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
$_result = false;
if($_result = file_get_contents($_url)) {
if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
$_coords['lat'] = $_match[1];
$_coords['long'] = $_match[2];
}
return $_coords;
}
点击这里查看详细情况:http://snipplr.com/view.php?codeview&id=47806
7、使用 PHP 和 Google 获取域名的 favicon 图标
有些网站或 Web 应用程序需要使用来自其他网站的 favicon 图标。利用 Google 和 PHP 很容易就能搞定,不过前提是 Google 不会连接被重置哦!
function get_favicon($url){
$url = str_replace("http://",'',$url);
return "http://www.google.com/s2/favicons?domain=".$url;
}
点击这里查看详细情况:http://snipplr.com/view.php?codeview&id=45928

세션 고정 공격을 방지하는 효과적인 방법은 다음과 같습니다. 1. 사용자 로그인 한 후 세션 ID 재생; 2. 보안 세션 ID 생성 알고리즘을 사용하십시오. 3. 세션 시간 초과 메커니즘을 구현하십시오. 4. HTTPS를 사용한 세션 데이터를 암호화합니다. 이러한 조치는 세션 고정 공격에 직면 할 때 응용 프로그램이 파괴 할 수 없도록 할 수 있습니다.

서버 측 세션 스토리지가없는 토큰에 저장되는 토큰 기반 인증 시스템 인 JSONWEBTOKENS (JWT)를 사용하여 세션없는 인증 구현을 수행 할 수 있습니다. 1) JWT를 사용하여 토큰을 생성하고 검증하십시오. 2) HTTPS가 토큰이 가로 채지 못하도록하는 데 사용되도록, 3) 클라이언트 측의 토큰을 안전하게 저장, 4) 변조 방지를 방지하기 위해 서버 측의 토큰을 확인하기 위해 단기 접근 메커니즘 및 장기 상쾌한 토큰을 구현하십시오.

PHP 세션의 보안 위험에는 주로 세션 납치, 세션 고정, 세션 예측 및 세션 중독이 포함됩니다. 1. HTTPS를 사용하고 쿠키를 보호하여 세션 납치를 방지 할 수 있습니다. 2. 사용자가 로그인하기 전에 세션 ID를 재생하여 세션 고정을 피할 수 있습니다. 3. 세션 예측은 세션 ID의 무작위성과 예측 불가능 성을 보장해야합니다. 4. 세션 중독 데이터를 확인하고 필터링하여 세션 중독을 방지 할 수 있습니다.

PHP 세션을 파괴하려면 먼저 세션을 시작한 다음 데이터를 지우고 세션 파일을 파괴해야합니다. 1. 세션을 시작하려면 세션 _start ()를 사용하십시오. 2. Session_Unset ()을 사용하여 세션 데이터를 지우십시오. 3. 마지막으로 Session_Destroy ()를 사용하여 세션 파일을 파괴하여 데이터 보안 및 리소스 릴리스를 보장하십시오.

PHP의 기본 세션 저장 경로를 변경하는 방법은 무엇입니까? 다음 단계를 통해 달성 할 수 있습니다. session_save_path를 사용하십시오 ( '/var/www/sessions'); session_start (); PHP 스크립트에서 세션 저장 경로를 설정합니다. php.ini 파일에서 세션을 설정하여 세션 저장 경로를 전 세계적으로 변경하려면 세션을 설정하십시오. memcached 또는 redis를 사용하여 ini_set ( 'session.save_handler', 'memcached')과 같은 세션 데이터를 저장합니다. ini_set (

tomodifyDatainAphPessess, startSessionstession_start (), 그런 다음 $ _sessionToset, modify, orremovevariables.

배열은 PHP 세션에 저장할 수 있습니다. 1. 세션을 시작하고 session_start ()를 사용하십시오. 2. 배열을 만들고 $ _session에 저장하십시오. 3. $ _session을 통해 배열을 검색하십시오. 4. 세션 데이터를 최적화하여 성능을 향상시킵니다.

PHP 세션 쓰레기 수집은 만료 된 세션 데이터를 정리하기위한 확률 메커니즘을 통해 트리거됩니다. 1) 구성 파일에서 트리거 확률 및 세션 수명주기를 설정합니다. 2) CRON 작업을 사용하여 고재 응용 프로그램을 최적화 할 수 있습니다. 3) 데이터 손실을 피하기 위해 쓰레기 수집 빈도 및 성능의 균형을 맞춰야합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
