Allow url fopen что это

от admin

Allow url fopen что это

Поведение этих функций зависит от установок в php.ini .

Директивы конфигурации файловой системы и потоков

Имя По умолчанию Место изменения Список изменений
allow_url_fopen "1" PHP_INI_SYSTEM
allow_url_include "0" PHP_INI_SYSTEM Объявлена устаревшей с версии PHP 7.4.0.
user_agent NULL PHP_INI_ALL
default_socket_timeout "60" PHP_INI_ALL
from "" PHP_INI_ALL
auto_detect_line_endings "0" PHP_INI_ALL Объявлена устаревшей с версии PHP 8.1.0.
sys_temp_dir "" PHP_INI_SYSTEM

Краткое разъяснение конфигурационных директив.

Данная директива включает поддержку обёрток URL (URL wrappers), которые позволяют работать с объектами URL как с обычными файлами. Обёртки, доступные по умолчанию, служат для работы с удалёнными файлами с использованием ftp или http протокола. Некоторые модули, например, zlib, могут регистрировать собственные обёртки.

Эта опция позволяет использование обёрток fopen, которые поддерживают работу с URL, в функциях include , include_once , require , require_once .

Замечание:

Эта опция требует включения опции allow_url_fopen.

Устанавливает отсылаемую PHP строку "User-Agent".

Значение времени ожидания по умолчанию (в секундах) для потоков, использующих сокеты. Отрицательное значения означает бесконечное время ожидания.

Адрес email, используемый в соединениях FTP без авторизации, а также в качестве значения заголовка From в HTTP соединениях при использовании ftp и http обёрток, соответственно.

Когда данная директива включена, PHP проверяет данные, получаемые функциями fgets() и file() с тем, чтобы определить способ завершения строк (Unix, MS-Dos или Macintosh).

Данная директива позволяет PHP взаимодействовать с системами Macintosh, однако, по умолчанию эта директива выключена, поскольку при её использовании возникает (несущественная) потребность в дополнительных ресурсах для определения символа окончания первой строки, а также потому, что программисты, использующие в системах Unix символы возврата каретки в качестве разделителей, столкнутся с обратно-несовместимым поведением PHP.

Настройка параметров PHP

На VPS-сервере PHP по умолчанию работает в режиме mod_php. Также Вы можете подключить режим mod_cgi по этой инструкции. В режиме mod_php PHP работает как модуль Apache. Для настройки PHP вносятся изменения в файл .htaccess.

В режиме mod_cgi запускается интерпретатор php-cgi. Для настройки PHP вносятся изменения в файл .php.ini. в каталоге сайта cgi-bin.

Настройка параметров в файле .htaccess

Все директивы необходимо добавлять в самом начале или в самом конце файла. Не добавляйте директивы между блоками кода <IfModule>. </IfModule>.

apc.cache_by_default

apc увеличивает производительность за счет кэширования. Также иногда требуется отключить акселератор apc, например, при переполнении кэша.

Для включения акселератора apc выполните команду:

Для отключения apc выполните команду:

default_charset

Директива default_charset задает кодировку по умолчанию для всех выдаваемых страниц. Например, utf-8, cp1251, koi8-r.

Для добавления директивы введите:

display_errors

Директива display_errors позволяет скрыть или выводить на экран ошибки.

Для включения вывода ошибок введите:

Для отключения вывода ошибок введите:

log_errors

Директива log_errors включает запись ошибок php и их сохранение в заданный пользователем файл.

Для включения директивы введите:

Где user – имя пользователя, u – первая буква имени пользователя.

magic_quotes_gpc

Опция magic_quotes_gpc (волшебные кавычки) включает экранирование данных PHP-скрипта. При этом обратный слэш (\), одинарные (‘) и двойные кавычки («) автоматически экранируются.

Для включения magic_quotes_gpc введите:

Для отключения magic_quotes_gpc введите:

mail.add_x_header

Опция mail.add_x_header включает логирование отправки почты из скриптов сайта. В логах содержится путь до скрпипта, адрес получатели и заголовки.

Для включения mail.add_x_header введите:

