function safe_string($str){ //過濾安全字符
$str=str_replace("'","",$str);
$str=str_replace('"',"",$str);
$str=str_replace(" ","$nbsp;",$str);
$str=str_replace("\n;","
",$str);
$str=str_replace("<","<",$str);
$str=str_replace(">",">",$str);
$str=str_replace("\t"," ",$str);
$str=str_replace("\r","",$str);
$str=str_replace("/[\s\v]+/"," ",$str);
return $str;
}
2013年5月29日 星期三
網站 壓力測試
ab - Apache HTTP server benchmarking tool
http://httpd.apache.org/docs/2.2/programs/ab.html
ab 工具程式是 Apache 網站伺服器軟體的一個附帶的工具軟體,專門用來執行網站伺服器的運行效能
說明:http://blog.miniasp.com/post/2008/06/30/Using-ApacheBench-ab-to-to-Web-stress-test.aspx
http://httpd.apache.org/docs/2.2/programs/ab.html
ab 工具程式是 Apache 網站伺服器軟體的一個附帶的工具軟體,專門用來執行網站伺服器的運行效能
說明:http://blog.miniasp.com/post/2008/06/30/Using-ApacheBench-ab-to-to-Web-stress-test.aspx
2013年4月23日 星期二
排序更改
示意片:
$sort =$_POST['sort'];
$sortBL =$_POST['sortBL'];
$year =$_POST['year'];
$cat =$_POST['cat'];
$id =$_POST['sn'];
//B 代表 前面
//L 代表 後面
if($sort=='abcd')
echo_script_alert_ref("無效選擇,請勿選擇自己","XXXXX");
if($sortBL=='B'){//改到xxx之前
$sql="UPDATE col_doc_xxx SET sort=sort+1 WHERE sort >= '$sort' AND year_sn='$year' AND cat_sn='$cat'";
mysql_query($sql);
//塞此id 的sort 為$sort
$sql="UPDATE col_doc_xxx SET sort=$sort WHERE file_sn='$id'";
mysql_query($sql);
}
if($sortBL=='L'){// 改到XXX之後
$sql="UPDATE col_doc_xxx SET sort=sort-1 WHERE sort <= '$sort' AND year_sn='$year' AND cat_sn='$cat'";
mysql_query($sql);
//塞此id 的sort 為$sort
$sql="UPDATE col_doc_xxx SET sort=$sort WHERE file_sn='$id'";
mysql_query($sql);
}
echo_script_alert_ref("更新完成","xxx");
過濾$_GET和$_POST
Q:從使用者輸入篩除危險的字元
正確網址加 /index.php?module=Opportunities&action=/../../../../../../../../boot.ini%
00&advanced=true HTTP/1.0
<?php
/*
判斷傳遞的變量中是否含有非法字符
//要過濾的非法字符 如post get
*/
$ArrFiltrate=array("’",";","union","true","../");
//出錯後要跳轉的url,不填則默認前一頁
$StrGoUrl="http://XXX.tw";
//是否存在數組中的值
function FunStringExist($StrFiltrate,$ArrFiltrate){
foreach ($ArrFiltrate as $key=>$value){
if(eregi($value,$StrFiltrate)){
return true;
}
}
return false;
}
foreach($_POST as $key=>$value){
$ArrayPostAndGet[]=$value;
}
foreach($_GET as $key=>$value){
$ArrPostAndGet[]=$value;
}
//驗證開始
foreach($ArrPostAndGet as $key=>$value){
if(FunStringExist($value,$ArrFiltrate)){
if(empty($StrGoUrl)){
echo "<script>history.go(-1);</script>";
}else{
echo_script_alert_ref("非法字符",'');
}
}
}
?>
範例:以下連結會被過濾 將不能執行正確網址加 /index.php?module=Opportunities&action=/../../../../../../../../boot.ini%
00&advanced=true HTTP/1.0
2013年4月9日 星期二
ini_set error 、DIRECTORY_SEPARATOR
設定php發生錯誤的等級
ini_set('error_reporting', E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('track_errors', '1');
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
DIRECTORY_SEPARATOR
DIRECTORY_SEPARATOR是php的內部常量,用於顯示系統分隔符的命令,不需要任何定義與包含即可直接使用。在windows下路徑分隔符是\(當然/在部分系統上也是可以正常運行的),在linux上路徑的分隔符是/,這就導致了一個問題,比如伺服器是windows,有一個圖片上傳程序,伺服器上指定的上傳文件保存目錄是define('ROOT', dirname(__FILE__)."/upload");
ini_set('error_reporting', E_ALL);
| Constant | Description | Note |
|---|---|---|
| E_NOTICE | Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. | |
| E_STRICT | Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. | Since PHP 5 but not included in E_ALL until PHP 5.4.0 |
| E_ALL | All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0. |
ini_set('error_reporting', E_ALL);
ini_set('track_errors', '1');
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
DIRECTORY_SEPARATOR
DIRECTORY_SEPARATOR是php的內部常量,用於顯示系統分隔符的命令,不需要任何定義與包含即可直接使用。在windows下路徑分隔符是\(當然/在部分系統上也是可以正常運行的),在linux上路徑的分隔符是/,這就導致了一個問題,比如伺服器是windows,有一個圖片上傳程序,伺服器上指定的上傳文件保存目錄是define('ROOT', dirname(__FILE__)."/upload");
於是php引入了DIRECTORY_SEPARATOR變量,可以將上面的寫法改寫为:
2013年3月26日 星期二
ckeditor 4.1 範例
<!DOCTYPE html> <html> <head> <title> 路上線上預約系統-編輯借用路邊及垃圾使用規則</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script src="ckeditor/ckeditor.js"></script> <link rel="stylesheet" href="ckeditor/contents.css"> </head> <form action='comm.php?method=up_rule' method='post'> <textarea class="ckeditor" cols="60" id="editor1" name="editor1" rows="10"> <?php echo $data['rule']; ?> </textarea> <input type='hidden' name='op' value='edit'> <input type='submit' value='更新規則'> </form> <input type="button" onclick="doClose()" value="關閉此頁面"/> </body> </html>補充:HTML5 起始1
用到上傳圖片功能的 config.js
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
config.uiColor = '#AADC6E';
config.toolbar = [
['Bold','Italic','Underline','Strike','-'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
['TextColor','BGColor','Maximize','ShowBlock'], ['Link','Unlink','Anchor','Table','HorizontalRule'],'/',['Styles','Format','Font','FontSize','Source','Image']
];
config.filebrowserImageUploadUrl = '../../script/ckeditor4.1/upload1.php?type=img';
};
upload1.php(上傳圖片用的程式)<?php
$config=array();
$config['type']=array("flash","img"); //上傳允許type值
$config['img']=array("jpg","bmp","gif","png"); //img允許后綴
$config['flash']=array("flv","swf"); //flash允許后綴
$config['flash_size']=200; //上傳flash大小上限 單位:KB
$config['img_size']=2000; //上傳img大小上限 單位:KB
//$config['message']="上傳成功"; //上傳成功后顯示的消息,若為空則不顯示
$config['name']=mktime(); //上傳后的文件命名規則 這里以unix時間戳來命名
$config['img_dir']="uploadtpd/img"; //上傳img文件地址
$config['site_url']="http://XXXXX/coledXX/tpd/"; //網站的網址 這與圖片上傳后的地址有關 最后不加"/" 可留空
//在上傳圖片後會在URL會用到,並寫到資料庫裡去。
//文件上傳
uploadfile();
function uploadfile()
{
global $config;
//判斷是否是非法調用
if(empty($_GET['CKEditorFuncNum']))
mkhtml(1,"","錯誤的功能調用請求4");
$fn=$_GET['CKEditorFuncNum'];
if(!in_array($_GET['type'],$config['type']))
mkhtml(1,"","錯誤的文件調用請求3");
$type=$_GET['type'];
if(is_uploaded_file($_FILES['upload']['tmp_name']))
{
//判斷上傳文件是否允許
$filearr=pathinfo($_FILES['upload']['name']);
$filetype=$filearr["extension"];
if(!in_array($filetype,$config[$type]))
mkhtml($fn,"","錯誤的文件類型!2");
//判斷文件大小是否符合要求
if($_FILES['upload']['size']>$config[$type."_size"]*1024)
mkhtml($fn,"","上傳的文件不能超過".$config[$type."_size"]."KB!");
//$filearr=explode(".",$_FILES['upload']['name']);
//$filetype=$filearr[count($filearr)-1];
//$file_abso=$config[$type."_dir"]."/".$config['name'].".".$filetype;
$file_abso=$config[$type."_dir"]."/".$config['name'].".".$filetype; //資料夾和檔案路徑
//echo $file_abso;
//exit;
// $file_host=$_SERVER['DOCUMENT_ROOT'].$file_abso; //絕對路徑
$file_host="../../../".$config[$type."_dir"]."/".$config['name'].".".$filetype; //相對路徑
// echo $file_host;
//exit;
if(move_uploaded_file($_FILES['upload']['tmp_name'],$file_host))
{
mkhtml($fn,$config['site_url'].$file_abso,$config['message']);
}
else
{
mkhtml($fn,"","文件上傳失敗,請檢查上傳目錄設置和目錄讀寫權限");
}
}
}
//輸出js調用
function mkhtml($fn,$fileurl,$message)
{
$str='<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$fn.', \''.$fileurl.'\', \''.$message.'\');</script>';
exit($str);
}
?>
補充說明:陣列,檔案操作
QA
抓BUG抓不出來,面版一直是最簡單的。
最後把tpd/tpdadmin/script/4.1丟上 社x院即成。
2013年2月18日 星期一
上傳檔案簡易版
創建 FILE UPLOAD
Create The Upload Script
if ($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "";
}else{
echo "Upload: " . $_FILES["file"]["name"] . "";
echo "Type: " . $_FILES["file"]["type"] . "";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
$_FILES["file"]["name"] - the name of the uploaded file$_FILES["file"]["type"] - the type of the uploaded file
$_FILES["file"]["size"] - the size in kilobytes of the uploaded file
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload
2013年2月5日 星期二
MAIL OUTLOOK 信中有亂碼(主旨、寄件人、內容)產生
情況:收的人用outlook收信,發現是一團亂碼。
主旨、寄件人 皆比照辦理
header
如果再不見,只好見官方PHP 的MAIL 有前輩提供了一個fuhction..
網址:http://www.php.net/manual/en/function.mail.php#92976
因為寄件人亂碼了,所以做了變化,不知道有沒有成功。
Encodes the given data with base64.
This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
Base64-encoded data takes about 33% more space than the original data.
參考連結:
php mail 寄送會有亂碼: 解決方式如下:
http://www.macsoho.net/blog/?p=143
http://www.php.net/manual/en/function.mail.php#92976
參考:
主旨、寄件人 皆比照辦理
$subject = "天氣 ".$state." 可能會..."; 添加base64_encode $subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";內容:加入html 和charset=utf-8
$message = 'Fillon soutient à fond le retour d\'un Grand Prix de France Le Premier ministre François Fillon, passionné d\'automobile et pilote à ses heures, a apporté un soutien appuyé au retour d\'un Grand Prix de France au calendrier 2013 de la Formule 1, en faisant un passage-éclair vendredi sur le circuit Paul Ricard dans le Var.
header
$headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=utf- 8\r\n";
如果再不見,只好見官方PHP 的MAIL 有前輩提供了一個fuhction..
網址:http://www.php.net/manual/en/function.mail.php#92976
/* ** * Function responsible for sending unicode emails. * * @author Gajus Kuizinas2013.05.17 新增* @version 1.0.1 (2012 01 11) */ function mail_send($arr) { if (!isset($arr['to_email'], $arr['from_email'], $arr['subject'], $arr['message'])) { throw new HelperException('mail(); not all parameters provided.'); } $to = empty($arr['to_name']) ? $arr['to_email'] : '"' . mb_encode_mimeheader($arr['to_name']) . '" <' . $arr['to_email'] . '>'; $from = empty($arr['from_name']) ? $arr['from_email'] : '"' . mb_encode_mimeheader($arr['from_name']) . '" <' . $arr['from_email'] . '>'; $headers = array ( 'MIME-Version: 1.0', 'Content-Type: text/html; charset="UTF-8";', 'Content-Transfer-Encoding: 7bit', 'Date: ' . date('r', $_SERVER['REQUEST_TIME']), 'Message-ID: <' . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>', 'From: ' . $from, 'Reply-To: ' . $from, 'Return-Path: ' . $from, 'X-Mailer: PHP v' . phpversion(), 'X-Originating-IP: ' . $_SERVER['SERVER_ADDR'], ); mail($to, '=?UTF-8?B?' . base64_encode($arr['subject']) . '?=', $arr['message'], implode("\n", $headers)); }
因為寄件人亂碼了,所以做了變化,不知道有沒有成功。
function mail_send($arr)
{
if (!isset($arr['to_email'], $arr['from_email'], $arr['subject'], $arr['message'])) {
throw new HelperException('mail(); not all parameters provided.');
}
$to = empty($arr['to_name']) ? $arr['to_email'] : '"' . mb_encode_mimeheader($arr['to_name']) . '" <' . $arr['to_email'] . '>';
//針對寄件人的姓名做DEBUG避免寄件人姓名亂碼
$from = empty($arr['from_name']) ? $arr['from_email'] : '"' .'=?UTF-8?B?' . base64_encode( mb_encode_mimeheader($arr['from_name'])) . '?=' . '" <' . $arr['from_email'] . '>';
$headers = array
(
'MIME-Version: 1.0',
'Content-Type: text/html; charset="UTF-8";',
'Content-Transfer-Encoding: 7bit',
'Date: ' . date('r', $_SERVER['REQUEST_TIME']),
'Message-ID: <' . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
'X-Mailer: PHP v' . phpversion(),
'X-Originating-IP: ' . $_SERVER['SERVER_ADDR'],
);
mail($to, '=?UTF-8?B?' . base64_encode($arr['subject']) . '?=', $arr['message'], implode("\n", $headers));
}
base64_encode 解釋:Encodes the given data with base64.
This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
Base64-encoded data takes about 33% more space than the original data.
參考連結:
php mail 寄送會有亂碼: 解決方式如下:
http://www.macsoho.net/blog/?p=143
http://www.php.net/manual/en/function.mail.php#92976
參考:
2012年11月2日 星期五
[文章標題]在近N天的標題後加一個new的icon
function new_image($s_time){
$tc=(date('U',time())-date("U",strtotime($s_time)))/86400;
$tc_image_new='';
if($tc<=3)
$tc_image_new="
";
return $tc_image_new;
}
PS. 一天86400秒
icon finder: http://www.iconfinder.com/
您可能有興趣的書單:
2012年9月27日 星期四
php excel
EXCEL讀檔 寫入MYSQL
寫入excel
include_once("../XXX/phpexcel/PHPExcel/IOFactory.php");
include_once('../XXX/phpexcel/PHPExcel/Reader/Excel5.php');
if($_FILES['employeeData']['name']=="" )"ERROR!!no FILE!!";
$reader = new PHPExcel_Reader_Excel5;
$PHPExcel=$reader->load($_FILES['exployxeData']['tmp_name']);
$sheet=$PHPExcel->getSheet(0);
$highestRow=$sheet->getHighestRow();
for($row=1;$row<=$highestRow;$row++){
//echo $i."$$";
$str='';
for($column=0;$column<=6;$column++){
$aa=$sheet->getCellByColumnAndRow($column,$row)->getvalue();
$temp[$column]=$aa;
if($column=='0'){
$str.="'".$aa."',";//id
$str.="'".$aa."',";//pwd
}elseif($column=='6'){
if($temp[4]==$temp[0]){
$str.="'1',";
}elseif($temp[6]=='1'){
$str.="'2',";
}else{
$str.="'0',";
}
}elseif($column=='5'){
continue;
}else{
if($aa!=''){
$str.="'".$aa."',";
}
}
}
$str=substr($str,0,strlen($str)-1);
if($row>1){
$sql="insert into Base (`ID`,`Pwd`,`Name`,`Name`,`Email`,`lID`,`role`)values($str)";
mysql_query($sql);
if(! mysql_affected_rows()>0){
echo "error:name:{$temp[1]}";
exit;
}
}
}
寫入excel
include_once("../class/phpexcel/PHPExcel/IOFactory.php");
$path="../download/";
$objRD=PHPExcel_IOFactory::createReader("Excel5");
$objExcel=$objRD->load($path."temp.xls");
//$CobjExcel=new PHPExcel();
//$objExcel=$CobjExcel->load($path."temp.xls");
$objExcel->setActiveSheetIndex(0);
$sheet=$objExcel->getActiveSheet();
for($i=1;$i<$num;$i++){
//if($data[$i]['enable']==0) continue; #因為sql裡面排除不了enable為0的,所以做此處理
$sheet->setCellValueByColumnAndRow(0,$colum,$searchContent[$i]['userName']);
$sheet->setCellValueByColumnAndRow(1,$colum,$searchContent[$i]['ID']);
$sheet->setCellValueByColumnAndRow(2,$colum,$searchContent[$i]['shifName']);
$colum++;
}
$objExcel=PHPExcel_IOFactory::createWriter($objExcel,'Excel5');
$filePath=$path."labor_hour.xls";
$objExcel->save($filePath);
dl_file($filePath);
2012年6月21日 星期四
西元轉民國 及 MS-DOS 版本編號
function DtoCh($dday, $st) {
//把西元日期改為民日期 $st為分隔符號
$tok= strtok($dday,$st);
$i = 0;
while ($tok){
$d[$i] =$tok;
$tok = strtok($st) ;
$i = $i+1 ;
}
$temp=strtok($d[2],' ');
$d[2]=$temp[0].$temp[1];
$d[0] = $d[0] - 1911 ;
$cday = $d[0]."/".$d[1]."/".$d[2] ;
return $cday ;
}
例子:DtoCh("2011-12-08 15:54:27",'-') ==> 100/12/08
MS-DOS 版本編號:
Windows 98 (Windows 4.1), Windows 98 Second Edition
Windows Millennium Edition (Windows 4.9)
Windows NT 4.0
Windows 2000 (Windows NT 5.0)
Windows XP (Windows NT 5.1)
Windows Server 2003 (Windows NT 5.2)
Windows Vista (Windows NT 6.0)
Windows Server 2008 (Windows NT 6.0)
Windows 7 (Windows NT 6.1)
Windows Server 2008 R2 (Windows NT 6.1)
Windows Home Server
Windows 8 (Windows NT 6.2)
2012年6月18日 星期一
取整函数ceil floor round intval
ceil —進一取整數
float ceil ( float $value )取回不小於 value 的下一個整数,value 如果有小數部分則進一位。
echo ceil(4.3); // 5
echo ceil(9.999); // 10
floor — 捨去法取整數
说明float floor ( float $value )
返回不大于 value 的下一个整数,将 value 的小数部分舍去取整。
echo floor(4.3); // 4
echo floor(9.999); // 9
round — 对浮点数进行四舍五入
说明float round ( float $val [, int $precision ] )
返回將 val 根据指定精度 precision(十进制小数点后数字的数目)进行四舍五入的结果
。precision 也可以是负数或零(默认值)。
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
intval —獲取整数值
说明int intval ( mixed $var [, int $base ] )
通过使用特定的进制转换(默认是十进制),返回变量 var 的 integer 数值。
var 可以是任何标量类型。intval() 不能用于 array 或 object。
intval() 例子
echo intval(4.3); // 4
echo intval(9.999); // 9
2012年6月6日 星期三
文字處理
文字處理:
語法 : int strpos (string haystack, string needle [, int offset])
substr --- 取得部份字串
語法 : string substr (string string, int start [, int length])
explode ---將字串依指定的字串或字元separator切開
語法:array explode(string separator, string string,[int limit])
將字串 "宅配通:123456789" 套用explode,條件":"
$a=explode(':',"宅配通:123456789");
$a[0]='宅配通',$a[1]='123456789'
//研判第一個字元是不是在A(ASCII值是65)到Z(95)之間,若是,那第一個字母就是大寫字元。
$str=str_replace("mrsoft","吉林省明日科技有限公司","Welcome to mrsoft!");
結果:Welcome to 吉林省明日科技有限公司
例子:將雙引號取代成 code
str_replace('\"', """,$content);
則要利用什麼方法,可以擷取出此文字:MyHttp.php
參考解:
$arr = explode('/',$_SERVER['PHP_SELF']);
$filename = $arr[count($arr)-1];
在CKEDITOR 中丟入從word復製的文字或表格,有太多的不必要的word的字元,我想要把那些字完踢掉:
找到一個東西叫preg_replace() 正規表示式取代字串
微軟字元都藏在 span 中,所以把 span全部抓掉
摘錄其中我用的一些功能,詳細功能,請上網找。
strpos
--- 找出字串第一次出現的位置語法 : int strpos (string haystack, string needle [, int offset])
substr
substr --- 取得部份字串
語法 : string substr (string string, int start [, int length])
explode ---將字串依指定的字串或字元separator切開
語法:array explode(string separator, string string,[int limit])
將字串 "宅配通:123456789" 套用explode,條件":"
$a=explode(':',"宅配通:123456789");
$a[0]='宅配通',$a[1]='123456789'
CODE:
例子:$ac=exam_560 $pos= strpos($ac,'_'); $id =substr($ac,0,$pos); $exam_name= substr($ac,$pos+1);針對字串第一個字是否為大寫!!ex:身分證 Q123584123
CODE:
$b=substr($a,0,1);取得第一個字//研判第一個字元是不是在A(ASCII值是65)到Z(95)之間,若是,那第一個字母就是大寫字元。
if ( ord($b) >= 65 AND ord($b) <= 95 ) {
echo "驗證合格!";
} else {
echo "第一個字元不是大寫字母!";
}
補充:ord a: 97 z:127 A: 65 Z: 95 str_replace
mixed str_Replace(mixed search, mixed replace,mixed subject , int &count)$str=str_replace("mrsoft","吉林省明日科技有限公司","Welcome to mrsoft!");
結果:Welcome to 吉林省明日科技有限公司
例子:將雙引號取代成 code
str_replace('\"', """,$content);
取得目前頁面的檔案名稱
echo basename(__FILE__);取得網址(URL中的檔案含副檔名)
例如網址是:http://127.0.0.1/myTest/MyHttp.php則要利用什麼方法,可以擷取出此文字:MyHttp.php
參考解:
$arr = explode('/',$_SERVER['PHP_SELF']);
$filename = $arr[count($arr)-1];
#當前運行腳本所在的文檔根目錄。在服務器配置文件中定義。
$_SERVER['DOCUMENT_ROOT'];去掉最後一個逗號/去尾巴
substr($str,0,strrpos($str,','))亂數
$a=rand(最小值[整數],最大值[整數])在CKEDITOR 中丟入從word復製的文字或表格,有太多的不必要的word的字元,我想要把那些字完踢掉:
找到一個東西叫preg_replace() 正規表示式取代字串
微軟字元都藏在 span 中,所以把 span全部抓掉
摘錄其中我用的一些功能,詳細功能,請上網找。
$body = preg_replace("/\/",'',$publications2);
濾掉
2012年6月4日 星期一
md5 加密 應用在會員密碼
系統管理工程人員 或者 掛載的公司的員工可以輕鬆看到用戶密碼,所以先將用戶密碼加密是必要。
PHP 內建了 MD5() 單向加密演算法,即只可加密,而不可以反向解密,但可以用猜的,只是難度很高。
md5 在class login 中會有錯誤。所以不能放。
PHP 內建了 MD5() 單向加密演算法,即只可加密,而不可以反向解密,但可以用猜的,只是難度很高。
比對資料
md5($password) 存到資料庫
$sql = mysql_query("select * from users where `username`='$username' and `password`='".md5($password)."'");
md5 在class login 中會有錯誤。所以不能放。
2012年2月15日 星期三
上傳圖片及PHP處理
處理端(接收來自form,並加以處理):
情境:多張圖片上傳
print_r($_FILES)
上傳多個標檔案--例子:
getimagesize
imagecreatefromgif
imagepng
情境:多張圖片上傳
//解晰圖片
$image_type=getimagesize($_FILES['x'.$im]['tmp_name']);
switch ($image_type[2]){
case "1"://gif
$src = imagecreatefromgif($_FILES['x'.$im]['tmp_name']);
break;
case "2": //jpg
$src = imagecreatefromjpeg($_FILES['x'.$im]['tmp_name']);
break;
case "3":
$src=imagecreatefrompng($_FILES['x'.$im]['tmp_name']);
break;
default:
echo '
ERROR!!請通知系統人員。
';
exit;
}
壓縮圖檔1:$file_name = $_FILES['image'.$im]['name'];
$src_w = imagesx($src);
$src_h = imagesy($src);
if($src_w > $src_h){
$thumb_w = 150;
$thumb_h = intval($src_h / $src_w * 150);
}else{
$thumb_h = 110;
$thumb_w = intval($src_w / $src_h * 110);
}
壓縮圖檔2:// 建立縮圖
$thumb = imagecreatetruecolor($thumb_w, $thumb_h);
// 開始縮圖
imagecopyresampled($thumb, $src, 0, 0, 0, 0, $thumb_w, $thumb_h, $src_w, $src_h);
// 假設要長寬不超過90
// 複製上傳圖片到指定 images 目錄
$number = strrpos($file_name,".");
$orig_name = substr($file_name,0,$number);
$sub_file_name = substr($file_name,$number+1);
$new_file_name = time()."_".$num.".".$sub_file_name;
$dest_filename = $upload_dir.$new_file_name;
$sql="插入db所需要的資料";
mysql_query($sql);
$r=mysql_affected_rows();
圖檔儲存在伺服器if($r>0) {
switch ($image_type[2]){
case "1"://gif
imagegif($thumb, 'path'.$dest_filename);
copy($_FILES['image'.$im]['tmp_name'], "../images/upload/" .$dest_filename);
break;
case "2": //jpg
imagejpeg($thumb, "path".$dest_filename);
copy($_FILES['image'.$im]['tmp_name'], "../images/upload/" .$dest_filename);
break;
case "3": //png
imagepng($thumb, "path".$dest_filename);
copy($_FILES['image'.$im]['tmp_name'], "../images/upload/" .$dest_filename);
break;
}
}
form 的元素: enctype='multipart/form-data'列出上傳的檔案資訊:
print_r($_FILES)
上傳多個標檔案--例子:
科目<input type='file' name='con_subject[]'><br>
科目<input type='file' name='con_subject[]'><br>
科目<input type='file' name='con_subject[]'><br>
接收端
第一個檔案: $_FILES['con_subject']['name'][0]
解釋:getimagesize
imagecreatefromgif
imagepng
2012年2月8日 星期三
檔案下載
使用的下載方式是跳出下載的方塊而不是瀏覽。
副程式:
2012.10.
下載檔名中有中文 產生亂碼,解法:
副程式:
//First, see if the file exists
if (!is_file($file)) { die("404 File not found!"); }
//Gather relevent info about file
$len = filesize($file);
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
/*
找了一下檔案下載的程式,在 EcStart 看到這個 Function,用它下載檔案的話,都會以
「下載」的方式呈現,而不是直接在瀏覽器開啟檔案。
http://my-web-design.blogspot.com/2010/08/php.html#links
*/
//This will set the Content-Type to the appropriate setting for the file
switch( $file_extension ) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
case "mp3": $ctype="audio/mpeg"; break;
case "wav": $ctype="audio/x-wav"; break;
case "mpeg":
case "mpg":
case "mpe": $ctype="video/mpeg"; break;
case "mov": $ctype="video/quicktime"; break;
case "avi": $ctype="video/x-msvideo"; break;
case "txt": $ctype="text/plain"; break;
//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
case "php":
case "htm":
case "html":die("Cannot be used for ". $file_extension ." files!"); break;
default: $ctype="application/force-download";
}
//Begin writing headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
//Use the switch-generated Content-Type
header("Content-Type: $ctype");
//Force the download
$header="Content-Disposition: attachment; filename=".$filename.";";
header($header );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$len);
@readfile($file);
exit;
2012.10.
下載檔名中有中文 產生亂碼,解法:
mb_convert_encoding($chineseFile,"BIG-5","UTF-8");您可能有興趣的書單:
2012年2月7日 星期二
PHP陣列
語法:array array(mixed...])
參數mixed的語法為"key=>value",多個參數mixed用逗號分開
如果省略了索引,會自動產生從0開始的整數索引
範例:
$array=array("ASP","PHP","JSP");
$rray[]="ASP",$rray[]="PHP",$rray[]="JSP"
$array3=array("a"=>"books","b"=>"apple","c"=>"orig")
array_search :在陣列中尋找指定的值, 傳回值true/false
語法:mixed array_search(mixed needle,array haystack[,bool strict])
搜尋陣列中是否有8這個數字。
array_search('8',$array);
1.explode():此函式可以將字串分割為陣列儲存,類似切token的方式,若以下列程式碼為例:
$student="kevin susan james";
$stuednt_array=explode(" ",$student);
foreach($stuednt_array as $index => $value)
echo "student $index is: $value\n";
則結果為:
student 0 is: kevin
student 1 is: susan
student 2 is: james
2.implode():此函式可以將陣列合併為字串儲存,若以下列程式碼為例:
$stuednt_array = array(kevin, susan, james);
$student = implode(",", $stuednt_array);
echo $student
把$_POST 的資料用成$key=>$value 的方式,不用在自己轉換成變數,減少很多麻煩。
$_POST = array_map('trim', $_POST);
foreach($_POST as $key => $value) {
${'post_' . $key} = mysql_real_escape_string($value);
}
輸出就是 $post_key的方式丟出來
參數mixed的語法為"key=>value",多個參數mixed用逗號分開
如果省略了索引,會自動產生從0開始的整數索引
範例:
$array=array("ASP","PHP","JSP");
$rray[]="ASP",$rray[]="PHP",$rray[]="JSP"
$array3=array("a"=>"books","b"=>"apple","c"=>"orig")
array_search :在陣列中尋找指定的值, 傳回值true/false
語法:mixed array_search(mixed needle,array haystack[,bool strict])
搜尋陣列中是否有8這個數字。
array_search('8',$array);
1.explode():此函式可以將字串分割為陣列儲存,類似切token的方式,若以下列程式碼為例:
$student="kevin susan james";
$stuednt_array=explode(" ",$student);
foreach($stuednt_array as $index => $value)
echo "student $index is: $value\n";
則結果為:
student 0 is: kevin
student 1 is: susan
student 2 is: james
2.implode():此函式可以將陣列合併為字串儲存,若以下列程式碼為例:
$stuednt_array = array(kevin, susan, james);
$student = implode(",", $stuednt_array);
echo $student
把$_POST 的資料用成$key=>$value 的方式,不用在自己轉換成變數,減少很多麻煩。
$_POST = array_map('trim', $_POST);
foreach($_POST as $key => $value) {
${'post_' . $key} = mysql_real_escape_string($value);
}
輸出就是 $post_key的方式丟出來
2012年2月3日 星期五
date 日期格式化
阿都仔的日期表示方式多以: 日/月/年
英文裡的數,可以分為「基數」(one、two、three)與「序數」(第一first、第二second、第三third)
日期表示:
MYSQL
取得現在時間---------------
select DATE_FORMAT(NOW(),'%H:%s, %D %b., %Y')==> 09:01, 2nd Feb., 2012
符合 rfc822
$date=gmdate("D, d M Y H:i:s", $this->unix);
DATE_FORMAT(time,'%a, %d %b %y %k:%i:%s +0000')
PHP
取得現在時間---------------
echo date("Y/m/d H:i",time()); //其結果為2010/03/24 14:32
echo date("H:i,jS D.,Y"); //結果:11:38,6th Mon.,2012
PHP:
d - 幾日,兩位數字,若不足二位則前面補零; 如: "01" 至 "31"
j - 幾日,兩位數字,若不足二位不補零; 如: "1" 至 "31"
D - 星期幾,三個英文字母; 如: "Fri"
l - 星期幾,英文全名; 如: "Friday"
F - 月份,英文全名; 如: "January"
Y - 年份,四位數字; 如: "1999"
y - 年份,二位數字; 如: "99"
h - 12 時制的小時; 如: "01" 至 "12"
H - 24 時制的小時; 如: "00" 至 "23"
g - 12 時制的小時,不足二位不補零; 如: "1" 至 12"
G - 24 時制的小時,不足二位不補零; 如: "0" 至 "23"
i - 分鐘; 如: "00" 至 "59"
m - 月份,兩位數字,若不足二位則在前面補零; 如: "01" 至 "12"
n - 月份,兩位數字,若不足二位則不補零; 如: "1" 至 "12"
M - 月份,三個英文字母; 如: "Jan"
s - 秒數; 如: "00" 至 "59"
S - 字尾加英文序數,二個英文字母; 如: "th","nd"
t - 指定月份的天數; 如: "28" 至 "31"
U - 總秒數
w - 數字型的星期幾,如: "0" (星期日) 至 "6" (星期六)
z - 一年中的第幾天; 如: "0" 至 "365"
date('U',time())
主要是將文字日期改為Unix時間戳記
date('U',time()); 獲得現在的秒數
mktime(hour,minute,second,month,day,year,is_dst)
範例:今天往後算一個月的日子
只有 小時與分鐘,所以mysql 的 unix_timestamp 不能用。
找出 開始與結束時間是否是一樣的
$ss_start=($_sHour * 60 + $_sMinute)*60; //秒
$ss_end=($_eHour * 60 + $_eMinute)*60; //秒
$sql="select * from `XXX` where TIME_TO_SEC( `start`)='$ss_start' and TIME_TO_SEC(`end`)='$ss_end' and auto='{$auto_id}'";
英文裡的數,可以分為「基數」(one、two、three)與「序數」(第一first、第二second、第三third)
日期表示:
- 1號、11號、21號、31號 英文 => 1st, 11st, 21st, 31st (數字後面加 st)
- 2號、12號、22號 英文 = 2nd, 12nd, 22nd (數字後面加 nd)
- 3號、13號、23號 英文 = 3rd, 13rd, 23rd (數字後面加 rd )
- 其他的後面(4~9)加 "th" 就符合規則了如=> 19th, 24th, 8th
MYSQL
取得現在時間---------------
select DATE_FORMAT(NOW(),'%H:%s, %D %b., %Y')==> 09:01, 2nd Feb., 2012
符合 rfc822
$date=gmdate("D, d M Y H:i:s", $this->unix);
DATE_FORMAT(time,'%a, %d %b %y %k:%i:%s +0000')
PHP
取得現在時間---------------
echo date("Y/m/d H:i",time()); //其結果為2010/03/24 14:32
echo date("H:i,jS D.,Y"); //結果:11:38,6th Mon.,2012
PHP:
d - 幾日,兩位數字,若不足二位則前面補零; 如: "01" 至 "31"
j - 幾日,兩位數字,若不足二位不補零; 如: "1" 至 "31"
D - 星期幾,三個英文字母; 如: "Fri"
l - 星期幾,英文全名; 如: "Friday"
F - 月份,英文全名; 如: "January"
Y - 年份,四位數字; 如: "1999"
y - 年份,二位數字; 如: "99"
h - 12 時制的小時; 如: "01" 至 "12"
H - 24 時制的小時; 如: "00" 至 "23"
g - 12 時制的小時,不足二位不補零; 如: "1" 至 12"
G - 24 時制的小時,不足二位不補零; 如: "0" 至 "23"
i - 分鐘; 如: "00" 至 "59"
m - 月份,兩位數字,若不足二位則在前面補零; 如: "01" 至 "12"
n - 月份,兩位數字,若不足二位則不補零; 如: "1" 至 "12"
M - 月份,三個英文字母; 如: "Jan"
s - 秒數; 如: "00" 至 "59"
S - 字尾加英文序數,二個英文字母; 如: "th","nd"
t - 指定月份的天數; 如: "28" 至 "31"
U - 總秒數
w - 數字型的星期幾,如: "0" (星期日) 至 "6" (星期六)
z - 一年中的第幾天; 如: "0" 至 "365"
date('U',time())
主要是將文字日期改為Unix時間戳記
$ThisDay = '2008-01-01';
$ThisDay = strtotime($ThisDay); // 將日期轉為Unix時間戳記
echo date("Y-m-d",strtotime("now",$ThisDay)). "\n";
//顯示2008-01-01
echo date("Y-m-d",strtotime("+1 day",$ThisDay)). "\n";
//顯示2008-01-02
echo date("Y-m-d",strtotime("+1 week",$ThisDay)). "\n";
//顯示2008-01-08
echo date("Y-m-d",strtotime("+1 week 2 days 4 hours 2 seconds",$ThisDay)). "\n";
//顯示2008-01-10
echo date("Y-m-d",strtotime("next Thursday",$ThisDay)). "\n";
//顯示2008-01-03
echo date("Y-m-d",strtotime("last Monday",$ThisDay)). "\n";
//顯示2007-12-31
以上範例會有1970的問題
使用 date_default_timezone_set('UTC'); 可以解決
日期:2012-01-13 00:56:35
date("Y-m-d 00:00:00",strtotime("-1 week")) //往前推七天 2012-01-06 00:00:00
date('U',time()); 獲得現在的秒數
mktime(hour,minute,second,month,day,year,is_dst)
範例:今天往後算一個月的日子
$years = date("Y");
$months = date("m");
$days = date("d");
$day = date("Y-m-d",mktime(0,0,0,$months+1,$days,$years));
只有 小時與分鐘,所以mysql 的 unix_timestamp 不能用。
找出 開始與結束時間是否是一樣的
$ss_start=($_sHour * 60 + $_sMinute)*60; //秒
$ss_end=($_eHour * 60 + $_eMinute)*60; //秒
$sql="select * from `XXX` where TIME_TO_SEC( `start`)='$ss_start' and TIME_TO_SEC(`end`)='$ss_end' and auto='{$auto_id}'";
2012年1月18日 星期三
PHP 補零
資料來源:http://blog.hsin.tw/2009/php-pad-a-string/
資料來源:http://boray06.blogspot.com/2011/06/php_27.html
資料來源:http://boray06.blogspot.com/2011/06/php_27.html
string str_pad ( string $input , int $pad_length [, string $pad_string= " " [, int $pad_type= STR_PAD_RIGHT ]] ) $input : 原字串 $pad_length : 補齊後的位數 $pad_string : 用來補齊的字串 $pad_type : 補齊的方式 有三種,STR_PAD_RIGHT (由右邊補)、STR_PAD_LEFT (由左邊補)、STR_PAD_BOTH (左右兩邊都補), 預設為STR_PAD_RIGHT $value = 7; //將數字由左邊補零至三位數 $value = str_pad($value,3,'0',STR_PAD_LEFT); echo $value; // 結果會印出 007;
2012年1月17日 星期二
preg_match 正規表示式比對
int preg_match ( string pattern, string subject [, array matches [, int flags]])
本函式以 pattern 的規則來剖析比對字串 subject。比對結果傳回的值放在陣列參數 matches 之中,matches[0]
內容就是原字串 subject、matches[1] 為第一個合乎規則的字串、matches[2] 就是第二個合乎規則的字串,餘類推。
若省略參數 matches,則只是單純地比對,找到則傳回值為 true。
本函式以 pattern 的規則來剖析比對字串 subject。比對結果傳回的值放在陣列參數 matches 之中,matches[0]
內容就是原字串 subject、matches[1] 為第一個合乎規則的字串、matches[2] 就是第二個合乎規則的字串,餘類推。
若省略參數 matches,則只是單純地比對,找到則傳回值為 true。
// the "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
認證IP是否正確
function validIP($ip){
return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
網站實例:
preg_match("/product[0-9]{4}.html/i",$_SERVER['REQUEST_URI']
參考regular expressions
訂閱:
文章 (Atom)