PHP SSL stream_socket_client 不会使用创建的 $context

标签 php ssl stream-socket-client

我完全失望了。我正在连接到 ssl 服务器,并且直接连接运行良好,但是当我尝试添加流上下文以使用代理或 socks5 时,socket 不会使用它并且直接连接到这些 ssl://服务器时效果很好,我我正在通过查看 127.0.0.1 代理服务器日志进行检查 - 甚至没有连接尝试。另外,我可以使用 socks5://http 代理选项将流包装到 socks5 服务器吗?

$ctx = stream_context_create( array(
                      "http" => array(
                          "timeout"         => 15,
                          "proxy"           => "tcp://127.0.0.1:3128",
                          "request_fulluri" => TRUE,
                       ),
                      "ssl"  => array(
                          "SNI_enabled" => FALSE,
                      )
              ) );

try
{
    $socket = stream_socket_client( "ssl://google.com:443", 
        $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $ctx );
}
catch ( Exception $e )
{
    die( $e->getMessage() );
}

if ( $socket === FALSE )
{
    echo "bad socket";
}

fwrite( $socket, "GET /\n" );
echo fread( $socket, 8192 );

// Here I am connected DIRECTLY, not thru proxy. WHY ???

// But this call succesfully uses context
echo file_get_contents("https://google.com", 0, $ctx);

最佳答案

我找到了正确的方法。这可以完美地连接到 socks5 服务器。

$desthost = "google.com";
$port     = 443;
$conflag  = STREAM_CLIENT_CONNECT;

try
{
    $socket = stream_socket_client( "tcp://127.0.0.1:1080", $errno, $errstr, 15, $conflag );

    fwrite( $socket, pack( "C3", 0x05, 0x01, 0x00 ) );
    $server_status = fread( $socket, 2048 );
    if ( $server_status == pack( "C2", 0x05, 0x00 ) )
    {
        // Connection succeeded
    }
    else
    {
        die( "SOCKS Server does not support this version and/or authentication method of SOCKS.\r\n" );
    }

    fwrite( $socket, pack( "C5", 0x05, 0x01, 0x00, 0x03, strlen( $desthost ) ) . $desthost . pack( "n", $port ) );
    $server_buffer = fread( $socket, 10 );

    if ( ord( $server_buffer[0] ) == 5 && ord( $server_buffer[1] ) == 0 && ord( $server_buffer[2] ) == 0 )
    {
        // Connection succeeded
    }
    else
    {
        die( "The SOCKS server failed to connect to the specificed host and port. ( " . $desthost . ":" . $port . " )\r\n" );
    }

    stream_socket_enable_crypto( $socket, TRUE, STREAM_CRYPTO_METHOD_SSLv23_CLIENT );
}
catch ( Exception $e )
{
    die( $e->getMessage() );
}

if ( $socket === FALSE )
{
    die( "bad socket" );
}

fwrite( $socket, "GET /\n" );
echo fread( $socket, 8192 );

关于PHP SSL stream_socket_client 不会使用创建的 $context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30691573/

相关文章:

C#、Metro、Stream Socket、SSL 不可信主机、Squid

ios - SSL 操作失败并显示代码,同时向 iOS 设备发送推送通知

php - 数据表 : How to make a page load faster?

php - 为什么我的 php 脚本不能生成整个 word doc 文件?

php - iOS 使用 SSL (HTTPS) 发送 POST

powershell - 如何使用 Powershell 和 PKI 进行 LDAP 查询

php - 如何使用 Mozilla CA 证书作为 ssl 客户端证书

php - 如果使用 PHP 找不到,则使用默认值进行正则表达式分组

php - 在页面加载时隐藏文本输入字段?

c - OpenSSL 错误 : unable to verify the first certificate