Где user – имя пользователя, u – первая буква имени пользователя.

max_input_vars

Директива max_input_vars задает максимальное количество входных переменных, которое может быть принято в одном запросе.

Например, если максимальное количество входных переменных 9000, введите:

mbstring.func_overload, mbstring.internal_encoding

Как правило, директивы mbstring.func_overload и mbstring.internal_encoding используются для оптимизации работы сайтов на CMS Битрикс. Для данной CMS введите:

Для других CMS рекомендуется использовать такие значения:

opcache.revalidate_freq

Настройка opcache.revalidate_freq необходима для CMS Битрикс. Чтобы отключить опцию введите:

pcre.recursion_limit

Данная директива позволяет установить лимит на рекурсию.

post_max_size

Директива post_max_size устанавливает максимальный объем данных, отправляемых методом POST:

Для загрузки больших файлов значение post_max_size должно быть больше upload_max_filesize.

register_globals

Директива register_globals используется для управления глобальными переменными.

Для включения глобальных переменных введите:

Для отключения глобальных переменных введите:

request_order

Директива request_order устанавливает очередность добавления переменных Cookie, POST и GET в массив _REQUEST:

upload_max_filesize

Данная директива позволяет установить максимальный размер закачиваемого файла.

Настройка опций в файле php.ini

allow_url_fopen

Опция allow_url_fopen включает URL wrappers (поддержку оберток URL). Это позволяет работать с объектами URL через ftp/http как с обычными файлами.

Для включения allow_url_fopen введите:

Для отключения allow_url_fopen введите:

apc.cache_by_default

apc увеличивает производительность за счет кэширования. Также иногда требуется отключить акселератор apc, например, при переполнении кэша.

Для включения акселератора apc выполните команду:

Для отключения apc выполните команду:

default_charset

Директива default_charset задает кодировку по умолчанию для всех выдаваемых страниц. Например, utf-8, cp1251, koi8-r.

Для добавления директивы введите:

display_errors

Директива display_errors позволяет скрыть или выводить на экран ошибки.

Для включения вывода ошибок введите:

Для отключения вывода ошибок введите:

magic_quotes_gpc

Опция magic_quotes_gpc (волшебные кавычки) включает экранирование данных PHP-скрипта. При этом обратный слэш (\), одинарные (‘) и двойные кавычки («) автоматически экранируются.

Для включения magic_quotes_gpc введите:

Для отключения magic_quotes_gpc введите:

mail.add_x_header

Опция mail.add_x_header включает логирование отправки почты из скриптов сайта. В логах содержится путь до скрпипта, адрес получатели и заголовки.

Для включения mail.add_x_header введите:

Где user – имя пользователя, u – первая буква имени пользователя.

max_input_vars

Директива max_input_vars задает максимальное количество входных переменных, которое может быть принято в одном запросе.

Например, если максимальное количество входных переменных 9000, введите:

mbstring.func_overload и mbstring.internal_encoding

Как правило директивы mbstring.func_overload и mbstring.internal_encoding используются для оптимизации работы сайтов на CMS Битрикс. Для данной CMS введите:

Для других CMS рекомендуется использовать такие значения:

opcache.revalidate_freq

Настройка opcache.revalidate_freq необходима для CMS Битрикс. Чтобы отключить опцию введите:

pcre.recursion_limit

Данная директива позволяет установить лимит на рекурсию.

post_max_size

Директива post_max_size устанавливает максимальный объем данных, отправляемых методом POST:

post_max_size = 100M

php_value post_max_size 100M

Для загрузки больших файлов значение post_max_size должно быть больше upload_max_filesize.

register_globals

Директива register_globals используется для управления глобальными переменными.

Для включения глобальных переменных введите:

Для отключения глобальных переменных введите:

request_order

Директива request_order устанавливает очередность добавления переменных Cookie, POST и GET в массив _REQUEST:

upload_max_filesize

Данная директива позволяет установить максимальный размер закачиваемого файла.

Опции, которые не могут быть изменены

При использовании виртуального сервера нельзя изменить следующие настройки php:

How to Enable / Disable PHP allow_url_fopen on a Linux/cPanel Server

