顯示具有 php 標籤的文章。 顯示所有文章
顯示具有 php 標籤的文章。 顯示所有文章

2023年8月20日 星期日

程式撰寫編碼,以可讀性為最高優先,一些較少用、非直觀的語法,盡量不要用,以PHP的 AND/&&、OR/|| 為例

PHP 的 邏輯運算元:AND/&&、OR/|| 這是常使用的運算元

而,AND 與 && 都是 AND 運算,有差別嗎?

有,其運算的優先次序不同。

&& 的運算次序高於 = , = 高於 AND

OR 一樣。

為了便於可讀性,我們建議一律使用可讀性高的表示法

如果有多個運算元在一起的運算式,就使用()來明確的表示優先次序,不要使用 && 這類不容易閱讀的運算元。


2022年6月2日 星期四

PHP 浮點運算產生的問題,需要注意

PHP的浮點加減乘除運算,會產生小數位以下與設計師預期不一樣的結果。

例如: 
$sell_price = 123.456; 
$buy_price = 123.455; 
$t_diff = $sell_price - $buy_price; 
 預期結果是: 0.001,結果出來的是:0.00000000000098! 

這是因為浮點運算的緣故。原因就不說了。直接看如何處理?! 

 1. 先個別 x 1000,相減,然後再除1000 

 2. php提供了高精度計算的函式庫,實際上就是為了解決這個浮點數計算問題而生的。 

 主要函式有: 
  •  bcadd — 將兩個高精度數字相加 
  •  bccomp — 比較兩個高精度數字,返回-1, 0, 1 
  •  bcdiv — 將兩個高精度數字相除 
  •  bcmod — 求高精度數字餘數 
  •  bcmul — 將兩個高精度數字相乘 
  •  bcpow — 求高精度數字乘方 
  •  bcpowmod — 求高精度數字乘方求模,數論裡非常常用 
  •  bcscale — 配置預設小數點位數,相當於就是Linux bc中的”scale=” 
  •  bcsqrt — 求高精度數字平方根 
  •  bcsub — 將兩個高精度數字相減

** 切記:永遠不要相信浮點運算會精準到小數點最後一位,也不要拿浮點運算的數字來做比較是否相等?!

2022年4月6日 星期三

希望 讓 CRON 要30秒執行一次

 CRON設定是最少一分鐘執行一次。

如果要小於60秒執行一次,就需要額外技巧:配合 sleep 30; 指令完成。

秒數必須是 60秒可以整除的,這樣才不會亂!例如:30秒、20秒、15秒、10秒等。

只要在 CRON 中這樣下:

* * * * <指令1>

* * * * sleep 30; <指令1>

這樣就可以一分鐘內,30秒自動執行一次。

如果是20秒,如下:

* * * * <指令1>

* * * * sleep 20; <指令1>

* * * * sleep 20; <指令1>

這樣就是一分鐘內,執行三次,每20秒一次。


2022年3月1日 星期二

ERROR: CONSTANT DS ALREADY DEFINED

Constant 重複定義了! 

找到這個指令:

define('DS', DIRECTORY_SEPARATOR);

修改成這樣就可以了:

if(!defined('DS')){ define('DS',DIRECTORY_SEPARATOR); }

2022年1月15日 星期六

在 Centos 上安裝 Ghostscript ,這是 使用 PDF要用到的。

GhostScript:

https://www.ghostscript.com/index.html

下載:

https://www.ghostscript.com/releases/gsdnld.html

安裝:

在SSH終端上:

cd /usr/src

wget https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/download/gs9550/ghostscript-9.55.0.tar.gz

tar -xzvf ghostscript-9.55.0.tar.gz

cd ghostscript-9.55.0

./configure 

make

make install


在 使用 Imagick,使用 PDF 轉換 JPG,一直發生 Internal Error 500

經查了很久,才知道,Server必須安裝 PHP Imagick 以外,還有 GhostScript,這是一個 PDF 要用的免費程式。

我的主機上沒有,所以必須安裝起來。





在 PDF Report 裡面的  PDF Layout Code下面增加產生  PDF,轉 JPG 的程式

因為,我們不知道 SC產生的 PDF 檔案名稱,只好自己用自訂的PDF檔名來產生

然後,再由自己產生的 PDF 產生 JPG

$t_pdf_file = $_SERVER['DOCUMENT_ROOT']."/_lib/tmp/id_".{pay_form_id}."_pay_form.pdf";

