tedshd's DevNote

Develop & Design Note by Ted

Your posts match “ php ” tag:

PHP Note

PHP Note

Notice

  • 處理 db 的部分放到 model 處理來增強可用性
  • 減少邏輯判斷
  • 以錯誤為優先處裡

array to string

<?php

$arr = array(
    'val' => 1,
    'str' => 'string',
);

$to_string = serialize($arr);
echo $to_string;
// a:2:{s:3:"val";i:1;s:3:"str";s:6:"string";}

$to_array = unserialize($to_string);
var_dump($to_array);

/* not better
 * if $to_string can't unserialize, it has PHP error
 */

?>

coding style

在 PHP 中有許多邏輯判斷
當有許多條件要去檢查時, 一般來說就是用 if 一直寫下去
最後就造成下面的情況

if ($a === $b)
{
    if ($c)
    {
        if ($c >= 10)
        {
            if ($d)
            {
                // do something
                // ...
            }
        return;
        }
    return;
    }
}

這樣下去就沒完沒了, 而且縮排會越來越多, 要看 code 也很不方便
所以假如就已作條件檢查來說
可以用以下的做法

// check condition 1
if ($a !== $b)
{
    return;
}

// check condition 2
if (!$c || $c === '')
{
    return;
}

// check condition 3
if ($c < 9)
{
    return;
}

// check condition 4
if (!d)
{
    return;
}

// do something
// ...

做個 反向思考 , 把不適合的條件列出再一一 return or 作處理
剩下的便是所需要的

有時也會遇到應該用 switch 卻用 if 去一直加下去的情況
所以當 if 用到 3 個 以上時, 就要思考要用什麼敘述來達到目的比較好

htmlspecialchars

在輸出資料時在 HTML 呈現會有特殊字元或跳脫字元甚至把 script 輸出執行的問題
所以在輸出的資料是使用者輸入的, 就必須用 htmlspecialchars 包起來

<?php

htmlspecialchars($string);

?>

curl

PHP CURL詳解

Detect mobile device

Detect mobile device

Use PHP or JavaScript detect mobile device like iPhone, iPad, iPod or Android...

Android

PHP
<?php
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua, 'android') !== false) {
    echo 'Android!!';
    exit;
}
?>
JavaScript
var ua = navigator.userAgent.toLowerCase();
if(ua.indexOf("android") > -1) {
    document.write('Android!!');
}

Refer - Android Detection with JavaScript or PHP

Apple mobile device

Refer - How to detect iPhone, iPod and iPad with PHP
Refer - How to Identify an Apple iPhone, iPod or iPad Visitor to Your Website

PHP - install phpcs(PHP CodeSniffer)

PHP - install phpcs(PHP CodeSniffer)

Use pear install phpcs

in Linux(Ubuntu 14.04)

sudo pear install --alldeps php_codesniffer

in Mac(Mac OS X 10.10.1 Yosemite)

install pear
sudo curl -O  http://pear.php.net/go-pear.phar

then

sudo php -d detect_unicode=0 go-pear.phar

Update

pear upgrade pear
pear upgrade
install codesniffer
sudo pear install --alldeps php_codesniffer

check

phpcs -i

return

The installed coding standards are MySource, PEAR, PHPCS, PSR1, PSR2, Squiz and Zend

if return

Warning: include_once(PHP/CodeSniffer/CLI.php): failed to open stream: No such file or directory in /usr/bin/phpcs on line 22

Warning: include_once(): Failed opening 'PHP/CodeSniffer/CLI.php' for inclusion (include_path='.:') in /usr/bin/phpcs on line 22

Fatal error: Class 'PHP_CodeSniffer_CLI' not found in /usr/bin/phpcs on line 25

Must include pear path

Modify php.ini

sudo vim /etc/php.ini
include_path = ".:/usr/share/pear"

Usage

phpcs <php file>

Refer - PEAR - PHP Extension and Application Repository
Refer - PHP_CodeSniffer
Refer - Code Sniffer
Refer - Installing PEAR on OSX 10.9 Mavericks and OSX10.8/10.7