How to check whether allow_url_fopen is Enabled for your domain

You must create a phpinfo.php file under your domain to check whether allow_url_fopen is enabled or not. Open phpinfo.php file in browser http://yourdomain.com/phpinfo.php and search for “allow_url_fopen” to check whether it is On/Off.

Type the below command on the server to check whether allow_url_fopen is On or Off.

grep allow_url_fopen /usr/local/lib/php.ini

php.ini file location might be different on your server so change the above command accordingly.

How to Enable allow_url_fopen globally on a Linux/cPanel Server

1. Log into your Linux Server via SSH as ‘root’.

2. Type “php --ini” command to find the location of PHP configuration file.

]# php --ini
Configuration File (php.ini) Path: /usr/local/lib
Loaded Configuration File: /usr/local/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)

On the above server you can see that PHP configuration file is in location “/usr/local/lib/php.ini”

On Easyapache 3 servers the php.ini file will be in the above location. Location is different on Easyapache 4 servers.

3. Edit the php.ini file to enable allow_url_fopen.

You can edit the file php.ini using vi editor

]# vi /usr/local/lib/php.ini
allow_url_fopen = On

4. Change the line “allow_url_fopen = Off” to “allow_url_fopen = On”

5. Save the php.ini file after changing allow_url_fopen to On

6. Restart apache service after enabling allow_url_fopen

Command : service httpd restart

Now allow_url_fopen is enabled globally for all domains on your Server. allow_url_include = On

How to enable allow_url_fopen for a specific website

If your website is hosted on shared server allow_url_fopen might be disabled globally by your webhosting provider. You must create a custom php.ini file to enable it for your website.

1. Login to cPanel

2. Click on “File Manager” in cPanel

3. Create a php.ini file in the document root of your website

4. Enter “allow_url_fopen = On” in the above custom php.ini

vi /home/user/public_html/php.ini
allow_url_fopen = On

5. Save the php.ini file and exit.

6. Run the command “service httpd restart” to restart apache.

7. Create a phpinfo page under your website to check whether allow_url_fopen is enabled.

How to Disable allow_url_fopen on a Linux/cPanel Server

Websites might get hacked if allow_url_fopen is enabled on the server so most of the hosting companies disable it. Websites will be compromised if this directive is enabled globally on the server.

How to check whether allow_url_fopen is disabled globally

Type the below command to check whether “allow_url_fopen” is enabled on the server.

Command : php -i | grep allow_url_fopen

]# php -i | grep allow_url_fopen
allow_url_fopen => On => On

allow_url_fopen is enabled on the above server. Edit the PHP main configuration file to disable allow_url_fopen

Type the below command to check the location of main PHP configuration file:

Command : php -i | grep php.ini

]# php -i | grep php.ini
Configuration File (php.ini) Path => /usr/local/lib
Loaded Configuration File => /usr/local/lib/php.ini

Edit the PHP main configuration file /usr/local/lib/php.ini using vi editor and change “allow_url_fopen = On” to “allow_url_fopen = Off”. Save the changes and exit.

Users can still enable allow_url_fopen for their website by creating a custom php.ini file under their website.

Do the below steps if you want to prevent users from enabling allow_url_fopen by creating custom php.ini

Add allow_url_fopen to disable_functions

Edit PHP configuration file /usr/local/lib/php.ini using vi editor and change “disable_functions = allow_url_fopen, fopen”

Save the file and exit.

How to Enable/Disable allow_url_fopen on Easyapache 4 server

1. Log into server via SSH as ‘root’ user

2. Type “php --ini” command to find the PHP configuration file

]# php –ini
Configuration File (php.ini) Path: /opt/cpanel/ea-php56/root/etc
Loaded Configuration File: /opt/cpanel/ea-php56/root/etc/php.ini

PHP configuration file on the above server is /opt/cpanel/ea-php56/root/etc/php.ini

3. Edit the above file and change “allow_url_fopen = Off” to “allow_url_fopen = On”

To Disable Change “allow_url_fopen = Off”

4. Restart the webserver

You can do the same steps from WHM

1. Log in to WHM