$t_jpg_file = $_SERVER['DOCUMENT_ROOT']."/_lib/tmp/id_".{pay_form_id}."_pay_form.jpg";

$pdf->output($t_pdf_file,"F");

$im = new Imagick();

$im->setResolution(150, 150);

$im->readImage( $t_pdf_file );

$im->writeImages( $t_jpg_file, false );




** 還有 /domains/<websitename>.com/public_html/_lib/prod/third/wkhtmltopdf/linux-amd64/wkhtmltopdf-amd64 權限要設成 "777"




2020年12月2日 星期三

php 使用 SQL 時,引號要避開,否則會出錯!mysqli_real_escape_string()

 

<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}

// Escape special characters, if any
$firstname = $mysqli -> real_escape_string($_POST['firstname']);
$lastname = $mysqli -> real_escape_string($_POST['lastname']);
$age = $mysqli -> real_escape_string($_POST['age']);

$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')";

if (!$mysqli -> query($sql)) {
  printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli -> close();
?>



像下面這個例子: $lastname 裡面的值有單引號。這樣進入 SQL 就會發生錯誤,應該要避開。

就使用這個函數:mysqli_real_escape_string(),就可以把單引號等避開了!


<?php

$lastname = "D'Ore";

$sql="INSERT INTO Persons (LastName) VALUES ('$lastname')";

// This query will fail, cause we didn't escape $lastname
if (!$mysqli -> query($sql)) {
  printf("%d Row inserted.\n", $mysqli->affected_rows);
}

?>


https://www.w3schools.com/php/func_mysqli_real_escape_string.asp

https://www.php.net/manual/en/mysqli.real-escape-string.php

2020年6月12日 星期五

php "@"意思

在函數的前面加了"@",這是抑制錯誤訊息顯示在螢幕上的意思。
不影響函數的執行,只是如果有錯誤訊息,不顯示出來!

據說最好不要用,因為錯誤你不知道,是否再導致其他錯誤,最後怎樣,很難掌控!
據網路上網友看到的建議,是盡量不要用!

2019年3月4日 星期一

php iif

The function iif does not exist in the standard PHP libraries.

But in most cases it is a 'short if expression' such as: (condition ? true : false).

2018年9月24日 星期一

2015年11月22日 星期日

將經營規則 business rule 寫在 mysql 中

資料庫系統,一定牽涉到資料庫本身,以及應用程式所處理的功能。
這些功能的規則,稱為 Business Rule. 有人翻譯為"商業規則",我認為這個翻譯不大妥當,應該為 "經營規則"。

這些經營規則,以前通常都是在 APP 應用程式中去設計執行,但如果有不同的程式給不同的人使用,而要遵守同一個 business rule ,那就變成必需在各個 AP 中個別去撰寫程式碼,這樣就會有不一致以及浪費時間的現象。

所以,關於這些資料的經營規則 business rule 最好是直接在  mysql 中執行即可,以方便保持資料的一致性,規則的一致性。

使用 mysql 的 STORED ROUTINE(Procedure/Function)及 Trigger Routine 以及Table 間的Foreign Key 規則、Index 唯一或可重複等工具,即可以達到一定的一致性規則。

而畫面的新增/更改/刪除/查詢,則可以很簡單的運用如 Scriptcase 等畫面產生器,就可以輕鬆的完成輸出入界面。


某些技巧:

如果有些程式碼是在特定的情況下才需要被執行,可以設計一個欄位值來控制他。
例如:field: execute_it char(1), Default:"0"
在 update_trigger中的程式可以寫:

IF NEW.execute_it = "1" THEN
    -- Execute some code...
    SET NEW.execute_it = "0";
ELSE
    -- Execute the other code......
END IF;

記得最後必須將 execute_it 的值設回來"0"
    SET NEW.execute_it = "0";



2014年8月15日 星期五

php 讀取檔案副檔名的方法

php 讀取檔案副檔名的方法,有以下六個:


$filename = 'mypic.gif';

// 1. The "explode/end" approach
$ext = end(explode('.', $filename));

// 2. The "strrchr" approach
$ext = substr(strrchr($filename, '.'), 1);

// 3. The "strrpos" approach
$ext = substr($filename, strrpos($filename, '.') + 1);

// 4. The "preg_replace" approach
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

// 5. The "never use this" approach
//   From: http://php.about.com/od/finishedphp1/qt/file_ext_PHP.htm
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];

