0

PHP's file_get_contents works fine while not inside of a function. However after moving it to a function and calling that function without any other changes the code stops working.

This (outside of a function) works...

$cpuser = 'exampl';
$cppass = 'PASSWORD';
$cpdomain = 'example.com';
$cpskin = 'darnkids';
$emailname = 'darnkids';
$emaildomain = 'example.com';
$password = 'PASSWORD';
$quota = '0';

$result1 = file_get_contents("https://$cpuser:$cppass@$cpdomain:2083/frontend/$cpskin/mail/doaddpop.html?email=$emailname&domain=$emaildomain&password=$password&quota=$quota");
echo $result1;

This same code (inside of a function) does not work...

$cpuser = 'exampl';
$cppass = 'PASSWORD';
$cpdomain = 'example.com';
$cpskin = 'darnkids';
$emailname = 'darnkids';
$emaildomain = 'example.com';
$password = 'PASSWORD';
$quota = '0';

function account_create()
{
 $result1 = file_get_contents("https://$cpuser:$cppass@$cpdomain:2083/frontend/$cpskin/mail/doaddpop.html?email=$emailname&domain=$emaildomain&password=$password&quota=$quota");
 echo $result1;
}

account_create();

I need to be able to capture the response regardless of what it is. Why is file_get_contents not working while inside a function and how do I get it to work inside of a function?

4

3 回答 3

3

这与file_get_contents(). 该函数在其范围内没有这些全局变量。

您需要使用global关键字或$GLOBALS数组使它们可用,或者更好的是,将它们限定为您的函数。

于 2013-06-15T00:27:38.377 回答
1

当您将对 file_get_contents 的调用移动到函数中时,您用于定义文件名的变量是本地版本,它们未在您的函数中定义。将变量移动到函数中,将它们作为参数传递。

于 2013-06-15T00:28:43.830 回答
1

正如上面的@Alex 所说,全局变量不可用。如果您不想定义全局变量(无论出于何种原因),只需确保您的函数将所有数据包含在您的第一个代码段中。像这样的东西。

function account_create(){
$cpuser = 'exampl';
$cppass = 'PASSWORD';
$cpdomain = 'example.com';
$cpskin = 'darnkids';
$emailname = 'darnkids';
$emaildomain = 'example.com';
$password = 'PASSWORD';
$quota = '0';
$result1 = file_get_contents("https://$cpuser:$cppass@$cpdomain:2083/frontend/$cpskin/mail/doaddpop.html?email=$emailname&domain=$emaildomain&password=$password&quota=$quota");
 echo $result1;
}

account_create();

如果这对您的用例不起作用,您始终可以将部分或全部数据传递给函数。如...

function account_create($cp_user, $cppass){
    ...
}

account_create('example1', 'PASSWORD');

有很多选择可供您使用。希望这有点帮助。

于 2013-06-15T00:36:09.823 回答