Php windows call to undefined function curl init

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); $enc...

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's user avatar

Uwe Keim

39k56 gold badges175 silver badges289 bronze badges

asked Dec 18, 2010 at 9:45

Santosh Linkha's user avatar

Santosh LinkhaSantosh Linkha

14.1k17 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's user avatar

Shane

9952 gold badges10 silver badges30 bronze badges

answered Dec 18, 2010 at 9:48

RusAlex's user avatar

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

Kanda's user avatar

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:

  1. Fatal Error on curl_init() call
  2. in php_info, you will see the curl module author (indicating curl is installed and available)
  3. also in php_info, you will see no curl config block (indicating curl wasn’t loaded)

answered Mar 15, 2015 at 13:28

Kevin Ard's user avatar

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

lightbyte's user avatar

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

ultrajohn's user avatar

ultrajohnultrajohn

2,4973 gold badges30 silver badges56 bronze badges

To fix this bug, I did:

  1. In php.ini file, uncomment this line: extension=php_curl.dll
  2. In php.ini file, uncomment this line: extension_dir = "ext"
  3. I restarted NETBEANS, as I was using Built-in server

JasonMArcher's user avatar

JasonMArcher

13.8k22 gold badges55 silver badges52 bronze badges

answered Oct 31, 2014 at 17:17

Rajat26's user avatar

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

fishbone's user avatar

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

Community's user avatar

answered Feb 17, 2017 at 8:58

Amit Garg's user avatar

Amit GargAmit Garg

3,8171 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's user avatar

il_raffa

5,075121 gold badges32 silver badges34 bronze badges

answered Apr 10, 2018 at 7:24

Hiruna De Alwis's user avatar

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's user avatar

Uwe Keim

39k56 gold badges175 silver badges289 bronze badges

answered Aug 18, 2020 at 2:02

Vitox's user avatar

VitoxVitox

3,60425 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

jessejuicer's user avatar

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.'s user avatar

Wasim A.Wasim A.

9,54021 gold badges89 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 Klein's user avatar

Pascal KleinPascal Klein

23k24 gold badges80 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

Rajesh Kumar's user avatar

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

Mohsen Zamani's user avatar

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

Atul Baldaniya's user avatar

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.

Giulio Caccin's user avatar

answered Sep 16, 2019 at 8:39

Varun P V's user avatar

Varun P VVarun P V

1,04111 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 Preston's user avatar

Promise PrestonPromise Preston

21k11 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

mcmacerson's user avatar

mcmacersonmcmacerson

7931 gold badge12 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 Kumar's user avatar

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

rundekugel's user avatar

rundekugelrundekugel

9921 gold badge9 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 Chalhoub's user avatar

George ChalhoubGeorge Chalhoub

13.9k3 gold badges36 silver badges60 bronze badges

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:

  1. Click on the WampServer icon in your system tray.
  2. Hover over the “PHP” option.
  3. Once the PHP menu appears, hover over the “PHP extensions” option.
  4. 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.
  5. WampServer should automatically restart Apache and the changes should take effect.
  6. 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.

Call to undefined function: curl_init() или нерабочий cURL

cURL — это свободная, кроссплатформенная служебная программа командной строки для копирования файлов по различным протоколам с синтаксисом URL.

Если Ваш парсер или модуль который Вы установили не работает из за cURL
Выводится ошибка «Fatal error: Call to undefined function: curl_init()»
Это означает что у Вас не установлены библиотеки cURL

Решения

Файл php.ini
Раскоментирать строку
из

на

— Перезапускаем PHP

Для Debian

Устанавливаем библиотеку cURL

aptget install php5curl

— Нажимаем «Y» и ждем завершения установки.
— Перезапускаем Apache

/etc/init.d/apache2 restart

Для Ubuntu

sudo aptget install curl libcurl3 libcurl3dev php5curl

— Перезапускаем Apache

sudo /etc/init.d/apache2 restart

Похожая запись

1 / 1 / 2

Регистрация: 22.09.2015

Сообщений: 65

1

08.02.2016, 07:20. Показов 35874. Ответов 15


Доброго времени суток!

При попытке отправить данные с сервера выходит ошибка Fatal error: Call to undefined function curl_init()
Проверила на сервере наличие библиотеки php_curl.dll, она вроде бы есть, да и в php.ini строчка extension= php_curl.dll расскомментирована, а больше никаких советов по решению данной проблемы найти не смогла (на сервере стоит не Denwer).Не могли бы Вы подсказать, как исправить данную ошибку?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Gcom

82 / 82 / 18

Регистрация: 03.02.2016

Сообщений: 564

Записей в блоге: 1

08.02.2016, 07:36

2