//6.
$filename = 'mypic.gif';
$ext = pathinfo($filename, PATHINFO_EXTENSION);
註: pathinfo(),取得副檔名應該沒有問題,因為副檔名都是英文的,若是讀中文檔名可能會有問題。










2014年8月14日 星期四

php 的檔案處理系統

php 的檔案處理系統


執行階段的設定

php的檔案處理函數皆會受到 php.ini 裡面的設定選項影響。所以,要先了解有哪些設定:

NameDefaultDescriptionChangeable
allow_url_fopen"1"Allows fopen()-type functions to work with URLs (available since PHP 4.0.4)PHP_INI_SYSTEM
user_agentNULLDefines the user agent for PHP to send (available since PHP 4.3)PHP_INI_ALL
default_socket_timeout"60"Sets the default timeout, in seconds, for socket based streams (available since PHP 4.3)PHP_INI_ALL
from""Defines the anonymous FTP password (your email address)PHP_INI_ALL
auto_detect_line_endings"0"When set to "1", PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Mac line-ending characters (available since PHP 4.3)PHP_INI_ALL


路徑 "/" "\"  的相容性 Unix / Windows Compatibility

Unix的路徑使用 (/),而Windows則是(/)(\)  都可以。

PHP 5  的檔案系統函數


函數 Function敘述 
basename()傳回一個路徑的 檔案名稱 部分
chgrp()改變檔案所屬的 群組 group
chmod()改變檔案 模式 mode
chown()改變檔案擁有者 file owner
clearstatcache()清除檔案狀態快取 file status cache
copy()複製一個檔案
delete()請閱  unlink() 或 unset()
dirname()傳回一個路徑的目錄部分
Returns the directory name component of a path
disk_free_space()傳回一個目錄的自由可用空間
Returns the free space of a directory
disk_total_space()傳回一目錄的總共空間
Returns the total size of a directory
diskfreespace()跟 disk_free_space() 一樣的。別名而已。
fclose()關閉一個開啟的檔案
feof()測試一個開啟檔案的 end-of-file
fflush()Flushes buffered output to an open file
fgetc()傳回開啟檔案的一個字元
Returns a character from an open file
fgetcsv()傳回開啟檔案的一行,CSV格式
Parses a line from an open file, checking for CSV fields
fgets()傳回開啟檔案的一行
Returns a line from an open file
fgetss()傳回開啟檔案的一行,移除HTML, PHP的標籤
Returns a line, with HTML and PHP tags removed, from an open file
file()讀取檔案到一個陣列中
Reads a file into an array
file_exists()檢查檔案或目錄是否存在
Checks whether or not a file or directory exists
file_get_contents()讀取檔案進入一個字串變數
Reads a file into a string
file_put_contents()將一個字串變數寫入檔案
Writes a string to a file
fileatime()傳回檔案最後一次存取的時間
Returns the last access time of a file
filectime()傳回檔案最後一次改變的時間
Returns the last change time of a file
filegroup()傳回檔案的 群組 ID
Returns the group ID of a file
fileinode()傳回檔案的 inode 號碼
Returns the inode number of a file
filemtime()傳回檔案最後修改的時間
Returns the last modification time of a file
fileowner()傳回檔案擁有者的 user ID
Returns the user ID (owner) of a file
fileperms()傳回檔案的權限資料
Returns the permissions of a file
filesize()傳回檔案大小
Returns the file size
filetype()傳回檔案格式
Returns the file type
flock()鎖定或釋放檔案
Locks or releases a file
fnmatch()比對 檔案名稱或字串
Matches a filename or string against a specified pattern
fopen()開啟檔案
Opens a file or URL
fpassthru()讀取一個開啟的檔案,直到EOF,然後將結果寫到output buffer
Reads from an open file, until EOF, and writes the result to the output buffer
fputcsv()將一行格式成CSV,然後寫到開啟的檔案
Formats a line as CSV and writes it to an open file
fputs()跟 fwrite()一樣
Alias of fwrite()
fread()從開啟的檔案讀取
Reads from an open file
fscanf()Parses input from an open file according to a specified format
fseek()Seeks in an open file
fstat()Returns information about an open file
ftell()Returns the current position in an open file
ftruncate()Truncates an open file to a specified length
fwrite()Writes to an open file
glob()Returns an array of filenames / directories matching a specified pattern
is_dir()Checks whether a file is a directory
is_executable()Checks whether a file is executable
is_file()Checks whether a file is a regular file
is_link()Checks whether a file is a link
is_readable()Checks whether a file is readable
is_uploaded_file()Checks whether a file was uploaded via HTTP POST
is_writable()Checks whether a file is writeable
is_writeable()Alias of is_writable()
lchgrp()Changes group ownership of symlink
lchown()Changes user ownership of symlink
link()Creates a hard link
linkinfo()Returns information about a hard link
lstat()Returns information about a file or symbolic link
mkdir()Creates a directory
move_uploaded_file()Moves an uploaded file to a new location
parse_ini_file()Parses a configuration file
parse_ini_string()Parses a configuration string
pathinfo()Returns information about a file path
pclose()Closes a pipe opened by popen()
popen()Opens a pipe
readfile()Reads a file and writes it to the output buffer
readlink()Returns the target of a symbolic link
realpath()Returns the absolute pathname
realpath_cache_get()Returns realpath cache entries
realpath_cache_size()Returns realpath cache size
rename()Renames a file or directory
rewind()Rewinds a file pointer
rmdir()Removes an empty directory
set_file_buffer()Sets the buffer size of an open file
stat()Returns information about a file
symlink()Creates a symbolic link
tempnam()Creates a unique temporary file
tmpfile()Creates a unique temporary file
touch()Sets access and modification time of a file
umask()Changes file permissions for files
unlink()Deletes a file




