Troubleshooting of PHP errors: Difference between revisions

Tag: wikieditor
 
(33 intermediate revisions by the same user not shown)
Line 1: Line 1:
PHP 問題的排除與解決
PHP 技術問題的排除與解決
 
This article categorizes various PHP issues into four main types:
 
# '''File and Directory Issues''': These involve problems related to file handling and directory operations in PHP, such as file not found errors or issues with file permissions.
# '''Configuration and Environment Issues''': This category covers issues arising from misconfigurations or environmental factors, including PHP settings, memory limits, and server configurations.
# '''Error Handling and Debugging''': These issues pertain to errors and debugging challenges, such as syntax errors, runtime errors, and debugging messages.
# '''General PHP Practices''': This encompasses best practices and general usage of PHP, including coding standards, command-line usage, and avoiding common pitfalls.
 
== Troubleshooting steps of PHP errors ==
Display error message or check the PHP error logs
* {{kbd | key=<nowiki>ini_set("display_errors", "On");</nowiki>}} See details on [http://php.net/manual/en/errorfunc.configuration.php PHP: Runtime Configuration - Manual]
* {{kbd | key=<nowiki>error_reporting(E_ALL);</nowiki>}} See details on [http://php.net/manual/en/function.error-reporting.php PHP: error_reporting - Manual]
* [https://www.jetbrains.com/help/phpstorm/event-log-tool-window.html Event Log - Help | PhpStorm]
 
Check the Web service logs
# {{kbd | key=<nowiki>sudo tail /var/log/httpd/error.log</nowiki>}} if the web service logs was located at {{kbd | key=<nowiki>/var/log/httpd/error.log</nowiki>}}
# Example log: {{kbd | key=<nowiki>[Thu Nov 08 12:20:40.412630 2018] [:error] [pid 12769] [client x.x.x.x:4433] PHP Parse error:  syntax error, unexpected '$var' (T_VARIABLE) in /home/wwwroot/path/to/file.php on line 100</nowiki>}}
# Display partial source code: {{kbd | key=<nowiki>sed -n '990,110p;111q' /home/wwwroot/path/to/file.php</nowiki>}}<ref>[https://stackoverflow.com/questions/83329/how-can-i-extract-a-predetermined-range-of-lines-from-a-text-file-on-unix How can I extract a predetermined range of lines from a text file on Unix? - Stack Overflow]</ref>
# 檢查網站伺服器 error log e.g. 如果使用 [https://www.nginx.com/ NGINX] Web Server 可輸入指令 {{kbd | key=<nowiki>sudo tail /var/log/nginx/error.log</nowiki>}}
 
Simply the question
* Is the [http://php.net/manual/en/function.function-exists.php function_exists]?
** Extension dependency? Install the extension you need.
** If not, looking for the alternative functions.
* Was the function really executed? Maybe using the __LINE__ to examin the logic.
* Disable the logical judgement and just print text using [http://php.net/manual/en/function.var-dump.php var_dump] or [http://php.net/manual/en/function.print-r.php print_r] functions.
* Check the if-else condition was satisfied or not cf: [http://www.leepoint.net/notes-java/data/strings/12stringcomparison.html Java: String Comparison] It's logical (compiler will not show the warning) but wrong.
* try & catch: [http://php.net/manual/en/language.exceptions.php PHP: Exceptions]
 
=== logging ===
native error logging
* [http://www.php.net/ PHP] log: check the configuration file: /etc/php.ini (the location of configuration file can be verified by [http://php.net/manual/en/function.phpinfo.php phpinfo()] )
(for production site) unmark theese lines in the php.ini and restart Apache service
<pre>
log_errors = On
error_log = "php_error.log"
</pre>
(for development site) using [http://php.net/manual/en/function.error-reporting.php error_reporting]
<pre>
error_reporting(E_ALL);
</pre>
 
[http://tw1.php.net/print_r PHP: print_r - Manual]
<pre>
$log = print_r($variable, true);
//save to the log file
 
$log = print_r(debug_backtrace(), true);
//Generates a backtrace and save to the log file
</pre>
 
capture the result of var_dump:
ob_start
* [http://stackoverflow.com/questions/139474/how-can-i-capture-the-result-of-var-dump-to-a-string php - How can I capture the result of var_dump to a string? - Stack Overflow]
* [http://php.net/manual/en/function.error-log.php PHP: error_log - Manual]
<pre>
ob_start();
var_dump($some_variable);
$result = ob_get_clean();
error_log($result, 3, 'd:/result.log');
</pre>
 
QuickForm
<pre>
$result = var_dump($some_variable);
$form->addElement('html', $result);
</pre>
 
 
[http://ellislab.com/codeigniter CodeIgniter]: [http://stackoverflow.com/questions/7370391/how-to-configure-codeigniter-to-report-all-errors php - How to configure Codeigniter to report all errors? - Stack Overflow]
 
 
show the line number and filename
<pre>
echo 'Houston, we've had a problem '. __line__ . ' ' . __FILE__ ."<br />";
</pre>
more on [http://php.net/manual/en/language.constants.predefined.php PHP: Magic constants], [https://github.com/Seldaek/monolog monolog]
 
== File and Directory Issues ==


== PHP 技術問題處理 ==
=== 檔案操作有關 ===
=== 檔案操作有關 ===
可否讀取或寫入:例如 imagejpeg($canvas, $filename, 100); 沒有顯示錯誤訊息,則需要
可否讀取或寫入:例如 imagejpeg($canvas, $filename, 100); 沒有顯示錯誤訊息,則需要
Line 19: Line 97:
* 驗證是否具備寫入權限:  
* 驗證是否具備寫入權限:  
*# 輸入 {{Linux}} 指令 (1) 檢查檔案權限 {{kbd | key = ls -Z /path/to/file}}、(2) 檢查目錄權限 {{kbd | key = ls -Zd /path/to/directory/}}
*# 輸入 {{Linux}} 指令 (1) 檢查檔案權限 {{kbd | key = ls -Z /path/to/file}}、(2) 檢查目錄權限 {{kbd | key = ls -Zd /path/to/directory/}}
*# PHP [https://www.php.net/manual/en/function.get-current-user.php get_current_user] function
*# PHP [http://php.net/manual/en/function.is-writable.php is_writable function]
*# PHP [http://php.net/manual/en/function.is-writable.php is_writable function]


=== 錯誤訊息: no such file or directory 找不到 PHP 路徑 ===
<pre>
% php -v
zsh: no such file or directory: /Applications/MAMP/bin/php/php7.4.21/bin/php
</pre>
解決方法:找到 PHP 檔案路徑
* [[XAMPP]] on {{Mac}} {{kbd | key=<nowiki>/Applications/xampp/bin/php</nowiki>}}
* MAMP PRO on on {{Mac}} input the command ls {{kbd | key=<nowiki>/Applications/MAMP/bin/php/php*/bin/php</nowiki>}} to find the suitable version you want e.g. {{kbd | key=<nowiki>/Applications/MAMP/bin/php/php8.1.13/bin/php</nowiki>}}
If you are using zsh. Input the command {{kbd | key=<nowiki>vi ~/.zshrc</nowiki>}} to edit the file<ref>[https://castion2293.medium.com/mac%E4%B8%AD%E5%8D%87%E7%B4%9Aphp%E7%89%88%E6%9C%AC%E4%B8%A6%E8%A8%AD%E7%82%BA%E9%A0%90%E8%A8%AD-d7e6fdad9cc2 Mac中升級php版本並設為預設. 確認目前PHP的版本 | by Nick Zhang | Medium]</ref>
原檔案內容
<pre>
alias php='/Applications/MAMP/bin/php/php7.4.21/bin/php'
</pre>
修改後檔案內容
<pre>
alias php='/Applications/MAMP/bin/php/php8.1.13/bin/php'
</pre>
And then relaunch the shell
=== PHPExcel 產生的 Excel 檔案,開啟後看到一堆亂碼 ===
狀況1: 開啟 Excel 檔案,看到最前面有 {{kbd | key=<nowiki>NOTICE</nowiki>}} 的錯誤訊息,例如 {{kbd | key=<nowiki><b>Notice</b>:  Constant CONST_XXX already defined in <b>path\to\script.php</b> on line xx</nowiki>}}
* 解法: 關閉錯誤訊息輸出 ex: [http://www.php.net/manual/en/function.error-reporting.php error_reporting(0);] 以及修正 NOTICE 訊息指涉的問題,例如例子中常數重複宣告的問題。
狀況2: 開啟 Excel 檔案,看到最前面有 {{kbd | key=<nowiki>Fatal error</nowiki>}} 之類的錯誤訊息
* 解法: 關閉錯誤訊息輸出 ex: [http://www.php.net/manual/en/function.error-reporting.php error_reporting(0);] ,以及修正 Fatal error 訊息指涉的問題。
狀況3: 開啟 Excel 檔案,看到有儲存格位址之類的錯誤訊息
* 解法: 該儲存格內容以等號 (=) 開始,卻不是函數。解決方式是將儲存格內容的最前面加一個單引號 (') 或者是加個空白。
== Configuration and Environment Issues ==
=== 不知道網站伺服器載入哪一個 php.ini 設定檔 ===
=== 不知道網站伺服器載入哪一個 php.ini 設定檔 ===
使用 console command<ref>[http://php.net/manual/en/features.commandline.options.php PHP: Options - Manual]</ref>
使用 console command<ref>[http://php.net/manual/en/features.commandline.options.php PHP: Options - Manual]</ref>
* 輸入命令 {{kbd | key = <nowiki>php --ini</nowiki>}}
* 輸入命令 {{kbd | key = <nowiki>php --ini</nowiki>}} 或 {{kbd | key = <nowiki>/path/to/php --ini</nowiki>}}
<pre>
<pre>
> php --ini
> php --ini
Line 33: Line 148:


* 使用 [http://php.net/manual/en/function.phpinfo.php phpinfo]  確認「Configuration File」<ref>[http://www.commandlinefu.com/commands/view/818/phpinfo-from-the-command-line phpinfo from the command line | commandlinefu.com]</ref>: {{kbd | key = <nowiki>echo "<?php phpinfo(); ?>" | php | grep "Configuration File"</nowiki>}}
* 使用 [http://php.net/manual/en/function.phpinfo.php phpinfo]  確認「Configuration File」<ref>[http://www.commandlinefu.com/commands/view/818/phpinfo-from-the-command-line phpinfo from the command line | commandlinefu.com]</ref>: {{kbd | key = <nowiki>echo "<?php phpinfo(); ?>" | php | grep "Configuration File"</nowiki>}}
** 指定完整 php 路徑 command: {{kbd | key = <nowiki>echo "<?php phpinfo(); ?>" | /Applications/XAMPP/bin/php | grep "Configuration File"</nowiki>}}
** 指定完整 php 路徑 command:  
*** {{kbd | key = <nowiki>/Applications/XAMPP/bin/php -r 'echo phpinfo();' | grep "Configuration File"</nowiki>}}
*** 或 {{kbd | key = <nowiki>echo "<?php phpinfo(); ?>" | /Applications/XAMPP/bin/php | grep "Configuration File"</nowiki>}}
* {{kbd | key = <nowiki>php -i | grep "Configuration File"</nowiki>}}
* {{kbd | key = <nowiki>php -i | grep "Configuration File"</nowiki>}}


Line 51: Line 168:
** 法2: 不啟用 short_open_tag,將多個 PHP 檔案的 {{kbd | key=<nowiki><? </nowiki>}} 改成 {{kbd | key=<nowiki><?php </nowiki>}}。 (1) 使用支援 [[Regular expression]] 的文字編輯軟體、(2) 搜尋 {{kbd | key=<nowiki><\?\s</nowiki>}} 取代為 {{kbd | key=<nowiki><\?php </nowiki>}} 。請注意取代部分結尾有一個空白。詳見 [[Batch remove PHP short tags]]
** 法2: 不啟用 short_open_tag,將多個 PHP 檔案的 {{kbd | key=<nowiki><? </nowiki>}} 改成 {{kbd | key=<nowiki><?php </nowiki>}}。 (1) 使用支援 [[Regular expression]] 的文字編輯軟體、(2) 搜尋 {{kbd | key=<nowiki><\?\s</nowiki>}} 取代為 {{kbd | key=<nowiki><\?php </nowiki>}} 。請注意取代部分結尾有一個空白。詳見 [[Batch remove PHP short tags]]


=== 錯誤訊息: ERROR: 00000:: ===
=== curl error 7 while downloading https://packagist.tw/ ... ===
* 原因: 想要刪除的資料不在 MySQL 資料庫內,進行刪除時,會發生的錯誤。
Error condition
* 解決方法: 先檢查該資料是否存在,再進行刪除。
<pre>
composer.phar update                             
Loading composer repositories with package information                                                      https://packagist.tw could not be fully loaded (curl error 7 while downloading https://packagist.tw/packages.json: Failed to connect to packagist.tw port 443: Connection refused), package information was loaded from the local cache and may be out of date
 
In CurlDownloader.php line 372:
                                                                                                                                                               
  curl error 7 while downloading https://packagist.tw/p/zircote/xxx.json: Failed to 
  connect to packagist.tw port 443: Connection refused         
</pre>
 
Solution
* The mirror I was using encountered a network error.
* Switch to a different mirror by entering the following command: {{kdb | key=<nowiki>composer config repos.packagist composer https://packagist.org</nowiki>}}


=== 錯誤訊息: phpinfo() has been disabled ===
=== 錯誤訊息: phpinfo() has been disabled ===
Line 66: Line 195:
** | 管線命令 (pipe),詳 [http://linux.vbird.org/linux_basic/0320bash.php#pipe 鳥哥的 Linux 私房菜 -- 學習 bash shell]
** | 管線命令 (pipe),詳 [http://linux.vbird.org/linux_basic/0320bash.php#pipe 鳥哥的 Linux 私房菜 -- 學習 bash shell]
** {{kbd | key = <nowiki>grep -i</nowiki>}} 變數 -i 代表忽略搜尋關鍵字或搜尋條件 (pattern) 的大小寫
** {{kbd | key = <nowiki>grep -i</nowiki>}} 變數 -i 代表忽略搜尋關鍵字或搜尋條件 (pattern) 的大小寫
* {{kbd | key = <nowiki>/path/to/bin/php -m</nowiki>}} 列出載入的模組<ref>[http://php.net/manual/en/function.extension-loaded.php PHP: extension_loaded - Manual]</ref>
* {{kbd | key = <nowiki>/path/to/bin/php -m</nowiki>}} 列出載入的模組名稱 (無版本資訊)<ref>[http://php.net/manual/en/function.extension-loaded.php PHP: extension_loaded - Manual]</ref>
 
 
=== 錯誤訊息: Allowed memory size of XXX bytes exhausted (out of memory) ===
* 訊息: PHP Fatal error:  Allowed memory size of XXX bytes exhausted (tried to allocate XX bytes) <ref>[https://www.airpair.com/php/fatal-error-allowed-memory-size Fixing PHP Fatal Error: Allowed Memory Size Exhausted]</ref>
* 可能原因:
** 一次讀取13萬行的資料,發生記憶體錯誤、
** 無窮迴圈 (infinite loop)
* 解決方法:
** 如果使用 32 位元 (x86) 的 PHP,改成使用 64 位元 (x64) 的 PHP
** 增加 memory_limit<ref>[http://blog.xuite.net/chingwei/blog/30054402-%E3%80%90%E7%B3%BB%E7%B5%B1%E3%80%91PHP+-+Fatal+error%3A+Allowed+memory+size+of+xxx+bytes+exhausted 【系統】PHP - Fatal error: Allowed memory size of xxx bytes exhausted @ My Life :: 隨意窩 Xuite日誌] </ref>
** 跟檔案處理有關:
*** (1) 減少每次讀取的資料行數,例如每次只讀取 50 行的資料筆數來做處理。
*** (2) 如果檔案較大,應避免使用一次讀取全部檔案內容的 [http://php.net/manual/en/function.file-get-contents.php file_get_contents]、[http://php.net/manual/en/function.file-put-contents.php file_put_contents] 等函數,讀取檔案建議改成使用 [https://www.php.net/manual/en/language.generators.overview.php Generators] 或 [http://php.net/manual/en/function.fgets.php fgets]、而寫入檔案則可使用 [https://www.php.net/manual/en/function.fwrite.php fwrite] append 方式寫入<ref>[https://davidwalsh.name/basic-php-file-handling-create-open-read-write-append-close-delete Basic PHP File Handling -- Create, Open, Read, Write, Append, Close, and Delete]</ref>。
*** (3) 如果透過 MySQL 執行匯出資料表的 CSV 檔案,則可以不要選擇欄位名稱,而是選擇全部欄位直接匯出。原因:「Rather than attempting to build the object-tree, you could directly try to select the result into a file」<ref>[https://stackoverflow.com/questions/31471186/how-to-export-millions-of-rows-from-mysql-to-csv-via-php-without-exhausting-memo How to export millions of rows from MySQL to CSV via PHP without exhausting memory? - Stack Overflow]</ref>
*** (4) 如果跟 json 檔案處理有關,可以搭配使用 [https://stedolan.github.io/jq/ jq] 可以有效處理大檔案的 json 檔案
** [http://php.net/manual/en/control-structures.foreach.php foreach] 時,與其寫入整個陣列到記憶體,可以改用 [http://php.net/manual/en/language.generators.overview.php Generators] 寫法,節省記憶體的使用。
** [https://errerrors.blogspot.com/2021/03/allowed-memory-exhausted.html 解決網站伺服器遇到 Allowed memory exhausted 問題]
 
=== 錯誤訊息: It is not safe to rely on the system's timezone settings ===
* 訊息: Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.
* 原因: 沒有設定時區
* 解決方法: 使用 date() 或 strtotime() 等[http://php.net/manual/en/ref.datetime.php 時間相關函數]之前,先設定時區,例 {{kbd | key = <nowiki>date_default_timezone_set("Asia/Taipei")</nowiki>}}
 
=== composer.phar: command not found 或 Could not open input file: composer.phar ===
錯誤訊息: 透過 [https://getcomposer.org/ composer] 安裝 PHP 套件時,例如 {{kbd | key = composer require league/csv}},出現錯誤訊息「composer.phar: command not found」或「Could not open input file: composer.phar」
* 解法I: 如果沒有設定 composer.phar 的 PATH ,需要清楚告知 composer.phar 的完整檔案路徑,例如{{kbd | key = /path/to/php /path/to/composer require league/csv}}
* 解法II on {{Mac}}/{{Linux}}:  將下載的 composer.phar 移動到 /usr/local/bin/composer {{kbd | key = mv /path/to/composer.phar /usr/local/bin/composer}},再重新執行安裝套件的指令<ref>[http://stackoverflow.com/questions/21670709/running-composer-returns-could-not-open-input-file-composer-phar php - Running Composer returns: "Could not open input file: composer.phar" - Stack Overflow]</ref>。
 
== Error Handling and Debugging ==
=== 錯誤訊息: ERROR: 00000:: ===
* 原因: 想要刪除的資料不在 MySQL 資料庫內,進行刪除時,會發生的錯誤。
* 解決方法: 先檢查該資料是否存在,再進行刪除。
 
 


=== 錯誤訊息: PHP syntax error “unexpected $end” ===
=== 錯誤訊息: PHP syntax error “unexpected $end” ===
Line 110: Line 273:
相關頁面: [[Email testing]]
相關頁面: [[Email testing]]


=== 錯誤訊息: Allowed memory size of XXX bytes exhausted (out of memory) ===
* 訊息: PHP Fatal error:  Allowed memory size of XXX bytes exhausted (tried to allocate XX bytes) <ref>[https://www.airpair.com/php/fatal-error-allowed-memory-size Fixing PHP Fatal Error: Allowed Memory Size Exhausted]</ref>
* 可能原因:
** 一次讀取13萬行的資料,發生記憶體錯誤、
** 無窮迴圈 (infinite loop)
* 解決方法:
** 增加 memory_limit<ref>[http://blog.xuite.net/chingwei/blog/30054402-%E3%80%90%E7%B3%BB%E7%B5%B1%E3%80%91PHP+-+Fatal+error%3A+Allowed+memory+size+of+xxx+bytes+exhausted 【系統】PHP - Fatal error: Allowed memory size of xxx bytes exhausted @ My Life :: 隨意窩 Xuite日誌] </ref>
** 跟檔案處理有關:
*** (1) 減少每次讀取的資料行數,例如每次只讀取 50 行的資料筆數來做處理。
*** (2) 如果檔案較大,應避免使用一次讀取全部檔案內容的 [http://php.net/manual/en/function.file-get-contents.php file_get_contents]、[http://php.net/manual/en/function.file-put-contents.php file_put_contents]等函數、
*** (3) 如果透過 MySQL 執行匯出資料表的 CSV 檔案,則可以不要選擇欄位名稱,而是選擇全部欄位直接匯出。原因:「Rather than attempting to build the object-tree, you could directly try to select the result into a file」<ref>[https://stackoverflow.com/questions/31471186/how-to-export-millions-of-rows-from-mysql-to-csv-via-php-without-exhausting-memo How to export millions of rows from MySQL to CSV via PHP without exhausting memory? - Stack Overflow]</ref>
*** (4) 如果跟 json 檔案處理有關,可以搭配使用 [https://stedolan.github.io/jq/ jq] 可以有效處理大檔案的 json 檔案
** [http://php.net/manual/en/control-structures.foreach.php foreach] 時,與其寫入整個陣列到記憶體,可以改用 [http://php.net/manual/en/language.generators.overview.php Generators] 或 [http://php.net/manual/en/function.fgets.php fgets] 寫法,節省記憶體的使用。
=== 錯誤訊息: It is not safe to rely on the system's timezone settings ===
* 訊息: Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.
* 原因: 沒有設定時區
* 解決方法: 使用 date() 或 strtotime() 等[http://php.net/manual/en/ref.datetime.php 時間相關函數]之前,先設定時區,例 {{kbd | key = <nowiki>date_default_timezone_set("Asia/Taipei")</nowiki>}}
=== 移除非預期的空白(全形空白) ===
需要額外移除 [http://www.fileformat.info/info/unicode/char/3000/index.htm 'IDEOGRAPHIC SPACE' (U+3000)] 全形空白
<pre>
$string = str_replace(json_decode('"\u3000"'), "", $string);
$string = trim($string);
</pre>
More on [[Data_cleaning#Data handling | Data handling]]
=== PHPExcel 產生的 Excel 檔案,開啟後看到一堆亂碼 ===
狀況1: 開啟 Excel 檔案,看到最前面有 {{kbd | key=<nowiki>NOTICE</nowiki>}} 的錯誤訊息,例如 {{kbd | key=<nowiki><b>Notice</b>:  Constant CONST_XXX already defined in <b>path\to\script.php</b> on line xx</nowiki>}}
* 解法: 關閉錯誤訊息輸出 ex: [http://www.php.net/manual/en/function.error-reporting.php error_reporting(0);] 以及修正 NOTICE 訊息指涉的問題,例如例子中常數重複宣告的問題。
狀況2: 開啟 Excel 檔案,看到最前面有 {{kbd | key=<nowiki>Fatal error</nowiki>}} 之類的錯誤訊息
* 解法: 關閉錯誤訊息輸出 ex: [http://www.php.net/manual/en/function.error-reporting.php error_reporting(0);] ,以及修正 Fatal error 訊息指涉的問題。
狀況3: 開啟 Excel 檔案,看到有儲存格位址之類的錯誤訊息
* 解法: 該儲存格內容以等號 (=) 開始,卻不是函數。解決方式是將儲存格內容的最前面加一個單引號 (') 或者是加個空白。
=== composer.phar: command not found 或 Could not open input file: composer.phar ===
錯誤訊息: 透過 [https://getcomposer.org/ composer] 安裝 PHP 套件時,例如 {{kbd | key = composer require league/csv}},出現錯誤訊息「composer.phar: command not found」或「Could not open input file: composer.phar」
* 解法I: 如果沒有設定 composer.phar 的 PATH ,需要清楚告知 composer.phar 的完整檔案路徑,例如{{kbd | key = /path/to/php /path/to/composer require league/csv}}
* 解法II on {{Mac}}/{{Linux}}:  將下載的 composer.phar 移動到 /usr/local/bin/composer {{kbd | key = mv /path/to/composer.phar /usr/local/bin/composer}},再重新執行安裝套件的指令<ref>[http://stackoverflow.com/questions/21670709/running-composer-returns-could-not-open-input-file-composer-phar php - Running Composer returns: "Could not open input file: composer.phar" - Stack Overflow]</ref>。


=== COMPOSER 升級 PHPUNIT 版本 6 到 7 遇到問題 YOUR REQUIREMENTS COULD NOT BE RESOLVED TO AN INSTALLABLE SET OF PACKAGES ===
=== COMPOSER 升級 PHPUNIT 版本 6 到 7 遇到問題 YOUR REQUIREMENTS COULD NOT BE RESOLVED TO AN INSTALLABLE SET OF PACKAGES ===
Line 169: Line 290:
[https://www.geeksforgeeks.org/php-shell_exec-vs-exec-function/ PHP | shell_exec() vs exec() Function - GeeksforGeeks]
[https://www.geeksforgeeks.org/php-shell_exec-vs-exec-function/ PHP | shell_exec() vs exec() Function - GeeksforGeeks]


Or input the {{kbd | key=kill}} command to stop the process if you have the permission. See details on [[Alternative_Linux_commands#Show_the_process_list_.26_kill_the_process]]
Or input the {{kbd | key=kill}} command to stop the process if you have the permission. See details on [[Linux_commands#Show_the_process_list_.26_kill_the_process]]
 
=== Using PHP from the command line ===
[[Execute php script in a bat file]]


=== Json errors ===
=== Json errors ===
Line 181: Line 299:


* 解法: 查詢語法中包含複雜的 sub query 雖然可以順利呈現查詢結果,但是搜尋篩選時出現查詢錯誤。如果要使用 phpgrid ,建議降低查詢的複雜度。
* 解法: 查詢語法中包含複雜的 sub query 雖然可以順利呈現查詢結果,但是搜尋篩選時出現查詢錯誤。如果要使用 phpgrid ,建議降低查詢的複雜度。
== General PHP Practices ==
=== Using PHP from the command line ===
[[Execute php script in a bat file]]
=== 移除非預期的空白(全形空白) ===
需要額外移除 [http://www.fileformat.info/info/unicode/char/3000/index.htm 'IDEOGRAPHIC SPACE' (U+3000)] 全形空白
<pre>
$string = str_replace(json_decode('"\u3000"'), "", $string);
$string = trim($string);
</pre>
More on: [[Data_cleaning#Remove other string look like whitespace | Remove other string look like whitespace]]


== 使用者操作/使用者輸入的內容 ==
== 使用者操作/使用者輸入的內容 ==
Line 186: Line 318:


== 避免的 coding 習慣 ==
== 避免的 coding 習慣 ==
* 避免使用簡化的的變數名稱,例如 $sd 也許一開始還會記得,但是過一陣子就會忘記這是什麼
[[Maintain legacy code]]
* 重複複製貼上的內容,但是內容可能常被使用者更改,導致內容更新困難,需要修改多處的程式碼
* 絕對路徑或絕對網址寫死在程式碼內,導致日後移機或對外公開網站服務時,需要修改多處的程式碼
** 存取檔案時將完整路徑,例如 {{kbd | key= <nowiki>D:/AppServ/www/abc.csv</nowiki>}} 寫死在程式碼內
** 將測試網址 (127.0.0.1 或 localhost) 寫死在程式碼內
* 容易閱讀的錯誤訊息:除了 500 Error ,如果可以讓使用者自行處理,建議改成容易閱讀的錯誤訊息。
 
* [[Maintain legacy code]]


== unified coding style ==
== unified coding style ==
Line 211: Line 336:
* [http://devdocs.io/ DevDocs API Documentation]
* [http://devdocs.io/ DevDocs API Documentation]


== troubleshooting steps of function ==
== References ==
Display error message or check the PHP error logs
* {{kbd | key=<nowiki>ini_set("display_errors", "On");</nowiki>}} See details on [http://php.net/manual/en/errorfunc.configuration.php PHP: Runtime Configuration - Manual]
* {{kbd | key=<nowiki>error_reporting(E_ALL);</nowiki>}} See details on [http://php.net/manual/en/function.error-reporting.php PHP: error_reporting - Manual]
* [https://www.jetbrains.com/help/phpstorm/event-log-tool-window.html Event Log - Help | PhpStorm]
 
Check the Web service logs
# {{kbd | key=<nowiki>sudo tail /var/log/httpd/error.log</nowiki>}} if the web service logs was located at {{kbd | key=<nowiki>/var/log/httpd/error.log</nowiki>}}
# Example log: {{kbd | key=<nowiki>[Thu Nov 08 12:20:40.412630 2018] [:error] [pid 12769] [client x.x.x.x:4433] PHP Parse error:  syntax error, unexpected '$var' (T_VARIABLE) in /home/wwwroot/path/to/file.php on line 100</nowiki>}}
# Display partial source code: {{kbd | key=<nowiki>sed -n '990,110p;111q' /home/wwwroot/path/to/file.php</nowiki>}}<ref>[https://stackoverflow.com/questions/83329/how-can-i-extract-a-predetermined-range-of-lines-from-a-text-file-on-unix How can I extract a predetermined range of lines from a text file on Unix? - Stack Overflow]</ref>
 
Simply the question
* Is the [http://php.net/manual/en/function.function-exists.php function_exists]?
** Extension dependency? Install the extension you need.
** If not, looking for the alternative functions.
* Was the function really executed? Maybe using the __LINE__ to examin the logic.
* Disable the logical judgement and just print text using [http://php.net/manual/en/function.var-dump.php var_dump] or [http://php.net/manual/en/function.print-r.php print_r] functions.
* Check the if-else condition was satisfied or not cf: [http://www.leepoint.net/notes-java/data/strings/12stringcomparison.html Java: String Comparison] It's logical (compiler will not show the warning) but wrong.
* try & catch: [http://php.net/manual/en/language.exceptions.php PHP: Exceptions]
 
== logging ==
native error logging
* [http://www.php.net/ PHP] log: check the configuration file: /etc/php.ini (the location of configuration file can be verified by [http://php.net/manual/en/function.phpinfo.php phpinfo()] )
(for production site) unmark theese lines in the php.ini and restart Apache service
<pre>
log_errors = On
error_log = "php_error.log"
</pre>
(for development site) using [http://php.net/manual/en/function.error-reporting.php error_reporting]
<pre>
error_reporting(E_ALL);
</pre>
 
[http://tw1.php.net/print_r PHP: print_r - Manual]
<pre>
$log = print_r($variable, true);
//save to the log file
 
$log = print_r(debug_backtrace(), true);
//Generates a backtrace and save to the log file
</pre>
 
capture the result of var_dump:
ob_start
* [http://stackoverflow.com/questions/139474/how-can-i-capture-the-result-of-var-dump-to-a-string php - How can I capture the result of var_dump to a string? - Stack Overflow]
* [http://php.net/manual/en/function.error-log.php PHP: error_log - Manual]
<pre>
ob_start();
var_dump($some_variable);
$result = ob_get_clean();
error_log($result, 3, 'd:/result.log');
</pre>
 
QuickForm
<pre>
$result = var_dump($some_variable);
$form->addElement('html', $result);
</pre>
 
 
[http://ellislab.com/codeigniter CodeIgniter]: [http://stackoverflow.com/questions/7370391/how-to-configure-codeigniter-to-report-all-errors php - How to configure Codeigniter to report all errors? - Stack Overflow]
 
 
show the line number and filename
<pre>
echo 'Houston, we've had a problem '. __line__ . ' ' . __FILE__ ."<br />";
</pre>
more on [http://php.net/manual/en/language.constants.predefined.php PHP: Magic constants], [https://github.com/Seldaek/monolog monolog]
 
== references ==
<references/>
<references/>