PHP封装的HttpClient类用法实例,封装httpclient
本文实例讲述了PHP封装的HttpClient类。分享给大家供大家参考。具体分析如下:
这是一段php封装的HttpClient类,可实现GET POST Cookie Session等简单的功能。原来做过,这两天重新修改了一下。
<?php /* * Filename: httpclient.php * Created on 2012-12-21 * Created by RobinTang * To change the template for this generated file go to * Window - Preferences - PHPeclipse - PHP - Code Templates */ class SinCookie { public $name; // Cookie名称 public $value; // Cookie值 // 下面三个属性现在未实现 public $expires; // 过期时间 public $path; // 路径 public $domain; // 域 // 从Cookie字符串创建一个Cookie对象 function __construct($s = false) { if ($s) { $i1 = strpos($s, '='); $i2 = strpos($s, ';'); $this->name = trim(substr($s, 0, $i1)); $this->value = trim(substr($s, $i1 +1, $i2 - $i1 -1)); } } // 获取Cookie键值对 function getKeyValue() { return "$this->name=$this->value"; } } // 会话上下文 class SinHttpContext { public $cookies; // 会话Cookies public $referer; // 前一个页面地址 function __construct() { $this->cookies = array (); $this->refrer = ""; } // 设置Cookie function cookie($key, $val) { $ck = new SinCookie(); $ck->name = $key; $ck->value = $val; $this->addCookie($ck); } // 添加Cookie function addCookie($ck) { $this->cookies[$ck->name] = $ck; } // 获取Cookies字串,请求时用到 function cookiesString() { $res = ''; foreach ($this->cookies as $ck) { $res .= $ck->getKeyValue() . ';'; } return $res; } } // Http请求对象 class SinHttpRequest { public $url; // 请求地址 public $method = 'GET'; // 请求方法 public $host; // 主机 public $path; // 路径 public $scheme; // 协议,http public $port; // 端口 public $header; // 请求头 public $body; // 请求正文 // 设置头 function setHeader($k, $v) { if (!isset ($this->header)) { $this->header = array (); } $this->header[$k] = $v; } // 获取请求字符串 // 包含头和请求正文 // 获取之后直接写socket就行 function reqString() { $matches = parse_url($this->url); !isset ($matches['host']) && $matches['host'] = ''; !isset ($matches['path']) && $matches['path'] = ''; !isset ($matches['query']) && $matches['query'] = ''; !isset ($matches['port']) && $matches['port'] = ''; $host = $matches['host']; $path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/'; $port = !empty ($matches['port']) ? $matches['port'] : 80; $scheme = $matches['scheme'] ? $matches['scheme'] : 'http'; $this->host = $host; $this->path = $path; $this->scheme = $scheme; $this->port = $port; $method = strtoupper($this->method); $res = "$method $path HTTP/1.1\r\n"; $res .= "Host: $host\r\n"; if ($this->header) { reset($this->header); while (list ($k, $v) = each($this->header)) { if (isset ($v) && strlen($v) > 0) $res .= "$k: $v\r\n"; } } $res .= "\r\n"; if ($this->body) { $res .= $this->body; $res .= "\r\n\r\n"; } return $res; } } // Http响应 class SinHttpResponse { public $scheme; // 协议 public $stasus; // 状态,成功的时候是ok public $code; // 状态码,成功的时候是200 public $header; // 响应头 public $body; // 响应正文 function __construct() { $this->header = array (); $this->body = null; } function setHeader($key, $val) { $this->header[$key] = $val; } } // HttpClient class SinHttpClient { public $keepcontext = true; // 是否维持会话 public $context; // 上下文 public $request; // 请求 public $response; // 响应 public $debug = false; // 是否在Debug模式, //为true的时候会打印出请求内容和相同的头部 function __construct() { $this->request = new SinHttpRequest(); $this->response = new SinHttpResponse(); $this->context = new SinHttpContext(); $this->timeout = 15; // 默认的超时为15s } // 清除上一次的请求内容 function clearRequest() { $this->request->body = ''; $this->request->setHeader('Content-Length', false); $this->request->setHeader('Content-Type', false); } // post方法 // data为请求的数据 // 为键值对的时候模拟表单提交 // 其他时候为数据提交,提交的形式为xml // 如有其他需求,请自行扩展 function post($url, $data = false) { $this->clearRequest(); if ($data) { if (is_array($data)) { $con = http_build_query($data); $this->request->setHeader('Content-Type', 'application/x-www-form-urlencoded'); } else { $con = $data; $this->request->setHeader('Content-Type', 'text/xml; charset=utf-8'); } $this->request->body = $con; $this->request->method = "POST"; $this->request->setHeader('Content-Length', strlen($con)); } $this->startRequest($url); } // get方法 function get($url) { $this->clearRequest(); $this->request->method = "GET"; $this->startRequest($url); } // 该方法为内部调用方法,不用直接调用 function startRequest($url) { $this->request->url = $url; if ($this->keepcontext) { // 如果保存上下文的话设置相关信息 $this->request->setHeader('Referer', $this->context->refrer); $cks = $this->context->cookiesString(); if (strlen($cks) > 0) $this->request->setHeader('Cookie', $cks); } // 获取请求内容 $reqstring = $this->request->reqString(); if ($this->debug) echo "Request:\n$reqstring\n"; try { $fp = fsockopen($this->request->host, $this->request->port, $errno, $errstr, $this->timeout); } catch (Exception $ex) { echo $ex->getMessage(); exit (0); } if ($fp) { stream_set_blocking($fp, true); stream_set_timeout($fp, $this->timeout); // 写数据 fwrite($fp, $reqstring); $status = stream_get_meta_data($fp); if (!$status['timed_out']) { //未超时 // 下面的循环用来读取响应头部 while (!feof($fp)) { $h = fgets($fp); if ($this->debug) echo $h; if ($h && ($h == "\r\n" || $h == "\n")) break; $pos = strpos($h, ':'); if ($pos) { $k = strtolower(trim(substr($h, 0, $pos))); $v = trim(substr($h, $pos +1)); if ($k == 'set-cookie') { // 更新Cookie if ($this->keepcontext) { $this->context->addCookie(new SinCookie($v)); } } else { // 添加到头里面去 $this->response->setHeader($k, $v); } } else { // 第一行数据 // 解析响应状态 $preg = '/^(\S*) (\S*) (.*)$/'; preg_match_all($preg, $h, $arr); isset ($arr[1][0]) & $this->response->scheme = trim($arr[1][0]); isset ($arr[2][0]) & $this->response->stasus = trim($arr[2][0]); isset ($arr[3][0]) & $this->response->code = trim($arr[3][0]); } } // 获取响应正文长度 $len = (int) $this->response->header['content-length']; $res = ''; // 下面的循环读取正文 while (!feof($fp) && $len > 0) { $c = fread($fp, $len); $res .= $c; $len -= strlen($c); } $this->response->body = $res; } // 关闭Socket fclose($fp); // 把返回保存到上下文维持中 $this->context->refrer = $url; } } } // demo // now let begin test it $client = new SinHttpClient(); // create a client $client->get('http://www.baidu.com/'); // get echo $client->response->body; // echo ?>
希望本文所述对大家的php程序设计有所帮助。

데이터베이스 스토리지 세션 사용의 주요 장점에는 지속성, 확장 성 및 보안이 포함됩니다. 1. 지속성 : 서버가 다시 시작 되더라도 세션 데이터는 변경되지 않아도됩니다. 2. 확장 성 : 분산 시스템에 적용하여 세션 데이터가 여러 서버간에 동기화되도록합니다. 3. 보안 : 데이터베이스는 민감한 정보를 보호하기 위해 암호화 된 스토리지를 제공합니다.

SessionHandlerInterface 인터페이스를 구현하여 PHP에서 사용자 정의 세션 처리 구현을 수행 할 수 있습니다. 특정 단계에는 다음이 포함됩니다. 1) CustomsessionHandler와 같은 SessionHandlerInterface를 구현하는 클래스 만들기; 2) 인터페이스의 방법 (예 : Open, Close, Read, Write, Despare, GC)의 수명주기 및 세션 데이터의 저장 방법을 정의하기 위해 방법을 다시 작성합니다. 3) PHP 스크립트에 사용자 정의 세션 프로세서를 등록하고 세션을 시작하십시오. 이를 통해 MySQL 및 Redis와 같은 미디어에 데이터를 저장하여 성능, 보안 및 확장 성을 향상시킬 수 있습니다.

