I try PHP Post Request inside a POST Request thinking it might be useful for me. My code is given below:
$sub_req_url = "http://localhost/index1.php";
$ch = curl_init($sub_req_url);
$encoded = '';
// include GET as well as POST variables; your needs may vary.
foreach($_GET as $name => $value) {
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
foreach($_POST as $name => $value) {
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_exec($ch);
curl_close($ch);
from the index.php
file and index2.php
is another file in the same directory and when I open the page I get the following error in my error.log
file:
[Sat Dec 18 15:24:53 2010] [error] [client ::1] PHP Fatal error: Call to undefined function curl_init() in /var/www/testing1/index.php on line 5
What I want to do is to have a reservation form that send post request. Then I want to process post values and send again the post request to paypal.
Uwe Keim
39k56 gold badges175 silver badges289 bronze badges
asked Dec 18, 2010 at 9:45
Santosh LinkhaSantosh Linkha
14.2k17 gold badges77 silver badges115 bronze badges
3
You need to install CURL support for php.
In Ubuntu you can install it via
sudo apt-get install php5-curl
If you’re using apt-get then you won’t need to edit any PHP configuration, but you will need to restart your Apache.
sudo /etc/init.d/apache2 restart
If you’re still getting issues, then try and use phpinfo() to make sure that CURL is listed as installed. (If it isn’t, then you may need to open another question, asking why your packages aren’t installing.)
There is an installation manual in the PHP CURL documentation.
Shane
9952 gold badges10 silver badges30 bronze badges
answered Dec 18, 2010 at 9:48
7
For Windows, if anybody is interested, uncomment the following line (by removing the from php.ini
;extension=php_curl.dll
Restart apache server.
answered Jun 30, 2013 at 15:39
KandaKanda
2793 silver badges6 bronze badges
3
For Ubuntu:
add extension=php_curl.so
to php.ini to enable, if necessary. Then sudo service apache2 restart
this is generally taken care of automatically, but there are situations — eg, in shared development environments — where it can become necessary to re-enable manually.
The thumbprint will match all three of these conditions:
- Fatal Error on curl_init() call
- in php_info, you will see the curl module author (indicating curl is installed and available)
- also in php_info, you will see no curl config block (indicating curl wasn’t loaded)
answered Mar 15, 2015 at 13:28
Kevin ArdKevin Ard
5944 silver badges12 bronze badges
In my case, in Xubuntu, I had to install libcurl3 libcurl3-dev libraries. With this command everything worked:
sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
answered Jan 30, 2015 at 17:05
lightbytelightbyte
5564 silver badges10 bronze badges
Just adding my answer for the case where there are multiple versions of PHP installed in your system, and you are sure that you have already installed the php-curl
package, and yet Apache is still giving you the same error.
curl_init() undefined even if php-curl is enabled in Php 7.
answered Feb 18, 2017 at 5:33
ultrajohnultrajohn
2,4973 gold badges30 silver badges56 bronze badges
To fix this bug, I did:
- In
php.ini
file, uncomment this line:extension=php_curl.dll
- In
php.ini
file, uncomment this line:extension_dir = "ext"
- I restarted NETBEANS, as I was using Built-in server
JasonMArcher
13.8k22 gold badges56 silver badges52 bronze badges
answered Oct 31, 2014 at 17:17
1
I got this error using PHP7 / Apache 2.4 on a windows platform. curl_init
worked from CLI but not with Apache 2.4. I resolved it by adding LoadFile
directives for libeay32.dll and ssleay32.dll:
LoadFile "C:/path/to/Php7/libeay32.dll"
LoadFile "C:/path/to/Php7/ssleay32.dll"
LoadFile "C:/path/to/Php7/php7ts.dll"
LoadModule php7_module "C:/path/to/Php7/php7apache2_4.dll"
answered Feb 8, 2016 at 11:12
fishbonefishbone
3,0412 gold badges36 silver badges48 bronze badges
This answer is for https request:
Curl doesn’t have built-in root certificates (like most modern browser do). You need to explicitly point it to a cacert.pem file:
curl_setopt($ch, CURLOPT_CAINFO, '/path/to/cert/file/cacert.pem');
Without this, curl cannot verify the certificate sent back via ssl. This same root certificate file can be used every time you use SSL in curl.
You can get the cacert.pem file here: http://curl.haxx.se/docs/caextract.html
Reference PHP cURL Not Working with HTTPS
answered Feb 17, 2017 at 8:58
Amit GargAmit Garg
3,8271 gold badge29 silver badges35 bronze badges
Step 1 :
C:/(path to php folder)/php.ini
enable extension=php_curl.dll
(remove the ;
at the end of the line)
Step 2 :
Add this to Apache/conf/httpd.conf
(libeay32.dll, ssleay32.dll, libssh2.dll find directly in php7 folder)
# load curl and open ssl libraries
LoadFile "C:/(path to php folder)/libeay32.dll"
LoadFile "C:/(path to php folder)/ssleay32.dll"
LoadFile "C:/(path to php folder)/libssh2.dll"
il_raffa
5,075121 gold badges32 silver badges34 bronze badges
answered Apr 10, 2018 at 7:24
1
On newer versions of PHP on Windows, like PHP 7.x, the corresponding configuration lines suggested on previous answers here, have changed. You need to uncomment (remove the ; at the beginning of the line) the following line:
extension_dir = "ext"
extension=curl
Uwe Keim
39k56 gold badges175 silver badges289 bronze badges
answered Aug 18, 2020 at 2:02
VitoxVitox
3,61425 silver badges29 bronze badges
1
(Trying to get Curl working via PHP and Apache on Windows…)
I kept getting an error saying:
Call to undefined function ‘curl_init()’
I made sure I had enabled curl with this line in my php.ini file:
extension=php_curl.dll
I made sure the extension_dir variable was being set properly, like this:
extension_dir = «ext»
I was doing everything everyone else said on the forums and curl was not showing up in my call to phpinfo(), and I kept getting that same error from above.
Finally I found out that Apache by default looks for php.ini in the C:Windows folder. I had been changing php.ini in my PHP installation folder. Once I copied my php.ini into C:Windows, everything worked.
Took me forever to figure that out, so thought I’d post in case it helps someone else.
answered Jul 4, 2014 at 3:50
jessejuicerjessejuicer
1073 silver badges10 bronze badges
For PHP 7 and Windows x64
libeay32.dll, libssh2.dll and ssleay32.dll should not be in apache/bin and should only exist in php directory and add php directory in system environment variable. This work for me.
Obvisouly in php.ini you should have enable php_curl.dll as well.
answered Mar 17, 2018 at 19:14
Wasim A.Wasim A.
9,54021 gold badges90 silver badges119 bronze badges
1
RusAlex answer is right in that for Apache you have to install and enable curl and restart your apache service:
sudo apt-get install php5-curl
sudo service apache2 restart
On my Ubuntu Server with nginx and php5-fpm I however ran into the following problem. I had to restart nginx and php5-fpm like so:
sudo service nginx restart
sudo service php5-fpm restart
But I had non-working php5-fpm processes hanging around, which apparently is a bug in ubuntu https://bugs.launchpad.net/ubuntu/+source/php5/+bug/1242376
So I had to kill all idle php5-fpm processes to able to restart php5-fpm so that the curl module is actually loaded
sudo kill <Process Id of php5-fpm Process)
answered Jul 20, 2014 at 2:15
Pascal KleinPascal Klein
23k24 gold badges81 silver badges119 bronze badges
function curl_int();
cause server error,install sudo apt-get install php5-curl
restart apache2 server .. it will work like charm
answered Mar 12, 2016 at 8:21
For linux you can install it via
sudo apt-get install php5-curl
For Windows(removing the from php.ini
;extension=php_curl.dll
Restart apache server.
answered May 13, 2019 at 8:31
On Ubuntu 18.04 these two commands solve my this problem.
sudo apt-get install php5.6-curl //install curl for php 5.6
sudo service apache2 restart //restart apache
answered Jun 21, 2019 at 10:35
Seems you haven’t installed the Curl on your server.
Check the PHP version of your server and run the following command to install the curl.
sudo apt-get install php7.2-curl
Then restart the apache service by using the following command.
sudo service apache2 restart
Replace 7.2 with your PHP version.
answered Sep 16, 2019 at 8:39
Varun P VVarun P V
1,04112 silver badges29 bronze badges
I also faced this issue. My Operating system is Ubuntu 18.04 and my PHP version is PHP 7.2.
Here’s how I solved it:
Install CURL on Ubuntu Server:
sudo apt-get install curl
Add the PHP CURL repository below to your sources list:
sudo add-apt-repository ppa:ondrej/php
Refresh your package database
sudo apt update
Install PHP-curl 7.2
sudo apt install php7.2-fpm php7.2-gd php7.2-curl php7.2-mysql php7.2-dev php7.2-cli php7.2-common php7.2-mbstring php7.2-intl php7.2-zip php7.2-bcmath
Restart Apache Server
sudo systemctl restart apache2
That’s all.
I hope this helps
answered Jan 10, 2020 at 16:19
Promise PrestonPromise Preston
21.2k11 gold badges127 silver badges128 bronze badges
Yet another answer …
If you land here in Oct 2020 because PHP on the command line (CLI) has stopped working, guess what … some upgrades will move you to a different/newer version of PHP silently, without asking!
Run:
php --version
and you might be surprised to see what version the CLI is running.
Then run:
ll /usr/bin/php
and you might be surprised to see where this is linking to.
It’s best to reference the SPECIFIC version of PHP you want when calling the PHP binary directly and not a symbolic link.
Example:
/usr/bin/php7.3
will give you the exact version you want. You can’t trust /usr/bin/php or even just typing php because an upgrade might switch versions on you silently.
answered Oct 11, 2020 at 16:07
mcmacersonmcmacerson
8031 gold badge13 silver badges17 bronze badges
I have solved this issue in Ubuntu 20.04.1 LTS and PHP Version 7.4.3
Update the package index:
sudo apt-get update
Install php7.4-curl deb package:
sudo apt-get install php7.4-curl
answered Jan 29, 2021 at 13:17
Nanhe KumarNanhe Kumar
15.1k5 gold badges78 silver badges70 bronze badges
This worked for me with raspian:
sudo apt update && sudo apt upgrade
sudo apt install php-curl
finally:
sudo systemctl restart apache2
or:
sudo systemctl restart nginx
answered Feb 18, 2021 at 3:05
rundekugelrundekugel
1,0021 gold badge10 silver badges23 bronze badges
To install the last version of php-curl on Ubuntu, use this:
sudo apt-get install php-curl -y
answered Nov 9, 2021 at 14:43
George ChalhoubGeorge Chalhoub
13.9k3 gold badges36 silver badges60 bronze badges
Содержание
- Fixing “Uncaught error: Call to undefined function curl_init”
- Check to see if curl is enabled.
- Enabling curl on Linux.
- Enabling curl on Windows.
- Enabling curl on WampServer.
- PHP Fatal error: Uncaught Error: Call to undefined function curl_init()
- Shared Hosting
- Install cURL extension for Apache/Nginx on Linux
- Check php.ini
- Windows
- 4 replies
- Leave a reply
- Fatal error: Call to undefined function curl_init()
- Исправление ошибки “Fatal error: Call to undefined function curl_init()”
- Читайте также похожие статьи:
- PHP Fatal error: Uncaught Error: Call to undefined function curl_init()
- Shared Hosting
- Install cURL extension for Apache/Nginx on Linux
- Check php.ini
- Windows
- 4 replies
- Leave a reply
Fixing “Uncaught error: Call to undefined function curl_init”
This error will occur if your server does not have PHP’s curl extension installed or enabled.
The error will read something like this.
Uncaught error: Call to undefined function curl_init()
Essentially, PHP can’t find the curl_init function because the extension that defines it has not been loaded. This results in a fatal error, which kills the PHP script.
To avoid this kind of error, you can check to see whether the cURL module has been loaded or not before you attempt to use it.
Check to see if curl is enabled.
To see if your PHP installation has cURL enabled, you can run the following piece of code.
The phpinfo function above will output information about PHP’s configuration.
If a CTRL + F search for “curl” is unable to find anything, then it means that your web server has not loaded the curl extension.
If you do find it, then you should see the following line under the cURL heading:
Note that you should NOT leave this phpinfo function on a live web server, as it outputs sensitive information about your PHP installation!
Enabling curl on Linux.
If your web server is running on Linux and you have SSH / terminal access, then you can install and enable cURL by running the following command.
After running the command above, you will need to restart your web server so that the changes will take effect.
If you are using Apache, you can restart your web server like so.
If you are using Nginx, you can use the following command.
After your web server has been restarted, curl should be available.
Enabling curl on Windows.
If you are using Windows, you will need to locate the php.ini file that is being used by your web server.
If you are unsure about which php.ini file you need to edit, then you can use the phpinfo script that we used above, as that will display the full path to the file that is being used by the web server.
Once you have located your php.ini file, you will need to “uncomment” the following line.
To uncomment the line above and enable the php_curl.dll extension, simply remove the semi-colon at the beginning.
After you have saved the changes that you made to your php.ini file, you will need to restart your web server. Otherwise, the new configuration will not take effect.
Enabling curl on WampServer.
If you are using the popular WampServer program on Windows, then you can try the following steps:
- Click on the WampServer icon in your system tray.
- Hover over the “PHP” option.
- Once the PHP menu appears, hover over the “PHP extensions” option.
- At this stage, a list of PHP extensions should appear. If an extension has a tick beside it, then it is already enabled. If the php_curl option does not have a tick beside it, then it is not enabled. To enable curl, simply click on the php_curl option.
- WampServer should automatically restart Apache and the changes should take effect.
- If WampServer does not automatically restart Apache, then you can manually force it to do so by clicking on the “Restart All Services” option in the main menu.
Hopefully, this guide helped you to get rid of that nasty “undefined function curl_init” error!
Источник
PHP Fatal error: Uncaught Error: Call to undefined function curl_init()
cURL is a PHP extension used to transfer data to or from a remote server. If the extension is not installed or enabled on your web server, you may get a fatal PHP error about an undefined function curl_init().
If you are on shared hosting and do not have command line access to your web server or access to php.ini, you may have to contact your web host to see if they support the cURL PHP extension. Many web hosts disable this extension by default for security reasons but may enable it manually for you on request.
Install cURL extension for Apache/Nginx on Linux
If you have shell access to your Apache or Nginx web server, make sure the cURL extension is installed:
You must also restart your web server for changes to take effect.
To restart Apache, run:
To restart Nginx, run:
Now test cURL with:
If you see some HTML, cURL is working correctly.
Check php.ini
If cURL is installed but you are still getting “Call to undefined function curl_init()”, you may need to enable the extension in your php.ini file.
In the example below, we are editing the php.ini file for Apache with PHP 7.2.
Press CTRL + W and search for curl .
Remove the ; semicolon from the beginning of the following line. This line may look different depending on your version of PHP, just remove the semicolon.
To save file and exit, press CTRL + X , press Y and then press ENTER .
You must restart your web server for changes to take effect.
To restart Apache, run:
To restart Nginx, run:
Now test cURL with:
If you see some HTML, cURL is working correctly.
Windows
If you’re on Windows, go to your php.ini file and search for “curl”.
Remove the ; semicolon from the beginning of the following line.
If you are on an older version of PHP, the line might look like below.
After you have saved the file you must restart your HTTP server software before this can take effect.
Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.
p.s. I increased my AdSense revenue by 200% using AI 🤖. Read my Ezoic review to find out how.
Leave a reply
this works for me.:
sudo apt-get install php-curl
Источник
Fatal error: Call to undefined function curl_init()
Здравствуй уважаемый читатель блога LifeExample, у тебя бывало такое, когда знаешь, что код должен работать, но вместо ожидаемого результата компилятор говорит об обнаруженной фатальной ошибке? Я уверен, что бывало, так вот сегодня мне пришлось потратить не мало времени на устранение ошибки такого содержания Fatal error: Call to undefined function curl_init() , которое гласит о том, что функция curl_init() неизвестна компилятору, и нигде не определенна. Такая ошибка вызвала небольшое удивление, ибо код скрипта в котором содержится вызов curl_init() использовался мной на других хостингах без проблем, что позволило мне предположить о не правильности настроек файла php.ini.
Стоит отметить, что локальный хостинг на котором проявилась данная ошибка, организован с помощью набора дистрибутивов Denwer, достаточно популярном инструменте, начинающих веб разработчиков.
Первая самостоятельная попытка решения проблемы Fatal error: Call to undefined function curl_init() не увенчалась успехом. Первым действием был анализ файла php.ini , найдя в котором закомментированную строку:
я был уверен, что в этом кроется загвоздка. Удалив в начале строки точку с запятой “;”, и попробовав обновить страницу скрипта, снова получил сообщение об ошибке. Вновь принялся за изучения php.ini и нашел еще одну интересную строку:
Cодержание, которой говорит php компилятору, о том, в какой директории лежат все подключаемые dll библиотеки. Перейдя в директорию с удивлением обнаружил, отсутствие необходимого файла php_curl.dll. Поискав по просторам интернета, все таки нашел отсутствующую библиотеку php_curl.dll и загрузил ее в /usr/local/php5/ext . Как ни странно, но результата это не дало, вновь пришлось лицезреть сообщение: Fatal error: Call to undefined function curl_init().
Перечитав кучу форумов стал опускать руки, и уже хотел без помощи денвера самостоятельно поднять связку Apache, PHP и MySQL , дабы иметь полноценный комплект dll библиотек, включая и необходимую php_curl.dll , к счастью мне вовремя подвернулась правильная последовательность выполнения действий для решения данной задачи.
Исправление ошибки “Fatal error: Call to undefined function curl_init()”
- Скачиваем пакет библиотек для расширения возможностей набора denwer.
- Запускаем скачанный архив, в процессе установки он самостоятельно добавит нужную php_curl.dll , а также другие отсутствующие библиотеки.
- Открываем директорию, в которую установлен denwer, а именно каталог с данными PHP. Обычно это директория: c:WebServersusrlocalphp5.
- Копируем из данной директории файлы ssleay32.dll и libeay32.dll , вставляем их в каталог C:WINNTSYSTEM32.
- Открываем файл C:WebServersusrlocalphp5php.ini находим в нём строку “;extension=php_curl.dll”, и убираем точку с запятой вначале. (Внимание! Если ты до установки расширений из пункта №1 , уже проделывал данную операцию, не поленись вновь это повторить, ибо при установки данного пакета, файл php.ini перезаписывается).
- Перезапускаем denwer.
- Радуемся работе всех необходимых функций!
Данная последовательность действий является оптимальной для решения подобной проблемы при использовании утилиты denwer. Если же вы столкнулись с Fatal error: Call to undefined function curl_init(), не спользуя денвер, то вам следует покапаться в настройках php.ini , и вероятнее всего обратиться с своему хостинг-провайдеру.
Читайте также похожие статьи:
Чтобы не пропустить публикацию следующей статьи подписывайтесь на рассылку по E-mail или RSS ленту блога.
Источник
PHP Fatal error: Uncaught Error: Call to undefined function curl_init()
cURL is a PHP extension used to transfer data to or from a remote server. If the extension is not installed or enabled on your web server, you may get a fatal PHP error about an undefined function curl_init().
If you are on shared hosting and do not have command line access to your web server or access to php.ini, you may have to contact your web host to see if they support the cURL PHP extension. Many web hosts disable this extension by default for security reasons but may enable it manually for you on request.
Install cURL extension for Apache/Nginx on Linux
If you have shell access to your Apache or Nginx web server, make sure the cURL extension is installed:
You must also restart your web server for changes to take effect.
To restart Apache, run:
To restart Nginx, run:
Now test cURL with:
If you see some HTML, cURL is working correctly.
Check php.ini
If cURL is installed but you are still getting “Call to undefined function curl_init()”, you may need to enable the extension in your php.ini file.
In the example below, we are editing the php.ini file for Apache with PHP 7.2.
Press CTRL + W and search for curl .
Remove the ; semicolon from the beginning of the following line. This line may look different depending on your version of PHP, just remove the semicolon.
To save file and exit, press CTRL + X , press Y and then press ENTER .
You must restart your web server for changes to take effect.
To restart Apache, run:
To restart Nginx, run:
Now test cURL with:
If you see some HTML, cURL is working correctly.
Windows
If you’re on Windows, go to your php.ini file and search for “curl”.
Remove the ; semicolon from the beginning of the following line.
If you are on an older version of PHP, the line might look like below.
After you have saved the file you must restart your HTTP server software before this can take effect.
Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.
p.s. I increased my AdSense revenue by 200% using AI 🤖. Read my Ezoic review to find out how.
Leave a reply
this works for me.:
sudo apt-get install php-curl
Источник
This error will occur if your server does not have PHP’s curl extension installed or enabled.
The error will read something like this.
Uncaught error: Call to undefined function curl_init()
Essentially, PHP can’t find the curl_init function because the extension that defines it has not been loaded. This results in a fatal error, which kills the PHP script.
To avoid this kind of error, you can check to see whether the cURL module has been loaded or not before you attempt to use it.
Check to see if curl is enabled.
To see if your PHP installation has cURL enabled, you can run the following piece of code.
<?php //Call the phpinfo function. phpinfo();
The phpinfo function above will output information about PHP’s configuration.
If a CTRL + F search for “curl” is unable to find anything, then it means that your web server has not loaded the curl extension.
If you do find it, then you should see the following line under the cURL heading:
cURL support: enabled
Note that you should NOT leave this phpinfo function on a live web server, as it outputs sensitive information about your PHP installation!
Enabling curl on Linux.
If your web server is running on Linux and you have SSH / terminal access, then you can install and enable cURL by running the following command.
sudo apt-get install php-curl
After running the command above, you will need to restart your web server so that the changes will take effect.
If you are using Apache, you can restart your web server like so.
sudo /etc/init.d/apache2 restart
If you are using Nginx, you can use the following command.
sudo /etc/init.d/nginx restart
After your web server has been restarted, curl should be available.
Enabling curl on Windows.
If you are using Windows, you will need to locate the php.ini file that is being used by your web server.
If you are unsure about which php.ini file you need to edit, then you can use the phpinfo script that we used above, as that will display the full path to the file that is being used by the web server.
Once you have located your php.ini file, you will need to “uncomment” the following line.
;extension=php_curl.dll
To uncomment the line above and enable the php_curl.dll extension, simply remove the semi-colon at the beginning.
After you have saved the changes that you made to your php.ini file, you will need to restart your web server. Otherwise, the new configuration will not take effect.
Enabling curl on WampServer.
If you are using the popular WampServer program on Windows, then you can try the following steps:
- Click on the WampServer icon in your system tray.
- Hover over the “PHP” option.
- Once the PHP menu appears, hover over the “PHP extensions” option.
- At this stage, a list of PHP extensions should appear. If an extension has a tick beside it, then it is already enabled. If the php_curl option does not have a tick beside it, then it is not enabled. To enable curl, simply click on the php_curl option.
- WampServer should automatically restart Apache and the changes should take effect.
- If WampServer does not automatically restart Apache, then you can manually force it to do so by clicking on the “Restart All Services” option in the main menu.
Hopefully, this guide helped you to get rid of that nasty “undefined function curl_init” error!
Related: Sending a POST request without cURL.
Только для читателей Lifeexample возможно открыть интернет-магазин на Moguta.CMS со скидкой в 15%
Здравствуй уважаемый читатель блога LifeExample, у тебя бывало такое, когда знаешь, что код должен работать, но вместо ожидаемого результата компилятор говорит об обнаруженной фатальной ошибке? Я уверен, что бывало, так вот сегодня мне пришлось потратить не мало времени на устранение ошибки такого содержания Fatal error: Call to undefined function curl_init() , которое гласит о том, что функция curl_init() неизвестна компилятору, и нигде не определенна. Такая ошибка вызвала небольшое удивление, ибо код скрипта в котором содержится вызов curl_init() использовался мной на других хостингах без проблем, что позволило мне предположить о не правильности настроек файла php.ini.
Стоит отметить, что локальный хостинг на котором проявилась данная ошибка, организован с помощью набора дистрибутивов Denwer, достаточно популярном инструменте, начинающих веб разработчиков.
Первая самостоятельная попытка решения проблемы Fatal error: Call to undefined function curl_init() не увенчалась успехом. Первым действием был анализ файла php.ini , найдя в котором закомментированную строку:
;extension=php_curl.dll
я был уверен, что в этом кроется загвоздка. Удалив в начале строки точку с запятой “;”, и попробовав обновить страницу скрипта, снова получил сообщение об ошибке. Вновь принялся за изучения php.ini и нашел еще одну интересную строку:
extension_dir = «/usr/local/php5/ext»
Cодержание, которой говорит php компилятору, о том, в какой директории лежат все подключаемые dll библиотеки. Перейдя в директорию с удивлением обнаружил, отсутствие необходимого файла php_curl.dll. Поискав по просторам интернета, все таки нашел отсутствующую библиотеку php_curl.dll и загрузил ее в /usr/local/php5/ext . Как ни странно, но результата это не дало, вновь пришлось лицезреть сообщение: Fatal error: Call to undefined function curl_init().
Перечитав кучу форумов стал опускать руки, и уже хотел без помощи денвера самостоятельно поднять связку Apache, PHP и MySQL , дабы иметь полноценный комплект dll библиотек, включая и необходимую php_curl.dll , к счастью мне вовремя подвернулась правильная последовательность выполнения действий для решения данной задачи.
Исправление ошибки “Fatal error: Call to undefined function curl_init()”
- Скачиваем пакет библиотек для расширения возможностей набора denwer.
- Запускаем скачанный архив, в процессе установки он самостоятельно добавит нужную php_curl.dll , а также другие отсутствующие библиотеки.
- Открываем директорию, в которую установлен denwer, а именно каталог с данными PHP. Обычно это директория: c:WebServersusrlocalphp5.
- Копируем из данной директории файлы ssleay32.dll и libeay32.dll , вставляем их в каталог C:WINNTSYSTEM32.
- Открываем файл C:WebServersusrlocalphp5php.ini находим в нём строку “;extension=php_curl.dll”, и убираем точку с запятой вначале. (Внимание! Если ты до установки расширений из пункта №1 , уже проделывал данную операцию, не поленись вновь это повторить, ибо при установки данного пакета, файл php.ini перезаписывается).
- Перезапускаем denwer.
- Радуемся работе всех необходимых функций!
Данная последовательность действий является оптимальной для решения подобной проблемы при использовании утилиты denwer. Если же вы столкнулись с Fatal error: Call to undefined function curl_init(), не спользуя денвер, то вам следует покапаться в настройках php.ini , и вероятнее всего обратиться с своему хостинг-провайдеру.
Читайте также похожие статьи:
Чтобы не пропустить публикацию следующей статьи подписывайтесь на рассылку по E-mail или RSS ленту блога.
Last updated on November 7th, 2019 | 4 replies
cURL
is a PHP extension used to transfer data to or from a remote server. If the extension is not installed or enabled on your web server, you may get a fatal PHP error about an undefined function curl_init().
Shared Hosting
If you are on shared hosting and do not have command line access to your web server or access to php.ini, you may have to contact your web host to see if they support the cURL
PHP extension. Many web hosts disable this extension by default for security reasons but may enable it manually for you on request.
Install cURL extension for Apache/Nginx on Linux
If you have shell access to your Apache or Nginx web server, make sure the cURL extension is installed:
sudo apt-get install php-curl
You must also restart your web server for changes to take effect.
To restart Apache, run:
sudo service apache2 restart
To restart Nginx, run:
sudo service nginx restart
Now test cURL with:
curl google.com
If you see some HTML, cURL is working correctly.
Check php.ini
If cURL is installed but you are still getting “Call to undefined function curl_init()”, you may need to enable the extension in your php.ini file.
Firstly, locate your php.ini file: Where is my PHP php.ini Configuration File Located?
In the example below, we are editing the php.ini file for Apache with PHP 7.2.
sudo nano /etc/php/7.2/apache2/php.ini
Press CTRL
+ W
and search for curl
.
Remove the ;
semicolon from the beginning of the following line. This line may look different depending on your version of PHP, just remove the semicolon.
php.ini
;extension=curl
To save file and exit, press CTRL
+ X
, press Y
and then press ENTER
.
You must restart your web server for changes to take effect.
To restart Apache, run:
sudo service apache2 restart
To restart Nginx, run:
sudo service nginx restart
Now test cURL with:
curl google.com
If you see some HTML, cURL is working correctly.
Windows
If you’re on Windows, go to your php.ini
file and search for “curl”.
Remove the ;
semicolon from the beginning of the following line.
php.ini
;extension=curl
If you are on an older version of PHP, the line might look like below.
php.ini
;extension=php_curl.dll
After you have saved the file you must restart your HTTP server software before this can take effect.
Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.
p.s. I increased my AdSense revenue by 200% using AI 🤖. Read my Ezoic review to find out how.
So right now, i am attempting to enable php-curl within my apache2 server on Ubuntu 18.04 to allow an iframe to display an external site page. i have been using methods to attempt this that i have found documented in several places:
StackOverflow: How do I install the ext-curl extension with PHP 7?
StackOverflow: install cURL in php 7 (ubuntu14.04)
LinuxConfig.org: How to enable and disable PHP curl module with Apache on Ubuntu Linux
No matter what i seem to do, i cannot get anything sort of curl-related commands to work within php, which is very frustrating.
i have ensured that i have used sudo apt-get install curl php7.2-curl
which installed without issue, and have then restarted the apache service using sudo service apache2 restart
. I have tried to enable the extension in the php.ini using extension=php_curl.dll
, and also extension=curl
, with no luck. If i try the code given on linuxconfig.org to check the curl module state, it says its disabled.
If i try running my php code, i find in my logs:
PHP Fatal error: Uncaught Error: Call to undefined function curl_init() in /var/www/html/inc.redirect.php:4nStack trace:n#0 {main}n thrown in /var/www/html/inc.redirect.php on line 4
The code in my ‘inc.redirect.php’ file is as follows:
<?php
if (isset($_GET['url'])) {
$url = $_GET['url'];
$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
}
?>
What am i doing wrong/missing?
UPDATE:
looking in the apache2 error.log when i restart the service, i see the following:
PHP Warning: PHP Startup: Unable to load dynamic library ‘/usr/lib/php/20160303/curl.so’ — /usr/lib/php/20160303/curl.so: cannot open shared object file: No such file or directory in Unknown on line 0
Still attempting to dig more into this, and it appears that the curl.so file its looking for is located in ‘/usr/lib/php/20170718’. What do i have to do to change the php config to look in the proper directory?