2. Search for “MultiPHP INI Editor” in WHM

3. Click on “MultiPHP INI Editor” under “Software”

WHM Home » Software » MultiPHP INI Editor

4. Click on “Basic Mode” in “MultiPHP INI Editor”

5. Select the PHP version from dropdown

6. Use toggle key to Enable/Disable

How to Enable/Disable allow_url_fopen on Easyapache 3 server

1. Log in to WHM

2. Search for “PHP Configuration Editor” in WHM Search bar

3. Click on “PHP Configuration Editor” under “Service Configuration”

enable allow_url_fopen : Easy way to access remote data !!

The allow_url_fopen helps to access data from remote servers or websites.

Many times, hosting providers turn off the use of allow_url_fopen function as it can compromise the security of the website.

At Bobcares, we often get requests from our customers to enable allow_url_fopen as part of our Server Management Services.

Today, let’s get into the details on how our Support Engineers enable allow_url_fopen in different cases.

Why enable allow_url_fopen?

The allow_url_fopen refers to a PHP directive, which retrieves data from remote servers or websites. Our Support Engineers enable it from the custom/default PHP file according to the requirement.

Usually, hackers make use of this function to retrieve data from remote servers and do malicious acts. This PHP directiv e is always made disabled in the shared server. Thus, the shared server contains lots of domains, we always keep this as disabled to avoid high-security risk.

The following command checks whether the allow_url_fopen is On or Off.

According to the php.ini file location, there will be a slight variation in the actual command.

How to enable allow_url_fopen?

At Bobcares, where we have more than a decade of expertise in managing servers, we see many customers requesting to enable allow_url_fopen.

Now, let’s see how our Support Engineers enable allow_url_fopen by various methods according to the requirement of the user.

You can enable this via different methods.

1. Enabling for a unique website.

Quite often, customers approach us to enable this directive for unique websites (hosted in shared servers). In such cases, we help the customer by enabling it by creating a custom php.ini file under the public_html folder of the website.

According to the PHP handler used in the server, the file to edit the allow_url_fopen will vary.

a) Editing php.ini file

1. Initially, we log in to the server.
2. After that, we create a custom php.ini file and edit it using vim editor. Here, the allow_url_fopen will be set as disabled(off) for default. So to enable this, we edit this file and add

3. Then we save the php.ini file after changing allow_url_fopen to On

4. Finally, we restart the Apache service using

5. Further, we verify it using the info page under the user’s website.

enable allow_url_fopen

b) Altering .htaccess file

In addition to this, when PHP runs as a DSO module, we enable allow_url_fopen by altering the .htaccess file. We added the following code to

After altering we saved the file. This, in turn, enabled the allow_url_fopen.

2. Enabling allow_url_fopen for a server

Recently another customer who was having a dedicated server approached us to enable allow_url_fopen. We assisted the customer by editing the inbuilt php.ini file for enabling allow_url_fopen.

The path of the php.ini file varies according to easyapache 3 servers and easyapache 4 servers.

1. Initially, we logged into the server via SSH as root access.

2. Then using the php –ini command, we identified the path of default php.ini in the server.

In easyapache 3 servers the path is:

In easyapache 4 servers (with php version 5.6) the path is:

3. After that, we edited the directive in php.ini file using vim editor.

4. Finally, restart the webserver.

Enabling via WHM

In addition, for the same case, we also enable allow_url_fopen for a server via WHM.

1. We signed up to WHM panel.

2. Then searched for MultiPHP INI Editor

3. After that we Selected Editor Mode and then selected the php version in Edit the INI settings of a PHP version

4. In that we searched allow_url_fopen, made it as On as follows below:

5 Finally, saved the changes.

For making the changes effective we restarted the Apache server.

[Need assistance to enable allow_url_fopen? We’ll help you.]

Conclusion

In short, the allow_url_fopen refers to a PHP directive, which retrieves data from remote servers or websites. We can enable this via editing the php.ini, .htaccess, or via WHM interface and so on. Today, we saw how our Support Engineers enabled the allow_url_fopen using different methods.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Читать:
Как найти мост в графе

Похожие статьи