使用for循环创建一个String,然后使用cURL发布

时间:2014-01-10 10:28:45

标签: php curl

请帮助我,如果这是正确的方法,我怎么能使这个工作,如果不是你建议发布参数

$str = '';
for( $i = 11; $i <= 20; $i++ )
{
 $str .= $i . ' ';    
}
$ch = curl_init(); //http post to another server
curl_setopt($ch, CURLOPT_URL,"http://xxxx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=$username&password=$password&string=$str"); 

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
print_r($server_output);
curl_close ($ch);

2 个答案:

答案 0 :(得分:0)

如果您有权使用curl调用脚本,请尝试添加:

var_dump($_POST);

看看打印的内容。

我只是让你的代码更具可读性。 但它是正确的。应该有效。

尝试查看php_errors日志文件,看看它是否会触发。

<?php

$str = '';
for( $i = 11; $i <= 20; $i++ ) {
    $str .= $i . ' ';
}

$ch = curl_init(); //http post to another server
curl_setopt($ch, CURLOPT_URL           , 'http://xxxx');
curl_setopt($ch, CURLOPT_POST          , 1);
curl_setopt($ch, CURLOPT_POSTFIELDS    , 'username=' . $username . '&password=' . $password . '&string=' . $str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$server_output = curl_exec ($ch);

print_r($server_output);

curl_close($ch);

@Stoic在POSTFIELDS中传递数组确定Content-type header = multipart。可以改变回应。

答案 1 :(得分:0)

我了解您的代码是正确的,但您可以使用以下函数作为帮助程序:

<?php
$url  = "http://xxxx";
$str  = implode(" ", range(11,20));
$data = array("username" => $username, "password" => $password, "string" => $str);

$server_output = processURL($url, $data);
print_r($server_output);

function processURL($url, $data = array()){ 
    $ch=curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
    $response = curl_exec ($ch); 
    curl_close ($ch); 
    return $response; 
}

请注意,我确实理解使用rangefor循环慢一点,但我喜欢它的可读性和更清晰的代码:)