在页面之间传递全局帖子

时间:2018-04-03 06:56:07

标签: php post global-variables

考虑以下代码,让我知道如何使用PHP中的全局帖子。 虽然我通过在两个地方复制代码来运行此代码,但我需要访问已编写的代码。

我有一个文件abc.php

if (isset($_POST['test'])) {
    return 'hello test1';
} elseif(isset($_POST['test2'])){
    return 'hello test2';
} else {
    return "test3";
}

现在我有另一个文件efg.php

if (isset($_GET['hello'])) {
    //Here, I need content from abc.php 
}
/* More code... */

如何将POST从一个页面传递到另一个页面?

3 个答案:

答案 0 :(得分:0)

include "abc.php"; 
require "abc.php"; 
require_once "abc.php"; 

所有这些都可以在PHP中使用abc.php到另一个文件中!确保使用正确的路径。

也许

$file = $_SERVER['DOCUMENT_ROOT'] . "/folder/abc.php"; 
if(file_exists($file) !== false){
 require $file; 
}

取决于你如何设置它!

在abc.php上使用echo而不是return

答案 1 :(得分:0)

你不应该在全局范围内使用return,但你实际上可以得到这样的返回值:

if (isset($_GET['hello'])) {
    $value = include 'abc.php';
}

在官方文档中详细了解returnhttp://php.net/manual/en/function.return.php

答案 2 :(得分:0)

我假设您需要的是在脚本中请求另一个PHP页面并使用POST方法将测试数据传递给它。

最简单的方法是使用cURL

// full URL to your PHP script
$url = 'http://example.com/abc.php';

// what post fields?
$fields = array(
   'test' => '1st Value',
   'test2' => '2nd Value',
);

// encode your post data
$postvars = http_build_query($fields);

// open connection
$ch = curl_init();

// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);

// execute post
$result = curl_exec($ch);

// close connection
curl_close($ch);

归功于: https://stackoverflow.com/a/1217836/266076