PHP - Auto update static files cache

PHP - Auto update static files cache

We can cache static files(CSS, JavaScript) to client

When Server update static code.

We want to update cache then we can modify file or add query string update version.

We have some choice like modify url ?v=1 to ?v=2

But I want to auto modify version.

This is a way i use

<?php
function autoversion($url) {
    $ver = stat($_SERVER['DOCUMENT_ROOT'] . $url)[mtime];
    return $url . "?v=" . $ver;
}
# example
?>

<link href="<?php echo autoversion('/path/to/theme.css'); ?>" rel="stylesheet">

This way use file last modify time as a version.

First i want to use filemtime but it fail.

So i give up this way.

Update

Before use filemtime(), must use clearstatcache();

And my friend say stat has IO behavior, so this way is not perfect solution.

If service has lot of stat() or mass request, so many IO can influences performance.

Then we can write a script add update version and run it when service deploy.

Refer - Strategies for Cache-Busting CSS

Refer - stat

filemtime

Something about XSS(Cross-site scripting)

Something about XSS(Cross-site scripting)

If not set anything

Use like

<?php echo $_GET['name'];?>

and querystring name = <script>alert(document.cookie)</script>

And not defence XSS

In Firefox

In Chrome

In Safari

Result

Chrome & Safari browser has handle XSS default

Defence

Set header X-XSS-Protection: 1

if use PHP, can use

htmlspecialchars()
// or
 htmlentities()

Important!

Finally

We must know it is handle encode to avoid run JavaScript on page

JavaScript ver htmlspecialchars

Refer - XSS攻擊的深入探討與防護之道

php - 比對時間

php - 比對時間

記錄一下比對時間的方式(利用 timestamp)

time() > strtotime('2017-11-13 23:59:59');

php - loop directory

php - loop directory

Sometime need use php loop directory list all file in this directory

$directory = scandir('./js');
foreach($directory as $file) {
    if ($file === '.' || $file === '..') {
        continue;
    }
    echo $file;
    echo "\n";
}

Mac - php redis install

Mac - php redis install

Mac Env

Mac OSX 10.14.5

Step

git clone https://www.github.com/phpredis/phpredis.git

cd phpredis

phpize && ./configure && make && sudo make install

test

php -r "if (new Redis() == true){ echo \"\r\n OK \r\n\"; }"

Troubleshooting

phpize

1.

$ phpize
grep: /usr/include/php/main/php.h: No such file or directory
grep: /usr/include/php/Zend/zend_modules.h: No such file or directory
grep: /usr/include/php/Zend/zend_extensions.h: No such file or directory
Configuring for:
PHP Api Version:        
Zend Module Api No:     
Zend Extension Api No:

Solution

cd /Library/Developer/CommandLineTools/Packages/

open macOS_SDK_headers_for_macOS_10.14.pkg

2.

$ phpize
Cannot find autoconf. Please check your autoconf installation and the $PHP_AUTOCONF environment variable. Then, rerun this script.

Solution

brew install autoconf

Refer - install-phpredis-mac-osx

Refer - macOS 10.14软件编译时找不到头文件的解决方法

Refer - macOS 中使用 phpize 动态添加 PHP 扩展的错误解决方法

php - float 浮點數科學記號轉換

php - float 浮點數科學記號轉換

php - float

php 的浮點數大小受限於系統, 且會自動轉換成科學記號呈現, 但是一般人不會去看科學記號

echo 0.0000234;
// 2.34E-5

在呈現上希望轉換回小數點的呈現

可以用以下方法做到

$s = 0.0000234;
trim(rtrim(sprintf("%.10f", $s), '0'), '.');
// 0.0000234

這邊 sprintf 只取 10 位數

因為就之前遇到的系統超過 10 位數都會是不精確的浮點數

PHP - check HTTP protocol

PHP - check HTTP protocol

Use

$protocol    = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ? 'https' : 'http';