# PHP

# 【php】在 CentOS 6 安裝、設定 Oracel PDO_OCI

[在 CentOS 6 安裝、設定 Oracel PDO\_OCI | 未知 (dtask.idv.tw)](https://blog.dtask.idv.tw/Centos/oracle_pdo_oci_in_centos_6/)

---

[https://www.oracle.com/database/technologies/instant-client.html](https://www.oracle.com/database/technologies/instant-client.html)

```PHP
<?php
// IP 與 PORT
$tns = '
(DESCRIPTION =
    (ADDRESS_LIST =
        (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.3.1)(PORT = 1521))
    )
    (CONNECT_DATA =
        (SERVICE_NAME = orcl)
    )
)';

$user = 'tnfd';     // 帳號
$passwd = 'tnfd';   // 密碼

try {
    $dbConn = new PDO('oci:dbname=' . $tns, $user, $passwd);
} catch (PDOException $e){
    echo $e->getMessage();
}

$stmt = $dbConn->query('SELECT * FROM BACUST00');
$row = $stmt->fetch();

echo '';
var_dump($row);
echo '';
```

```
export ORACLE_HOME=/usr/lib/oracle/11.2/client64
export ORACLE_BASE=/usr/lib/oracle/11.2
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH
export PATH=$ORACLE_HOME/bin:$PATH
```

# 大於等於小於 縮寫

- **lt：less than** 小於
- **le：less than or equal to** 小於等於
- **eq：equal to** 等於
- **ne：not equal to** 不等於
- **ge：greater than or equal to** 大於等於
- **gt：greater than** 大於

# 常用函數 empty isset isnull 比較

[![image-1637654833415.png](https://bookstack.treemanou.com/uploads/images/gallery/2021-11/scaled-1680-/S9se8GNFeJJkm3lm-image-1637654833415.png)](https://bookstack.treemanou.com/uploads/images/gallery/2021-11/S9se8GNFeJJkm3lm-image-1637654833415.png)

# Centos7 安裝 php7.4

#### 新增Remi repository

```shell
yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum install epel-release yum-utils
```

開啟PHP 7.4  
`yum-config-manager --enable remi-php74`

安裝PHP 7.4  
`yum install php`

驗證  
`php -v`

安裝PHP 7.4擴充功能

```shell
yum install php-devel php-xmlrpc php-bcmath php-recode php-pdo php-mysqlnd \
php-enchant php-common php-cli php-gd php-embedded php-ldap php-process \
php-pecl-zip php-pgsql php-dba php-json php-soap php-fpm php-pear php-odbc \
php-intl php-xml php-snmp php-mbstring php-imagick -y
```

如要降級安裝php 7.3，則先移除原先的安裝，再執行  
`yum-config-manager --disable remi-php74<br></br>yum-config-manager --enable remi-php73`

# PHP_判斷json物件

```PHP
function isJson($string) {
   json_decode($string);
   return json_last_error() === JSON_ERROR_NONE;
}
```

# PHP_使用curl 上傳資料

client shell

```shell
# curl 上傳資料
# {file} : 可更改,$_file 的key就會不同
# curl -X POST -F "{file}=@{檔案路徑}" {api url}
curl -X POST -F "file=@/tmp/sms_count.csv" http://192.168.1.1/api/v1/SMS/UploadSmsCount

```

server 端 php

```PHP

// 取得$_file 資料
// $file 
Array
(
    [file] => Array
        (
            [name] => sms_count.csv
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpAvxPxQ
            [error] => 0
            [size] => 1175
        )

)
  
// 取得內容 => $data
$data = file_get_contents($_FILES['file']['tmp_name']);  

// 如果csv 是 big5  記得轉碼
$data = iconv("BIG5","UTF-8",$data);

```

# PHP_連線postgresql

安裝postgrel extenstion

```shell
yum install php-pgsql -y
```

修改 /var/lib/pgsql/12/data/pg\_hba.conf

```
host    all             all             10.60.87.0/24           md5
```

重啟服務

```
service postgresql-12 restart
```

# PHP_實現異步請求

[PHP教程：php中使用fsockopen實現異步請求（代碼示例） (insci.cn)](https://tw.insci.cn/job_87377.html)

[《面試官別再問》PHP運用多執行緒(Multi-thread)實現非阻塞方法 | 阿宅工作日誌 (bps1025.blogspot.com)](https://bps1025.blogspot.com/2018/10/php-multi-threadprocopen.html)

# PHP_檔案相關

- #### 判斷資料夾是否存在，建立資料夾

```PHP
if ( !file_exists( $dir ) || !is_dir( $dir) ) {   mkdir($dir); }
```

- #### 遞回查詢資料夾內檔案

```PHP

function listdirs($dirf, $mark=1) {

    // LOB_MARK	若檔案為資料夾，在回傳檔案路徑的最後面加上斜線"\"
    // GLOB_NOSORT	保持檔案路徑在原資料夾的出現順序(不重新排序)
    // GLOB_NOCHECK	若找不到匹配的檔案路徑，回傳匹配的條件字串
    // GLOB_NOESCAPE	不要將反斜線視為跳脫字元
    // GLOB_BRACE	將 {a,b,c} 視為搜尋 'a', 'b', 或 'c'
    // GLOB_ONLYDIR	只列出資料夾路徑
    // GLOB_ERR	發生讀取錯誤時停止動作(像是無法讀取的資料夾)，預設是「忽略錯誤」
    $alldirs = array();
    if ($mark==1)
    {
        $alldirs = null;
    }
    $dirs = glob($dirf . '/*', GLOB_NOSORT);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dirf) listdirs($dirf, 0);
    return $alldirs;
}
$dirf="/tmp";
$result_data = listdirs($dirf, $mark=1);
echo print_r($result_data,true);
```

執行系統命令

```PHP
  function osCommand( $CMD="" )
  {
    $ret="";
    
    if( $CMD=="" )
      return $ret;
      
    if( ($fp = popen($CMD,"r")) )
    {
      $ret="";
      while( !feof( $fp ) )
        $ret .= fgets( $fp )."\n";
      fclose( $fp );
    }
    
    return $ret;
  }
if(!is_dir($log_folder)){
	mkdir($log_folder);
	osCommand( "chown webmaster.webmaster $log_folder");
}
```

# prettyPrint

```PHP
function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }

    return $result;
}
```

# require和include的不同

<div id="bkmrk-include%28%27func.php%27%29%3B"><div>```
<span class="hljs-keyword">include</span>(<span class="hljs-string">'func.php'</span>);
<span class="hljs-keyword">include</span> <span class="hljs-string">'func.php'</span>;

<span class="hljs-keyword">require</span>(<span class="hljs-string">'lib.php'</span>);
<span class="hljs-keyword">require</span>(<span class="hljs-string">'lib.php'</span>);

<span class="hljs-keyword">include_once</span> <span class="hljs-string">'mydb.php'</span>;
<span class="hljs-keyword">include_once</span>(<span class="hljs-string">'mydb.php'</span>);

<span class="hljs-keyword">require_once</span> <span class="hljs-string">'copyright.php'</span>;
<span class="hljs-keyword">require_once</span>(<span class="hljs-string">'copyright.php'</span>);
```

</div></div><div id="bkmrk-%2Arequire%E5%92%8Cinclude%E7%9A%84%E4%B8%8D%E5%90%8C">*require和include的不同</div><div id="bkmrk-require"><div>- **require**

</div></div>> - 適合用來引入`靜態`的內容
> - 如果include進來的檔案發生錯誤的話，會顯示`警告`，`不會立刻停止`

<div id="bkmrk-include"><div>- **include**

</div></div>> - 則適合用來引入`動態`的程式碼。
> - 而require 則是會顯示`錯誤`，`立刻終止程式`，不再往下執行。

<div id="bkmrk-require_once%E5%92%8Cinclude"><div>---

- **require\_once**和**include\_once**

</div></div>> 使用方法跟require、include一樣，差別在於在引入檔案前
> 
> 會先**檢查檔案是否已經在其他地方被引入過了**，若有，就不會再重複引入。

# mac 安裝 php 7.4

mac 安裝 php 7.4

```
brew tap shivammathur/php
brew install php@7.4
brew link --overwrite --force php@7.4
php -v
```