简体   繁体   English

有没有办法用特定的IP地址执行php脚本

[英]Is there a way to have a php script execute with a specific ip address

Is there way to have a php script that uses file_get_contents to utilize an ip address different than what the server's ip address is? 有没有办法使用php脚本使用file_get_contents来利用与服务器的IP地址不同的IP地址? We have 5 ip addresses and want to utilize a specific one for this purpose. 我们有5个IP地址,并希望为此使用一个特定的IP地址。

Yes, it's possible. 是的,有可能。 You have to configure the stream context you want to use though. 但是,您必须配置要使用的流上下文。

<?php
// context options
$ctxopts = array(
    'socket' => array(
        'bindto' => '192.168.0.100:0',
    ),
);

// create the context...
$context = stream_context_create($ctxopts);

// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);

You can get more info on http://php.net/manual/en/context.socket.php 您可以在http://php.net/manual/en/context.socket.php上获取更多信息。

Per the documentation that is easily accessible on php.net 根据可在php.net上轻松访问的文档

context
A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL.

stream_context_create()'s documentation explains the rest stream_context_create()的文档介绍了其余内容

$opts = array(
    'socket' => array(
        'bindto' => '123.123.123.123:0', // 0 for automatically determine port
    )
);

final code: 最终代码:

$opts = array(
    'socket' => array(
        'bindto' => '123.123.123.123:0', // 0 for automatically determine port
    )
);    
$stream = stream_context_create($ctxopts);
echo file_get_contents('http://www.website', false, $stream);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM