简体   繁体   中英

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? We have 5 ip addresses and want to utilize a specific one for this purpose.

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

Per the documentation that is easily accessible on 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

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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