[英]Sending POST data without form
例如,我可以在不使用表單的情況下將字符串或另一條信息發送到 another.php 文件而不暴露它 [因此不是通過 GET 而是通過 POST 符合我所知道的]?
如果您不想要表單,可以使用AJAX發送POST請求。
使用jquery $ .post方法很簡單:
$.post('/foo.php', { key1: 'value1', key2: 'value2' }, function(result) {
alert('successfully posted key1=value1&key2=value2 to foo.php');
});
使用SESSION發送您的數據而不是發布。
session_start();
$_SESSION['foo'] = "bar";
在您收到請求的頁面上,如果您絕對需要POST數據(一些奇怪的邏輯),您可以在開頭執行此操作:
$_POST['foo'] = $_SESSION['foo'];
帖子數據的有效性與POST發送時的數據相同。
然后銷毀會話(或者如果您需要會話用於其他目的,則取消設置字段)。
銷毀會話或取消設置字段非常重要,因為與POST不同,SESSION將保持有效,直到您明確銷毀它或直到瀏覽器會話結束。 如果你不這樣做,你可以觀察到一些奇怪的結果。 例如:您使用sesson過濾某些數據。 用戶打開過濾器並獲取過濾數據。 過了一會兒,他回到頁面並希望重置過濾器,但事實並非如此:他仍然看到過濾后的數據。
看看你可以使用它們發送的功能的php文檔的php文檔。
fsockopen()
fputs()
或者只是使用類似Zend_Http_Client的類,它也基於套接字連接。
還找到了一個使用谷歌的簡潔例子 ...
只需使用: file_get_contents()
// building array of variables
$content = http_build_query(array(
'username' => 'value',
'password' => 'value'
));
// creating the context change POST to GET if that is relevant
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'content' => $content, )));
$result = file_get_contents('http://www.example.com/page.php', null, $context);
//dumping the reuslt
var_dump($result);
參考 :我對類似問題的回答:
我強烈建議在這種情況下使用 curl, file_get_content()
確實有效但並非始終有效,並且在某些應用程序中使用它可能會很麻煩。
盡管 curl 有不同的變體,具體取決於您要發送的內容和使用的方法,但這里是使用 curl 在沒有 HTML 表單的情況下發布數據的最常見方法。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/request_uri');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$post = array(
'data1' => 'value1',
'data2' => $value2
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
//do what you want with the responce
var_dump($result)
function redir(data) { document.getElementById('redirect').innerHTML = '<form style="display:none;" position="absolute" method="post" action="location.php"><input id="redirbtn" type="submit" name="value" value=' + data + '></form>'; document.getElementById('redirbtn').click(); }
<button onclick="redir('dataToBeSent');">Next Page</button> <div id="redirect"></div>
您可以使用此方法創建一個新的隱藏表單,當單擊一個按鈕[下一頁]時,其“數據”通過“發布”發送到“location.php”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.