Вот функция, которая должна позволять вам использовать существующий код без изменений:
if (!function_exists('http_post_data')) {
function http_post_data ($url, $data, $options) {
// Construct the URL with the auth stripped out
$urlParts = parse_url($url);
$urlToUse = $urlParts['scheme'].'://'.$urlParts['host'];
if (isset($urlParts['port'])) $urlToUse .= ':'.$urlParts['port'];
$urlToUse .= $urlParts['path'];
if (isset($urlParts['query'])) $urlToUse .= '?'.$urlParts['query'];
// Convert headers to a format cURL will like
$headers = array();
if (isset($options['headers'])) {
foreach ($options['headers'] as $name => $val) {
$headers[] = "$name: $val";
}
}
// Initialise cURL with the modified URL
$ch = curl_init($urlToUse);
// We want the function to return the response as a string
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the method to POST and set the body data
curl_setopt ($ch, CURLOPT_POST, TRUE);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data); // Wrapping this in an array() is definitely wrong, given that the content-type is xml
// Set the auth details if specified
if (isset($urlParts['user'], $urlParts['pass'])) {
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); // It's probably best to allow any auth method, unless you know the server ONLY supports basic
curl_setopt($ch, CURLOPT_USERPWD, $urlParts['user'].':'.$urlParts['pass']); // The square brackets are not required and will be treated as part of the username/password
}
// Set any extra headers
if ($headers) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
// Send the request and return the result:
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
Эта функция реализует только те опции для http_post_data()
, которые вы использовали в исходном коде - она будетМожно было бы реализовать и другие функции с использованием cURL, но я не раздул приведенный выше код с их ненужными реализациями.Если проверка ошибок не выполняется, особенно с точки зрения проверки предоставленного URL, возможно, вы захотите добавить дополнительную очистку.
Эта функция заключена в if (!function_exists())
, чтобы вы могли разместить ее в своем коде.и распространяться где угодно.Он не будет вступать в конфликт с нативной функцией, где он доступен.