pixelbrackets / api.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Simple request response script |
* |
* Point you cURL request to this script to see all incoming data |
*/ |
echo ‘*API*’ . PHP_EOL ; |
echo ‘Request Time: ‘ . time() . PHP_EOL ; |
echo ‘Request Method: ‘ . print_r( $ _SERVER [ ‘REQUEST_METHOD’ ], true ) . PHP_EOL ; |
if ( FALSE === empty( $ _SERVER [ ‘HTTP_X_HTTP_METHOD_OVERRIDE’ ])) |
echo ‘Request Header Method: ‘ . print_r( $ _SERVER [ ‘HTTP_X_HTTP_METHOD_OVERRIDE’ ], true ) . PHP_EOL ; |
> |
echo ‘Server Data: ‘ . print_r( $ _SERVER , true ) . PHP_EOL ; |
echo ‘Request Files: ‘ . print_r( $ _FILES , true ) . PHP_EOL ; |
echo ‘Request Data: ‘ . PHP_EOL ; |
// …Will only work with GET query parameters & POST form parameters |
echo ‘Request params: ‘ . print_r( $ _REQUEST , true ) . PHP_EOL ; |
// …Other methods like DELETE & PUT, and request body content types like JSON |
// are not converted into PHP superglobals automatically! Read the input stream instead. |
// Note: The input stream may be accessed once only! |
parse_str(file_get_contents( ‘php://input’ ), $ _INPUT ); |
echo ‘Input Stream: ‘ . print_r( $ _INPUT , true ) . PHP_EOL ; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Simple cURL request script |
* |
* Test if cURL is available, send request, print response |
* |
* php curl.php |
*/ |
if (!function_exists( ‘curl_init’ )) |
die( ‘cURL not available!’ ); |
> |
$ curl = curl_init(); |
// or use https://httpbin.org/ for testing purposes |
curl_setopt( $ curl , CURLOPT_URL , ‘https://my-own-domain.example.com/api.php’ ); |
curl_setopt( $ curl , CURLOPT_FAILONERROR , true ); |
curl_setopt( $ curl , CURLOPT_FOLLOWLOCATION , true ); |
curl_setopt( $ curl , CURLOPT_RETURNTRANSFER , true ); |
//// Require fresh connection |
//curl_setopt($curl, CURLOPT_FRESH_CONNECT, true); |
//// Send POST request instead of GET and transfer data |
//$postData = array( |
// ‘name’ => ‘John Doe’, |
// ‘submit’ => ‘1’ |
//); |
//curl_setopt($curl, CURLOPT_POST, true); |
//curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData)); |
//// Use a different request method |
//curl_setopt($curl, CURLOPT_CUSTOMREQUEST, ‘DELETE’); |
//// If the target does not accept custom HTTP methods |
//// then use a regular POST request and a custom header variable |
//curl_setopt($curl, CURLOPT_HTTPHEADER, array(‘X-HTTP-Method-Override: PUT’)); |
//// Note: PHP only converts data of GET queries and POST form requests into |
//// convenient superglobals (»$_GET« & »$_POST«) — To read the incoming |
//// cURL request data you need to access PHPs input stream instead |
//// using »parse_str(file_get_contents(‘php://input’), $_INPUT);« |
//// Send JSON body via POST request |
//$postData = array( |
// ‘name’ => ‘John Doe’, |
// ‘submit’ => ‘1’ |
//); |
//curl_setopt($curl, CURLOPT_POST, true); |
//curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postData)); |
//// Set headers to send JSON to target and expect JSON as answer |
//curl_setopt($curl, CURLOPT_HTTPHEADER, array(‘Content-Type:application/json’, ‘Accept:application/json’)); |
//// As said above, the target script needs to read `php://input`, not `$_POST`! |
//// Timeout in seconds |
//curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0); |
//curl_setopt($curl, CURLOPT_TIMEOUT, 10); |
//// Dont verify SSL certificate (eg. self-signed cert in testsystem) |
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); |
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); |
$ output = curl_exec( $ curl ); |
if ( $ output === FALSE ) |
echo ‘An error has occurred: ‘ . curl_error( $ curl ) . PHP_EOL ; |
> |
else |
echo $ output ; |
> |
PHP: Check if cURL is enabled.
This is a short guide on how to programmatically check whether cURL is enabled as a PHP extension or not. By checking to see if cURL is enabled, you can make your PHP code more portable by designing a fallback.
There are three popular approaches to this kind of check.
Does curl_init exist as a function?
The function curl_init allows us to initialize a cURL session. If it does not exist, then we can presume that the cURL module has not been loaded.
if(function_exists('curl_init') === false)< //curl_init is not defined //cURL not enabled >
In the code above, we used the PHP function function_exists to test whether curl_init is defined or not. If the function is not defined, we can presume that cURL has not been enabled and/or installed.
If curl_init is defined, then function_exists will return a boolean TRUE value.
Get loaded extensions.
Another approach is to use the PHP function get_loaded_extensions, which will return an array of all the PHP extensions / modules that have been loaded.
//Check if "curl" can be found in the array of loaded extensions. if(in_array('curl', get_loaded_extensions())) < //cURL module has been loaded >else< //It has not been loaded. Use a fallback. >
In the example above, we simply searched the array returned by get_loaded_extensions for the string “curl”. If the string “curl” cannot be found inside this array, then the extension has not been loaded and we can tell our code to use a fallback.
Yet another alternative is to use the function extension_loaded like so:
You can choose which approach you think is best, as they all accomplish the same thing and the performance differences are pretty negligible at best.
Fallback.
If you are looking for a fallback to use when the cURL module has not been enabled, then you can check out the following guides that I wrote:
Hopefully, you found this guide to be useful!
как проверить, включен ли curl
См. Руководство по написанию function , поместите туда однострочник, замените echo на return и вырежьте тройник.
7 ответов
Просто верните существующий чек из function.
Это работает и принимается, но приведенные ниже ответы — это то, что я бы посчитал менее хакерским и более понятным для кого-то другого, читающего код. Если я прочитаю это, я могу подумать, что вы специально проверяете, можете ли вы найти версию curl, а не проверяете, загружен ли curl. extension_loaded(‘curl’) гораздо более прямой.
else < return false; >> // Ouput text to user based on test if (_is_curl_installed()) < echo "cURL is installed on this server"; > else < echo "cURL is NOT installed on this server"; > ?>
var_dump(extension_loaded('curl'));
function_exists возвращает значение true или false . Вы можете просто вернуть его возвращаемое значение. Там нет необходимости для 4 дополнительных строк кода, для этого один лайнер. Кроме того, ваша функция не имеет конца > !
согласен с накладными расходами в коде, но у функции действительно есть конец> в виде одной строки, если операторам else не нужны фигурные скобки. Но, возможно, плохой отступ заставил вас совершить эту ошибку.
Вы всегда можете создать новую страницу и использовать phpinfo() . Прокрутите страницу вниз до секции curl и посмотрите, включена ли она.
Всегда лучше использовать универсальную функцию повторного использования в вашем проекте, которая возвращает, загружается ли расширение. Вы можете использовать следующую функцию для проверки —
function isExtensionLoaded($extension_name)
echo isExtensionLoaded('curl'); echo isExtensionLoaded('gd');
Предположим, вы работаете в большом проекте и хотите проверить вышеуказанное условие более 30-40 раз. Затем вам нужно написать вручную от 30 до 40 раз, и внезапно вы получили требование, что вам нужно проверить какое-то условие, прежде чем в это время вам нужно будет выполнить поиск и поместить условие во все 30 — 40 мест в вашем проекте. Вместо этого, если у вас была функция многократного использования, вы можете поместить это условие в функцию и избежать лишних затрат при поиске, замене или добавлении кода.
Вот для чего нужны инструменты рефакторинга. Но по сути: ввод кода, о котором вы не знаете наверняка, что это необходимо, я бы посчитал недостатком. Поэтому причина, по которой вы называете это причина, по моему мнению, не делать этого.
Отличная идея. Я начал оборачивать все нативные функции php. Я собрал их в библиотеке. Кто-нибудь заинтересован?