關於POST方式傳遞資料的問題
最近在研究怎麼用POST方式傳遞資料
我想得到的效果是,開啟網頁a,向一個網頁b傳遞一個字串
然後在網頁b上顯示這個字串。
在網上找到一份代碼,是這樣的
網頁a的代碼:
$uri = "http://localhost/handle.php";
// 參數數組
$data = array (
'name' => 'tanteng'
// 'password' => 'password'
);
$ch = curl_init ();
// print_r($ch);
curl_setopt ( $ch, CURLOPT_URL, $uri );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
$return = curl_exec ( $ch );
curl_close ( $ch );
print_r($return);
?>
網頁b的代碼
echo 'this is the posted data';
if(isset($_POST['name'])){
if(!empty($_POST['name'])){
echo '您好,',$_POST['name'].'!';
}
}
?>
在我電腦上實驗的結果是開啟網頁b只顯示 this is the posted data
而網頁a上顯示 您好,tanteng!
有誰能給我解釋下為什麼嗎?如果我想讓這句話在網頁b上顯示該怎麼做?
------解決思路----------------------
可以用數據庫或檔案儲存。
a.php
$uri = "http://localhost/handle.php";
// 參數數組
$data = array (
'name' => 'tanteng'
// 'password' => 'password'
);
$ch = curl_init ();
// print_r($ch);
curl_setopt ( $ch, CURLOPT_URL, $uri );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
$return = curl_exec ( $ch );
curl_close ( $ch );
print_r($return);
?>
handle.php
$name = isset($_POST['name'])? $_POST['name'] : '';
file_put_contents('tt.txt', $name, true);
echo 'success';
?>
b.php
echo 'this is the posted data';
if(file_exists('tt.txt')){
$name = file_get_contents('tt.txt');
if(!empty($name)){
echo '您好,',$name.'!';
}
}
?>