完整的刪除一個目錄:

function delTree($dir) {  
  1.     $files = glob$dir . '*', GLOB_MARK );  
  2.     foreach$files as $file ){  
  3.         ifsubstr$file, -1 ) == '/' )  
  4.             delTree( $file );  
  5.         else  
  6.             unlink( $file );  
  7.     }   
  8.   
  9.     if (is_dir($dir)) rmdir$dir );   
  10.   
  11. }  

2014年8月12日 星期二

php 的 ternary operator: ? :

ternary operator 三元操作元

語法:(expr1) ? (expr2) : (expr3)

意思是:  如果 (expr1) 為 true  ,則傳回 (expr2),否則傳回(expr3)

例如:

$opening_time = ($day == "WEEKEND") ? 12 : 9;

相當於:

if ($day == "WEEKEND")
    $opening_time = 12;
else
    $opening_time = 9;


php regular expression

http://www.regular-expressions.info/php.html

http://www.rexegg.com/regex-php.html

http://webcheatsheet.com/php/regular_expressions.php





PHP正則表達式-使用preg_match()過濾字串

在網頁程式撰寫的時候,經常需要把使用者輸入的字串做過濾
但有些時候並非惡意攻擊字串
可能使用者只是輸入錯誤
因此我們需要做一些基本的檢查來預防和提式
下面是使用 preg_match() 這個函數來檢查字串的方式

首先先簡單介紹一下 preg_match() 這個函數的用法

    preg_match( 正則表達式 , 要比對的字串 , 比對結果)

其中比對結果是一個陣列,其中陣列結果是 $result[0]=原字串、$result[1]=第一個符合規則的字串、$result[2]=第二個符合規則的字串...以此類推

比對結果則回傳 1(正確) 或是 0(錯誤)

下面是一個簡單的範例

        if(preg_match($regex, $resource , $result)) {

            echo "OK";

        } else {

            echo "error";

        }


另外附上幾個常用的表達式

       //A. 檢查是不是數字

       $standard_A = "/^([0-9]+)$/";

       //B. 檢查是不是小寫英文

       $standard_B = "/^([a-z]+)$/";

       //C. 檢查是不是大寫英文

       $standard_C = "/^([A-Z]+)$/";

       //D. 檢查是不是全為英文字串

       $standard_D = "/^([A-Za-z]+)$/";

       //E. 檢查是不是英數混和字串

       $standard_E = "/^([0-9A-Za-z]+)$/";

       //F. 檢查是不是中文

       $standard_F = "/^([\x7f-\xff]+)$/";

       //G. 檢查是不是電子信箱格式

       //$standard_G_1 這組正則允許 "stanley.543-ok@myweb.com"

       //但 $standard_G_2 僅允許 "stanley543ok@myweb.com" ,字串內不包含 .(點)和 -(中線)

       $standard_G_1 = "/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/";

       $standard_G_2 = "/^[\w]*@[\w-]+(\.[\w-]+)+$/" ;

       //下面則是個簡單的範例,大家可以嘗試看看



       $string = "stanley.543-ok@myweb.com" ;

       $standard_G_1 = "/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/";

       $standard_G_2 = "/^[\w]*@[\w-]+(\.[\w-]+)+$/" ;

       function checkString($strings, $standard){

           if(preg_match($standard, $strings, $hereArray)) {

              return 1;

           } else {

              return 0;

           }

       }

       echo checkString($string, $standard_G_1);

       echo "<br>";

       echo checkString($string, $standard_G_2);







