bytes.php 字节编码类
/** * byte数组与字符串转化类 * @author * created on 2011-7-15 */class bytes { /** * 转换一个string字符串为byte数组 * @param $str 需要转换的字符串 * @param $bytes 目标byte数组 * @author zikie */ public static function getbytes($str) { $len = strlen($str); $bytes = array(); for($i=0;$i= 128){ $byte = ord($str[$i]) - 256; }else{ $byte = ord($str[$i]); } $bytes[] = $byte ; } return $bytes; } /** * 将字节数组转化为string类型的数据 * @param $bytes 字节数组 * @param $str 目标字符串 * @return 一个string类型的数据 */ public static function tostr($bytes) { $str = ''; foreach($bytes as $ch) { $str .= chr($ch); } return $str; } /** * 转换一个int为byte数组 * @param $byt 目标byte数组 * @param $val 需要转换的字符串 * @author zikie */ public static function integertobytes($val) { $byt = array(); $byt[0] = ($val & 0xff); $byt[1] = ($val >> 8 & 0xff); $byt[2] = ($val >> 16 & 0xff); $byt[3] = ($val >> 24 & 0xff); return $byt; } /** * 从字节数组中指定的位置读取一个integer类型的数据 * @param $bytes 字节数组 * @param $position 指定的开始位置 * @return 一个integer类型的数据 */ public static function bytestointeger($bytes, $position) { $val = 0; $val = $bytes[$position + 3] & 0xff; $val > 8 & 0xff); return $byt; } /** * 从字节数组中指定的位置读取一个short类型的数据。 * @param $bytes 字节数组 * @param $position 指定的开始位置 * @return 一个short类型的数据 */ public static function bytestoshort($bytes, $position) { $val = 0; $val = $bytes[$position + 1] & 0xff; $val = $val <p class="sycode"> </p> <p> </p> <p> socket.class.php socket赋值类</p> <p class="sycode"> </p><p class="sycode"> </p> <pre style="代码" class="precsshei"><?phpdefine ("CONNECTED", true);define("DISCONNECTED", false);/** * Socket class * * * @author Seven */Class Socket{ private static $instance; private $connection = null; private $connectionState = DISCONNECTED; private $defaultHost = "127.0.0.1"; private $defaultPort = 80; private $defaultTimeout = 10; public $debug = false; function __construct() { } /** * Singleton pattern. Returns the same instance to all callers * * @return Socket */ public static function singleton() { if (self::$instance == null || ! self::$instance instanceof Socket) { self::$instance = new Socket(); } return self::$instance; } /** * Connects to the socket with the given address and port * * @return void */ public function connect($serverHost=false, $serverPort=false, $timeOut=false) { if($serverHost == false) { $serverHost = $this->defaultHost; } if($serverPort == false) { $serverPort = $this->defaultPort; } $this->defaultHost = $serverHost; $this->defaultPort = $serverPort; if($timeOut == false) { $timeOut = $this->defaultTimeout; } $this->connection = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); if(socket_connect($this->connection,$serverHost,$serverPort) == false) { $errorString = socket_strerror(socket_last_error($this->connection)); $this->_throwError("Connecting to {$serverHost}:{$serverPort} failed.<br>Reason: {$errorString}"); }else{ $this->_throwMsg("Socket connected!"); } $this->connectionState = CONNECTED; } /** * Disconnects from the server * * @return True on succes, false if the connection was already closed */ public function disconnect() { if($this->validateConnection()) { socket_close($this->connection); $this->connectionState = DISCONNECTED; $this->_throwMsg("Socket disconnected!"); return true; } return false; } /** * Sends a command to the server * * @return string Server response */ public function sendRequest($command) { if($this->validateConnection()) { $result = socket_write($this->connection,$command,strlen($command)); return $result; } $this->_throwError("Sending command \"{$command}\" failed.<br>Reason: Not connected"); } public function isConn() { return $this->connectionState; } public function getUnreadBytes() { $info = socket_get_status($this->connection); return $info['unread_bytes']; } public function getConnName(&$addr, &$port) { if ($this->validateConnection()) { socket_getsockname($this->connection,$addr,$port); } } /** * Gets the server response (not multilined) * * @return string Server response */ public function getResponse() { $read_set = array($this->connection); while (($events = socket_select($read_set, $write_set = NULL, $exception_set = NULL, 0)) !== false) { if ($events > 0) { foreach ($read_set as $so) { if (!is_resource($so)) { $this->_throwError("Receiving response from server failed.<br>Reason: Not connected"); return false; }elseif ( ( $ret = @socket_read($so,4096,PHP_BINARY_READ) ) == false){ $this->_throwError("Receiving response from server failed.<br>Reason: Not bytes to read"); return false; } return $ret; } } } return false; } public function waitForResponse() { if($this->validateConnection()) { return socket_read($this->connection, 2048); } $this->_throwError("Receiving response from server failed.<br>Reason: Not connected"); return false; } /** * Validates the connection state * * @return bool */ private function validateConnection() { return (is_resource($this->connection) && ($this->connectionState != DISCONNECTED)); } /** * Throws an error * * @return void */ private function _throwError($errorMessage) { echo "Socket error: " . $errorMessage; } /** * Throws an message * * @return void */ private function _throwMsg($msg) { if ($this->debug) { echo "Socket message: " . $msg . "\n\n"; } } /** * If there still was a connection alive, disconnect it */ public function __destruct() { $this->disconnect(); }}?>
PacketBase.class.php 打包类
<?php /** * PacketBase class * * 用以处理与c++服务端交互的sockets 包 * * 注意:不支持宽字符 * * @author Seven <seven@qoolu.com> * */class PacketBase extends ContentHandler{ private $head; private $params; private $opcode; /**************************construct***************************/ function __construct() { $num = func_num_args(); $args = func_get_args(); switch($num){ case 0: //do nothing 用来生成对象的 break; case 1: $this->__call('__construct1', $args); break; case 2: $this->__call('__construct2', $args); break; default: throw new Exception(); } } //无参数 public function __construct1($OPCODE) { $this->opcode = $OPCODE; $this->params = 0; } //有参数 public function __construct2($OPCODE, $PARAMS) { $this->opcode = $OPCODE; $this->params = $PARAMS; } //析构 function __destruct() { unset($this->head); unset($this->buf); } //打包 public function pack() { $head = $this->MakeHead($this->opcode,$this->params); return $head.$this->buf; } //解包 public function unpack($packet,$noHead = false) { $this->buf = $packet; if (!$noHead){ $recvHead = unpack("S2hd/I2pa",$packet); $SD = $recvHead[hd1];//SD $this->contentlen = $recvHead[hd2];//content len $this->opcode = $recvHead[pa1];//opcode $this->params = $recvHead[pa2];//params $this->pos = 12;//去除包头长度 if ($SD != 21316) { return false; } }else { $this->pos = 0; } return true; } public function GetOP() { if ($this->buf) { return $this->opcode; } return 0; } /************************private***************************/ //构造包头 private function MakeHead($opcode,$param) { return pack("SSII","SD",$this->TellPut(),$opcode,$param); } //用以模拟函数重载 private function __call($name, $arg) { return call_user_func_array(array($this, $name), $arg); } /***********************Uitl***************************/ //将16进制的op转成10进制 static function MakeOpcode($MAJOR_OP, $MINOR_OP) { return ((($MAJOR_OP & 0xffff) buf = ""; $this->contentlen = 0; $this->pos = 0; } function __destruct() { unset($this->buf); } public function PutInt($int) { $this->buf .= pack("i",(int)$int); } public function PutUTF($str) { $l = strlen($str); $this->buf .= pack("s",$l); $this->buf .= $str; } public function PutStr($str) { return $this->PutUTF($str); } public function TellPut() { return strlen($this->buf); } /*******************************************/ public function GetInt() { //$cont = substr($out,$l,4); $get = unpack("@".$this->pos."/i",$this->buf); if (is_int($get[1])){ $this->pos += 4; return $get[1]; } return 0; } public function GetShort() { $get = unpack("@".$this->pos."/S",$this->buf); if (is_int($get[1])){ $this->pos += 2; return $get[1]; } return 0; } public function GetUTF() { $getStrLen = $this->GetShort(); if ($getStrLen > 0) { $end = substr($this->buf,$this->pos,$getStrLen); $this->pos += $getStrLen; return $end; } return ''; } /***************************/ public function GetBuf() { return $this->buf; } public function SetBuf($strBuf) { $this->buf = $strBuf; } public function ResetBuf(){ $this->buf = ""; $this->contentlen = 0; $this->pos = 0; }}?>
格式
struct header{int type; // 消息类型int length; // 消息长度}struct MSG_Q2R2DB_PAYRESULT{int serialno; int openid; char payitem[512];int billno; int zoneid;int providetype; int coins; }调用的方法,另外需require两个php文件,一个是字节编码类,另外一个socket封装类,其实主要看字节编码类就可以了!
调用测试
public function index() { $socketAddr = "127.0.0.1"; $socketPort = "10000"; try { $selfPath = dirname ( __FILE__ ); require ($selfPath . "/../Tool/Bytes.php"); $bytes = new Bytes (); $payitem = "sdfasdfasdfsdfsdfsdfsdfsdfsdf"; $serialno = 1; $zoneid = 22; $openid = "CFF47C448D4AA2069361567B6F8299C2"; $billno = 1; $providetype = 1; $coins = 1; $headType = 10001; $headLength = 56 + intval(strlen($payitem )); $headType = $bytes->integerToBytes ( intval ( $headType ) ); $headLength = $bytes->integerToBytes ( intval ( $headLength ) ); $serialno = $bytes->integerToBytes ( intval ( $serialno ) ); $zoneid = $bytes->integerToBytes ( intval ( $zoneid ) ); $openid = $bytes->getBytes( $openid ); $payitem_len = $bytes->integerToBytes ( intval ( strlen($payitem) ) ); $payitem = $bytes->getBytes($payitem); $billno = $bytes->integerToBytes ( intval ( $billno ) ); $providetype = $bytes->integerToBytes ( intval ( $providetype ) ); $coins = $bytes->integerToBytes ( intval ( $coins ) ); $return_betys = array_merge ($headType , $headLength , $serialno , $zoneid , $openid,$payitem_len ,$payitem,$billno,$providetype,$coins); $msg = $bytes->toStr ($return_betys); $strLen = strlen($msg); $packet = pack("a{$strLen}", $msg); $pckLen = strlen($packet); $socket = Socket::singleton (); $socket->connect ( $socketAddr, $socketPort ); //连服务器 $sockResult = $socket->sendRequest ( $packet); // 将包发送给服务器 sleep ( 3 ); $socket->disconnect (); //关闭链接 } catch ( Exception $e ) { var_dump($e); $this->log_error("pay order send to server".$e->getMessage()); } }

PHP에서, 특성은 방법 재사용이 필요하지만 상속에 적합하지 않은 상황에 적합합니다. 1) 특성은 클래스에서 다중 상속의 복잡성을 피할 수 있도록 수많은 방법을 허용합니다. 2) 특성을 사용할 때는 대안과 키워드를 통해 해결할 수있는 방법 충돌에주의를 기울여야합니다. 3) 성능을 최적화하고 코드 유지 보수성을 향상시키기 위해 특성을 과도하게 사용해야하며 단일 책임을 유지해야합니다.

의존성 주입 컨테이너 (DIC)는 PHP 프로젝트에 사용하기위한 객체 종속성을 관리하고 제공하는 도구입니다. DIC의 주요 이점에는 다음이 포함됩니다. 1. 디커플링, 구성 요소 독립적 인 코드는 유지 관리 및 테스트가 쉽습니다. 2. 유연성, 의존성을 교체 또는 수정하기 쉽습니다. 3. 테스트 가능성, 단위 테스트를 위해 모의 객체를 주입하기에 편리합니다.

SplfixedArray는 PHP의 고정 크기 배열로, 고성능 및 메모리 사용이 필요한 시나리오에 적합합니다. 1) 동적 조정으로 인한 오버 헤드를 피하기 위해 생성 할 때 크기를 지정해야합니다. 2) C 언어 배열을 기반으로 메모리 및 빠른 액세스 속도를 직접 작동합니다. 3) 대규모 데이터 처리 및 메모리에 민감한 환경에 적합하지만 크기가 고정되어 있으므로주의해서 사용해야합니다.

