将参数发送到URL并从该页面获取输出

时间:2010-11-30 13:44:22

标签: php

我有2页说abc.phpdef.php。当abc.phpdef.php发送2个值[id和name]时,会显示“收到的值”消息。现在,如何在不使用def.php中的表单的情况下将这两个值发送到abc.php,并从def.php获取“已接收的值”消息?我无法使用表单,因为当用户经常访问abc.php文件时,脚本应自动生效并从def.php获取“收到的值”消息。请参阅我的示例代码:

abc.php

 <?php 
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;     
 ?>

def.php

 <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>

有没有善良的心可以帮助我解决这个问题?

5 个答案:

答案 0 :(得分:4)

首先下定决心:你想要GET或POST参数。

您的脚本当前希望它们是GET参数,因此您只需使用以下命令调用它(前提是已启用URL包装器):

$f = file_get_contents('http://your.domain/def.php?id=123&name=blahblah');

要在其他答案中使用此处发布的curl示例,您必须更改脚本以使用$ _POST而不是$ _GET。

答案 1 :(得分:3)

你可以尝试没有cURL(我没试过):

POSTing data without cURL extension

粘贴的复制件
// Your POST data
$data = http_build_query(array(
    'param1' => 'data1',
    'param2' => 'data2'
));

// Create HTTP stream context
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $data
    )
));

// Make POST request
$response = file_get_contents('http://example.com', false, $context);

答案 2 :(得分:2)

取自php.net的examples page

// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "example.com/abc.php");

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);  

编辑:发送参数

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( tch, CURLOPT_POSTFIELDS, array('var1=foo', 'var2=bar'));

答案 3 :(得分:1)

使用CURLZend_Http_Client

答案 4 :(得分:0)

<?php
$method = 'GET'; //change to 'POST' for post method
$url = 'http://localhost/browse/';
$data = array(
    'manufacturer' => 'kraft',
    'packaging_type' => 'bag'
    );

if ($method == 'POST'){
//Make POST request
    $data = http_build_query($data);
    $context = stream_context_create(array(
        'http' => array(
            'method' => "$method",
            'header' => 'Content-Type: application/x-www-form-urlencoded',
            'content' => $data)
        )
    );
    $response = file_get_contents($url, false, $context);
}
else {
// Make GET request
    $data = http_build_query($data, '', '&');
    $response = file_get_contents($url."?".$data, false);
}
echo $response;
?>

受到trix's answer的启发,我决定扩展该代码以满足GET和POST方法。