preg_match 進行正則表示式比對資料


int preg_match ( string pattern, string subject [, array matches [, int flags]] )

程式會在 string subject 中進行比對是否有符合 string pattern 條件的結果

很多人剛開始使用 preg_match 都蠻不了解其正規的用法,其實就算不完全了解正規的用法也是可以了解 preg_match 初階的使用方式,基本觀念就是給一個字串讓 preg_match 去幫你比對出符合條件的部分,透過幾個範例應該就能上手。

範例一、用 preg_match 單純的找出是否符合條件

if (preg_match("/1/i", "12345")) {
    echo "條件符合";
} else {
    echo "條件不符合";
}

這個範例會顯示條件符合。其中 i 表示不區分大小寫。

範例二、用 preg_match 找出完全符合的字母

if (preg_match("/\bdef\b/i", "abcdefg")) {
 echo "條件符合";
} else {
 echo "條件不符合";
}

這個範例會顯示條件不符合。其中 \b 所代表的意思是完全符合才算數,也就是說字串 abcdefg 中必須要有獨立的 def 才算符合,以目前狀況來說 abcdefg 全部黏在一起,所以並不符合,我們可以做個修改

if (preg_match("/\bdef\b/i", "abc def g")) {
 echo "條件符合";
} else {
 echo "條件不符合";
}

這樣子就會輸出條件符合囉!

範例三、用 preg_match 找出網址的部分

preg_match('@^(?:http://)?([^/]+)@i',"http://www.webtech.tw", $matches);
$host = $matches[1].'';
echo   $host;

這樣會輸出 www.webtech.tw,preg_match 先比對條件符合的結果,再把他放到 matches 陣列中,如果你輸出 matches 陣列會看到這樣

Array ( [0] => http://www.webtech.tw [1] => www.webtech.tw ) 

接著我們再利用 preg_match 去取得 webtech.tw 這樣的結果

preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo $matches[0];

這樣就順利找到咱們的 domain name 囉!








php 檔案下載





【PHP】下載檔案但不直接開啟
多數人在下載檔案的頁面直接連結該檔案, 如下寫法 ----

a href="檔名.副檔名"

這在 windows 系統會有一個可能的狀況, 當此類型檔案與 windows 預設開啟功能產生關聯時(通常是以副檔名為判斷依據), 一點擊這個下載連結時, windows 就會自動啟動此類型檔案的程式並開啟此檔案, 例如:

下載的檔案為 demo.txt, 而 .txt 檔在 windows 預設的開啟程式為記事本, 所以一點擊此連結, windows 便會啟動記事本並開啟 demo.txt, 但實際上我們所希望的是真正的下載 demo.txt 並儲存在硬碟內.

要達到此目的, 我們需要另一個專門下載檔案的 PHP 小程式, 假設我們將這個小程式命名為 downloadfile.php, 其程式內容如下 ----

if(isset($_GET['file']))
{
    // $_GET['file'] 即為傳入要下載檔名的引數
    header("Content-type:application");
    header("Content-Length: " .(string)(filesize($_GET['file'])));
    header("Content-Disposition: attachment; filename=".$_GET['file']);
    readfile($_GET['file']);
}

另外, 改寫原下載頁面的 html 語法 ----

a href="downloadfile.php?file=檔名.副檔名"


PHP檔案下載

下載的檔案與實際的檔案不同:

<?php

include("auth1.php"); //可不加上此行

header("Content-type: text/html; charset=utf-8");

$file="./9707.zip"; // 實際檔案的路徑+檔名

$filename="0714.zip"; // 下載的檔名

//指定類型

header("Content-type: ".filetype("$file"));

//指定下載時的檔名

header("Content-Disposition: attachment; filename=".$filename."");

//輸出下載的內容。

readfile($file);

?>

開啟網頁前的認證(auth1.php ):

<? header("Content-type: text/html; charset=utf-8");

if (empty($_SERVER['PHP_AUTH_USER'])) {

header('WWW-Authenticate: Basic realm="Please input"');

header('HTTP/1.0 401 Unauthorized');

echo '請輸入正確的帳號及密碼, 不可以取消!';

exit;

} else {

$correctName="pcschool";

$correctpwd="mysql" ;

if (($_SERVER['PHP_AUTH_USER'] != $correctName) or

($_SERVER['PHP_AUTH_PW'] !=$correctpwd)){

echo "登入失敗,請開啟新的瀏覽器重新登入";

}

}

?>


Read more: http://jiannrong.blogspot.com/2009/08/php.html#ixzz3ACCzhUCJ













PHP 檔案下載 header 設置

用以下的方式,可以讓大部份瀏覽器 (主要是 IE) 詢問你是否要下載檔案 (而不是直接開啟) 。

<?php
$file_name = "file.name";
$file_path = "/path/to/realfile";
$file_size = filesize($file_path);
header('Pragma: public');
header('Expires: 0');
header('Last-Modified: ' . gmdate('D, d M Y H:i ') . ' GMT');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: application/octet-stream');
header('Content-Length: ' . $file_size);
header('Content-Disposition: attachment; filename="' . $file_name . '";');
header('Content-Transfer-Encoding: binary');
readfile($file_path);
?>

補充:
•$file_name: 這是給瀏覽器看的檔案名稱,也就是下載視窗會出現的那個檔名;它可以跟實際檔案的名稱不一樣!
•$file_path: 會連到實際檔案的位置,也就是該檔案在伺服器上的真實路徑。
•$file_size: 檔案的大小。
•若php.ini 的 memory_limit 設的太小,會造成網頁一直在讀取, 不會跳出下載視窗的問題。









部分代碼如下
$filename="test.pdf";
$file = dirname(__FILE__)."/upload_file/".$file_name ;//注1
if(file_exists($file)){//注2
header("Expires: 0");
header("Pragma: no-cache");//注3
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-disposition: attachment; filename=' . basename($file)); //注4
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($file));
@readfile($filename);
   exit(0);
}
解釋一下上面作注的地方
注1:$file = dirname(__FILE__)."/upload_file/".$file_name ;
    指定要下載檔案(假設要下載的檔所在資料夾與當前檔所在的資料夾的處在同一級)
