如果您想从文件中的代码返回输出,只需对其进行 RESTful API 调用即可。这样,您可以将相同的代码文件用于 ajax 调用、REST API 或您的内部 PHP 代码。
它需要安装 cURL,但没有输出缓冲区或不包含,只需执行页面并返回到字符串中。
我会给你我写的代码。它适用于几乎所有 REST/Web 服务器(甚至适用于 Equifax):
$return = PostRestApi($url);
或者
$post = array('name' => 'Bob', 'id' => '12345');
$return = PostRestApi($url, $post, false, 6, false);
这是功能:
/**
* Calls a REST API and returns the result
*
* $loginRequest = json_encode(array("Code" => "somecode", "SecretKey" => "somekey"));
* $result = CallRestApi("https://server.com/api/login", $loginRequest);
*
* @param string $url The URL for the request
* @param array/string $data Input data to send to server; If array, use key/value pairs and if string use urlencode() for text values)
* @param array $header_array Simple array of strings (i.e. array('Content-Type: application/json');
* @param int $ssl_type Set preferred TLS/SSL version; Default is TLSv1.2
* @param boolean $verify_ssl Whether to verify the SSL certificate or not
* @param boolean $timeout_seconds Timeout in seconds; if zero then never time out
* @return string Returned results
*/
function PostRestApi($url, $data = false, $header_array = false,
$ssl_type = 6, $verify_ssl = true, $timeout_seconds = false) {
// If cURL is not installed...
if (! function_exists('curl_init')) {
// Log and show the error
$error = 'Function ' . __FUNCTION__ . ' Error: cURL is not installed.';
error_log($error, 0);
die($error);
} else {
// Initialize the cURL session
$curl = curl_init($url);
// Set the POST data
$send = '';
if ($data !== false) {
if (is_array($data)) {
$send = http_build_query($data);
} else {
$send = $data;
}
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $send);
}
// Set the default header information
$header = array('Content-Length: ' . strlen($send));
if (is_array($header_array) && count($header_array) > 0) {
$header = array_merge($header, $header_array);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
// Set preferred TLS/SSL version
curl_setopt($curl, CURLOPT_SSLVERSION, $ssl_type);
// Verify the server's security certificate?
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ($verify_ssl) ? 1 : 0);
// Set the time out in seconds
curl_setopt($curl, CURLOPT_TIMEOUT, ($timeout_seconds) ? $timeout_seconds : 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute the request
$result = curl_exec($curl);
// Close cURL resource, and free up system resources
curl_close($curl);
unset($curl);
// Return the results
return $result;
}
}