SessionId는 웹 애플리케이션에 사용되는 메커니즘으로 사용자 세션 상태를 추적합니다. 1. 사용자와 서버 간의 여러 상호 작용 중에 사용자의 신원 정보를 유지하는 데 사용되는 무작위로 생성 된 문자열입니다. 2. 서버는 쿠키 또는 URL 매개 변수를 통해 클라이언트로 생성하여 보낸다. 3. 생성은 일반적으로 임의의 알고리즘을 사용하여 독창성과 예측 불가능 성을 보장합니다. 4. 실제 개발에서 Redis와 같은 메모리 내 데이터베이스를 사용하여 세션 데이터를 저장하여 성능 및 보안을 향상시킬 수 있습니다.

JWT 또는 쿠키를 사용하여 API와 같은 무국적 환경에서 세션을 관리 할 수 있습니다. 1. JWT는 무국적자 및 확장 성에 적합하지만 빅 데이터와 관련하여 크기가 크다. 2. 쿠키는보다 전통적이고 구현하기 쉽지만 보안을 보장하기 위해주의해서 구성해야합니다.

세션 관련 XSS 공격으로부터 응용 프로그램을 보호하려면 다음 조치가 필요합니다. 1. 세션 쿠키를 보호하기 위해 Httponly 및 Secure 플래그를 설정하십시오. 2. 모든 사용자 입력에 대한 내보내기 코드. 3. 스크립트 소스를 제한하기 위해 컨텐츠 보안 정책 (CSP)을 구현하십시오. 이러한 정책을 통해 세션 관련 XSS 공격을 효과적으로 보호 할 수 있으며 사용자 데이터가 보장 될 수 있습니다.

PHP 세션 성능을 최적화하는 방법 : 1. 지연 세션 시작, 2. 데이터베이스를 사용하여 세션을 저장, 3. 세션 데이터 압축, 4. 세션 수명주기 관리 및 5. 세션 공유 구현. 이러한 전략은 높은 동시성 환경에서 응용의 효율성을 크게 향상시킬 수 있습니다.

THESESSION.GC_MAXLIFETIMESETTINGINSTTINGTINGSTINGTERMINESTERMINESTERSTINGSESSIONDATA, SETINSECONDS.1) IT'SCONFIGUDEDINPHP.INIORVIAINI_SET ()

PHP에서는 Session_Name () 함수를 사용하여 세션 이름을 구성 할 수 있습니다. 특정 단계는 다음과 같습니다. 1. Session_Name () 함수를 사용하여 Session_Name ( "my_session")과 같은 세션 이름을 설정하십시오. 2. 세션 이름을 설정 한 후 세션을 시작하여 세션을 시작하십시오. 세션 이름을 구성하면 여러 응용 프로그램 간의 세션 데이터 충돌을 피하고 보안을 향상시킬 수 있지만 세션 이름의 독창성, 보안, 길이 및 설정 타이밍에주의를 기울일 수 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)