PHP는 $ \ _ 파일 변수를 통해 파일 업로드를 처리합니다. 보안을 보장하는 방법에는 다음이 포함됩니다. 1. 오류 확인 확인, 2. 파일 유형 및 크기 확인, 3 파일 덮어 쓰기 방지, 4. 파일을 영구 저장소 위치로 이동하십시오.

JavaScript에서는 NullCoalescingOperator (??) 및 NullCoalescingAssignmentOperator (?? =)를 사용할 수 있습니다. 1. 2. ??= 변수를 오른쪽 피연산자의 값에 할당하지만 변수가 무효 또는 정의되지 않은 경우에만. 이 연산자는 코드 로직을 단순화하고 가독성과 성능을 향상시킵니다.

CSP는 XSS 공격을 방지하고 리소스로드를 제한하여 웹 사이트 보안을 향상시킬 수 있기 때문에 중요합니다. 1.CSP는 HTTP 응답 헤더의 일부이며 엄격한 정책을 통해 악의적 인 행동을 제한합니다. 2. 기본 사용법은 동일한 원점에서 자원을로드 할 수있는 것입니다. 3. 고급 사용량은 특정 도메인 이름을 스크립트와 스타일로드 할 수 있도록하는 것과 같은보다 세밀한 전략을 설정할 수 있습니다. 4. Content-Security Policy 보고서 전용 헤더를 사용하여 CSP 정책을 디버그하고 최적화하십시오.

HTTP 요청 방법에는 각각 리소스를 확보, 제출, 업데이트 및 삭제하는 데 사용되는 Get, Post, Put and Delete가 포함됩니다. 1. GET 방법은 리소스를 얻는 데 사용되며 읽기 작업에 적합합니다. 2. 게시물은 데이터를 제출하는 데 사용되며 종종 새로운 리소스를 만드는 데 사용됩니다. 3. PUT 방법은 리소스를 업데이트하는 데 사용되며 완전한 업데이트에 적합합니다. 4. 삭제 방법은 자원을 삭제하는 데 사용되며 삭제 작업에 적합합니다.

HTTPS는 HTTP를 기반으로 보안 계층을 추가하는 프로토콜로, 주로 암호화 된 데이터를 통해 사용자 개인 정보 및 데이터 보안을 보호합니다. 작업 원칙에는 TLS 핸드 셰이크, 인증서 확인 및 암호화 된 커뮤니케이션이 포함됩니다. HTTP를 구현할 때는 인증서 관리, 성능 영향 및 혼합 콘텐츠 문제에주의를 기울여야합니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

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

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

뜨거운 주제



