關於 ?> end tag,官網有這麼一段話,建議不要寫:
The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
最近遇到一件慘案。
伺服器A要呼叫伺服器B的一隻 API,因為早期開發比較沒有固定做法,所以把整個資料進行加密回傳給伺服器A。 然後有一天突然說解密錯誤。
測試的時候可以看到,伺服器A拿到的資料會換行,但是伺服器B傳出的時候並沒有換行。示意如下:
// 伺服器A [Tue Oct 13 11:27:39 2015] [error] [client 127.0.0.1] 4fCfBODGX4qDIcLjcc0NqbY- // 伺服器B [Tue Oct 13 11:27:39 2015] [error] [client 127.0.0.1] 4fCfBODGX4qDIcLjcc0NqbY-
檢查伺服器B,看起來沒什麼改動。找了很久之後才發現,有人在某隻依賴的 PHP 檔案的 end tag 後面加了一行:
- // handler.php
- <?php
- require_once 'XYZ.php';
- // ...
- header('Content-Type: application/octet-stream');
- header('HTTP/1.0 200');
- echo encrypt_data($output);
- ?>
- // ABC.php
- <?php
- // ...
- ?>
一個小疏忽會累死別人。