Посмотрите ошибку следующим кодом (что выдавать будет):

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$aOptionsCURL = array (
                CURLOPT_URL            => $url,
                CURLOPT_CUSTOMREQUEST  => 'POST',
                CURLOPT_POSTFIELDS     => $requestItem,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 10,
                CURLOPT_SSL_VERIFYPEER => false,
                );
$sOptionsSessionCURL = curl_init();
curl_setopt_array ($sOptionsSessionCURL, $aOptionsCURL);
 
$sResultHTML = curl_exec($sOptionsSessionCURL);
if (curl_errno ($sOptionsSessionCURL)) { 
echo '<br><br>cURL Error: ' . curl_error ($sOptionsSessionCURL);

И желательно код запроса бы видеть



1



1 / 1 / 2

Регистрация: 22.09.2015

Сообщений: 65

08.02.2016, 08:28

 [ТС]

3

Я попробовала то что Вы написали,

Цитата
Сообщение от Gcom
Посмотреть сообщение

Посмотрите ошибку следующим кодом (что выдавать будет):
PHPВыделить код
$aOptionsCURL = array (
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST *=> ‘POST’,
CURLOPT_POSTFIELDS => $requestItem,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
);
$sOptionsSessionCURL = curl_init();
curl_setopt_array ($sOptionsSessionCURL, $aOptionsCURL);
$sResultHTML = curl_exec($sOptionsSessionCURL);
if (curl_errno ($sOptionsSessionCURL)) {
echo ‘<br><br>cURL Error: ‘ . curl_error ($sOptionsSessionCURL);

выдало ошибку Use of undefined constant CURLOPT_URL — assumed ‘CURLOPT_URL’ ( не только для CURLOPT_URL, но и для всех остальных), ну и традиционную Fatal error: Call to undefined function curl_init()



0



82 / 82 / 18

Регистрация: 03.02.2016

Сообщений: 564

Записей в блоге: 1

08.02.2016, 08:30

4

Скиньте весь код который вы используете для запроса на сервер.



0



annie88

1 / 1 / 2

Регистрация: 22.09.2015

Сообщений: 65

08.02.2016, 08:33

 [ТС]

5

Попробовала запустить эти функции на другом web-сервере, там почему-то все прошло нормально, хотя настройки на нем такие же, как и на первом.

Добавлено через 1 минуту

PHP
1
2
3
4
5
6
7
if($curl = curl_init()){
    curl_setopt($curl, CURLOPT_URL, $url );
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $out = curl_exec($curl);
    echo 'out = '.$out.'<br/>';
    curl_close($curl);
}



0



Gcom

82 / 82 / 18

Регистрация: 03.02.2016

Сообщений: 564

Записей в блоге: 1

08.02.2016, 08:49

6

Что выводит следующий код? :

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php 
header ("Content-Type:text/html; charset=UTF-8");
ini_set ('display_errors', 1); 
error_reporting (E_ALL); 
 
$url = "https://www.cyberforum.ru";
 
$aOptionsCURL = array (
                CURLOPT_URL            => $url,
                CURLOPT_CUSTOMREQUEST  => 'POST',
                //CURLOPT_POSTFIELDS     => $request,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 10,
                CURLOPT_SSL_VERIFYPEER => false,
                );
$sOptionsSessionCURL = curl_init();
curl_setopt_array ($sOptionsSessionCURL, $aOptionsCURL);
 
$sResultHTML = curl_exec($sOptionsSessionCURL);
if (curl_errno ($sOptionsSessionCURL)) { 
    echo '<br><br>cURL Error: ' . curl_error ($sOptionsSessionCURL);
};
print_r ($sResultHTML);
?>

И какие web-сервера используете?



0



1 / 1 / 2

Регистрация: 22.09.2015

Сообщений: 65

08.02.2016, 08:58

 [ТС]

7

Цитата
Сообщение от Gcom
Посмотреть сообщение

И какие web-сервера используете?

web-сервер apache, на самом компьютере стоит Windows Server 2003.
попробовала выполнить код, вышла та же самая ошибка с неизвестными константами и неопределенной функцией curl_init() .
Другой web-сервер( настройки такие же) вернул страницу cyber-форума.
А может прокси-сервер как-нибудь заблокировать выполнение этой функций?



0



82 / 82 / 18

Регистрация: 03.02.2016

Сообщений: 564

Записей в блоге: 1

08.02.2016, 09:13

8

А полностью можно страничку что выдал скрипт (обработанный Вашем web-сервером)



0



1 / 1 / 2

Регистрация: 22.09.2015

Сообщений: 65

08.02.2016, 09:25

 [ТС]

9

1 скрин — результат выполнения на другом сервере (где все нормально выполняется), 2 скрин, это то, что выдается на сервере который мне нужен

Миниатюры

Ошибка  Call to undefined function curl_init()
 

Ошибка  Call to undefined function curl_init()
 



0



162 / 161 / 66

Регистрация: 28.06.2015

Сообщений: 576

08.02.2016, 09:35

10

Цитата
Сообщение от annie88
Посмотреть сообщение

сервере наличие библиотеки php_curl.dll, она вроде бы есть, да и в php.ini строчка extension= php_curl.dll

php_curl.dll дает лишь доступ для php к cURL(который в свою очередь установлен в самой оси) поэтому у вас на сервере все работает, т.к. curl установлен. Вот ссылка почитайте. Попробуйте установить.
Еще ссылка



1



82 / 82 / 18

Регистрация: 03.02.2016

Сообщений: 564

Записей в блоге: 1

08.02.2016, 09:37

11

Цитата
Сообщение от annie88
Посмотреть сообщение

2 скрин, это то, что выдается на сервере который мне нужен

Еще раз проверить в файле php.ini web-сервера apache установлены ли библиотеки cURL:
Раскоментирать строку
изменить
;extension=php_curl.dll
на
extension=php_curl.dll

И обязательно перезапустить web-сервер apache!



0



1 / 1 / 2

Регистрация: 22.09.2015

Сообщений: 65

08.02.2016, 09:59

 [ТС]

12

Цитата
Сообщение от Gcom
Посмотреть сообщение

Еще раз проверить в файле php.ini web-сервера apache установлены ли библиотеки cURL:
Раскоментирать строку
изменить
;extension=php_curl.dll
на
extension=php_curl.dll
И обязательно перезапустить web-сервер apache!

библиотека найдена, extension=php_curl.dll раскомменчен, apache перезапущен, но но функция curl_init() все также стабильно не найдена((((



0



82 / 82 / 18

Регистрация: 03.02.2016

Сообщений: 564

Записей в блоге: 1

08.02.2016, 10:03

13

Цитата
Сообщение от annie88
Посмотреть сообщение

библиотека найдена, extension=php_curl.dll раскомменчен, apache перезапущен, но но функция curl_init() все также стабильно не найдена((((

Тогда попробовать установить вручную, как это сделать человек писал выше:

Цитата
Сообщение от Xenox
Посмотреть сообщение

Вот ссылка почитайте. Попробуйте установить.
Еще ссылка



1



1 / 1 / 2

Регистрация: 22.09.2015

Сообщений: 65

08.02.2016, 11:52

 [ТС]

14

Ура!!!!
сделала так, как было предложено здесь и все сработало!



1



12 / 17 / 2

Регистрация: 02.11.2015

Сообщений: 222

03.02.2019, 16:10

15

Цитата
Сообщение от annie88
Посмотреть сообщение

Ура!!!!
сделала так, как было предложено здесь и все сработало!

Здорово! Но методы там конечно откровенно варварские, пусть даже они и рабочие.. Добавил своё видение в тему указанную в ссылке.. кто столкнулся с такой же проблемой, прошу обратить внимание



0



30 / 45 / 19

Регистрация: 18.07.2018

Сообщений: 578

03.02.2019, 16:50

16

Цитата
Сообщение от Eskander88
Посмотреть сообщение

варварские

сказал человек в теме о курле



0



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.

12.07.2015

Краткая инструкция для тех, кто хочет настроить curl php на Windows 8.1 x64. Если curl не настроен на вашем вэб-сервере, то возникает следующая ошибка: Fatal error: Call to undefined function curl_init().

Настройка cURL

Написанное ниже актуально для связки Windows 8.1 x64,  Windows10 x64 + Apache 2.4.12 (win32) + Open SSl 1.0.1m + PHP 5.6.11 (php-5.6.11-Win32-VC11-x86).

  1. Скачиваем библиотеку cURL http://winampplugins.co.uk/curl. Распаковываем в любую папку. Например, «W:WebServersusrlocalcurl».
  2. В файле настроек PHP php.ini необходимо включить расширение extension=php_curl.dll.
  3. Пункт не обязательный, но во многих источниках его рекомендуют выполнять. У нас работает без выполнения этого пункта. Из папки где установлен PHP скопировать в папку «C:Windowssystem32» следующие библиотеки: libssh2.dll, php_curl.dll (находится в папке ext), ssleay32.dll, libeay32.dll. Дополнительно файл ssleay32.dll необходимо скопировать в «C:WindowsSysWOW64». 
  4. Добавить в переменные среды в переменную Path пути до папки установки curl.exe и файла php.ini. Например, «W:WebServersusrlocalcurl;W:WebServersusrlocalphp5». Очень порадовало то, что в windows10 (1511) появился новый интерфейс редактирования переменных сред. Стало очень удобно редактировать параметры.

Включение поддержки SSL для cURL

  1. Скачать файл http://curl.haxx.se/ca/cacert.pem в папку, в которой установлена библиотека curl.exe.
  2. Переименовать скаченный файл в curl-ca-bundle.crt
  3. Перезагрузить компьютер.

Проверка работы cURL

Запустите командную строку Windows. Выполните следующую команду:

curl https://www.google.com или curl http://filinkov.ru

За последние 24 часа нас посетили 9773 программиста и 1237 роботов. Сейчас ищут 250 программистов …


  1. blackbanny

    blackbanny
    Активный пользователь

    С нами с:
    16 фев 2011
    Сообщения:
    89
    Симпатии:
    0

    Доброго времени суток!
    пишу такой код:

    1. private function getContentPage($url) {
    2.              curl_setopt($ch, CURLOPT_URL, $url);
    3.              curl_setopt($ch, CURLOPT_HEADER, false);
    4.              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    5.              curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    6.              curl_setopt($ch, CURLOPT_USERAGENT, ‘PHP’);
    7.     private function getPositionForQuery($query) {
    8.         for ($i = 0; $i < 1; $i++) {
    9.             $urlYandex = «http://yandex.ru/yandsearch?text=».$query.»&lr=65&numdoc=50&p=».$i;
    10.             $contentPage = $this->getContentPage($urlYandex);
    11.             if (empty($contentPage)) {
    12.             //$this->writeContentIntoFile($contentPage);

    если запускаю на localhost(extension=php_curl.dll раскоментировал), то появляется следующая ошибка:
    Fatal error: Call to undefined function curl_init() in Z:homelocalhostwwwparse_positionParsePositionsFromYandex.php на строку if ($ch = curl_init())
    если запускаю на хостинге(best-hoster.ru), то просто выводится empty content
    подскажите в чем дело? :(


  2. runcore

    С нами с:
    12 окт 2012
    Сообщения:
    3.625
    Симпатии:
    158

    -либо вы поправили не тот php.ini
    напишите phpinfo(); и посмотрите путь до того который щас используется
    — либо не настроен путь до каталога с расширениями(extensions)
    донастройте тогда php.ini


  3. blackbanny

    blackbanny
    Активный пользователь

    С нами с:
    16 фев 2011
    Сообщения:
    89
    Симпатии:
    0

    выдал Z:usrlocalphp5php.ini, я его и правил…

    а как настроить этот путь?
    P.S. почему тогда на хостинге ничего не выдает?


  4. demyan1

    demyan1
    Активный пользователь

    С нами с:
    17 май 2012
    Сообщения:
    65
    Симпатии:
    0

    не любит, наверное, яндекс ботов.
    вы же сами говорите:

    1. curl_setopt($ch, CURLOPT_USERAGENT, ‘PHP’);

    ищите похожую строку:
    extension_dir = «d:/Work/Server/php/ext»

    Добавлено спустя 1 минуту 57 секунд:
    и да, по-моему в phpinfo() видно какие расширения php подключены


  5. demyan1

    demyan1
    Активный пользователь

    С нами с:
    17 май 2012
    Сообщения:
    65
    Симпатии:
    0

    непонятно зачем…
    вам же говорят, настройте путь в php.ini: extension_dir = «d:/Work/Server/php/ext» (в вашем случае:extension_dir = «Z:/usr/local/php5/ext»)
    и ещё: странная ф-я какая-то function getPositionForQuery($query)…
    по-моему она никогда вам не выдаст страницу с контентом, т.к. после exit; уже ничего не выполняется.


  6. blackbanny

    blackbanny
    Активный пользователь

    С нами с:
    16 фев 2011
    Сообщения:
    89
    Симпатии:
    0

    в php.ini написано: extension_dir = «/usr/local/php5/ext»


  7. runcore

    С нами с:
    12 окт 2012
    Сообщения:
    3.625
    Симпатии:
    158

    ну так пропишите правильный абсолютный путь. несовпадает же с реальным расположением


  8. blackbanny

    blackbanny
    Активный пользователь

    С нами с:
    16 фев 2011
    Сообщения:
    89
    Симпатии:
    0

    написал абсолютный, все равно такая же ошибка…


  9. demyan1

    demyan1
    Активный пользователь

    С нами с:
    17 май 2012
    Сообщения:
    65
    Симпатии:
    0

    в phpinfo() в разделе curl, в строке cURL support должно стоять enabled, и ещё: скопируйте php.ini в c:windows
    кстати, если у вас денвер — выкиньте его в мусорку…


  10. blackbanny

    blackbanny
    Активный пользователь

    С нами с:
    16 фев 2011
    Сообщения:
    89
    Симпатии:
    0

Понравилась статья? Поделить с друзьями:
  • Php warning php startup unable to load dynamic library windows
  • Photopad photo editor free windows скачать на русском
  • Php value default charset windows 1251
  • Photographs appeared in shop windows in london and paris due to
  • Photodex proshow producer скачать на русском бесплатно для windows 10