1. 程式人生 > >fsockopen 來模擬生成 HTTP 連線

fsockopen 來模擬生成 HTTP 連線

/**
     * fsockopen 來模擬生成 HTTP 連線 
     */

    public function doRequest($host,$path, $param=array()){
        $query = isset($param)? http_build_query($param) : '';

        $port = 10086;
        $errno = 0;
        $errstr = '';
        $timeout = 360;

        $fp = fsockopen($host, $port, $errno, $errstr, $timeout);

        $out = "POST ".$path." HTTP/1.1\r\n";
        $out .= "host:".$host."\r\n";
        $out .= "content-length:".strlen($query)."\r\n";
        $out .= "content-type:application/x-www-form-urlencoded\r\n";
        $out .= "connection:close\r\n\r\n";
        $out .= $query;

        fputs($fp, $out);
        fclose($fp);
    }

呼叫

//查詢漏電自檢
                    $host = $_SERVER['SERVER_NAME'];
                    $path = "/apiv2/get-mogo/index";//這個是去請求的介面
                    $param = [
                        "sid" => $deviceid
                    ];
$result = $this->doRequest($host, $path, $param);

呼叫的介面

 public function actionIndex()
    {
        $request = \Yii::$app->request;

        if ($request->isPost) {
            $attributes = $request->post();
            $sid = isset($attributes['sid']) ? $attributes['sid'] : '';
            $path = \app\services\VStatusLog::newestQueryup($sid);
            $path = json_encode($path,true);
            return $path;
        }else {
            return $this->returnData('', -1, '請求方式錯誤');
        }

    }

 

根據結果進行判斷

               用法1: 新增一個數據庫欄位(0查詢前 1 查詢成功 2查詢失敗)   查詢後修改