注2:if(file_exists($file) 判斷指定檔是否存在。
注3:header("Pragma: no-cache");
   這裡若是伺服器便用了SSL,即通過HTTPs來訪問的話。要將no-cache改成private
   即header("Pragma: private");
注4: header('Content-disposition: attachment; filename=' . basename($filename));
   basename($filename) 取出檔案名
   Content-disposition: attachment;點下載後出現下載對話方塊。若不需要出現下載對話方塊直接打開的話,將 
   attachment改成in-line 即:Content-disposition: in-line;


注意點:要確認一下php.ini中的output_buffering的設定,如果是output_buffering = Off的話,將它修改成如下
    output_buffering = 4096
    ;output_buffering = Off







[PHP 檔案下載]

參考網址   http://blog.roodo.com/jaceju/archives/805389.html

用以下的方式,可以讓大部份瀏覽器 (主要是 IE) 詢問你是否要下載檔案 (而不是直接開啟) 。

 $file_name = "file.name";
 $file_path = "/path/to/realfile";
 $file_size = filesize($file_path);
 header('Pragma: public');
 header('Expires: 0');
 header('Last-Modified: ' . gmdate('D, d M Y H:i ') . ' GMT');
 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
 header('Cache-Control: private', false);
 header('Content-Type: application/octet-stream');
 header('Content-Length: ' . $file_size);
 header('Content-Disposition: attachment; filename="' . $file_name . '";');
 header('Content-Transfer-Encoding: binary');
 readfile($file_path);
?>

[PHP 讀大檔]

$fp = fopen("sn.txt", "r");
while (!feof($fp)) {
   $content. = fgets($fp);
}

[php寫入成 excel檔, 並可從網頁下載]

  header("Content-Disposition:filename=myfile.xls");
 header("Content-type:application/vnd.ms-excel");
 $content = "a \t b\t c\t d\n";
 $content .= "e \t f\t g\t h\n";
 echo $content;
?>

如何判斷現在FORM是在 insert mode? 還是 update mode?

只要用  if (empty({primary_key})) 就可以知道是否為新增模式了。 如果 {promary_key} 是空白的,那麼就是在新增模式;反之,就是更新模式。 以上。