Tag: PHP

How to convert a string to lowercase in Bash

This note will show you how to convert a string to lowercase (small letters) on the Linux command line.

To convert a string to lower case regardless of its current case, use one of the following commands.

tr

echo "Hi all" | tr '[:upper:]' '[:lower:]'
hi all

Attention! If you want to change the case of any letters other than Latin (national alphabets, letters with diacritics), then do not use tr, but use any other solution suggested below. This is because the classic Unix tr operates on single-byte characters and is not compatible with Unicode.

AWK

echo "Hi all" | awk '{print tolower($0)}'
hi all

Bash

a="Hi all"
echo "${a,,}"
hi all

Starting with Bash 5.1, there is a conversion option “L”, which is intended to convert a string to lowercase:

${var@L}

Example:

v="heLLo"
echo "${v@L}"
hello

sed

echo "Hi all" | sed -e 's/\(.*\)/\L\1/'
hi all

Or this solution:

echo "Hi all" | sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all

Another solution:

echo "Hi all" | sed 's/./\L&/g'

Perl

echo "Hi all" | perl -ne 'print lc'
hi all

Python

a="Hi all"
b=`echo "print ('$a'.lower())" | python`; echo $b

Ruby

a="Hi all"
b=`echo "print '$a'.downcase" | ruby`; echo $b

PHP

b=`php -r "print strtolower('$a');"`; echo $b

NodeJS

b=`node -p "\"$a\".toLowerCase()"`; echo $b

In zsh

a="Hi all"
echo $a:l

How to convert a string to uppercase in Bash

This note will show you how to convert a string to upper case (capital letters, uppercase) on the Linux command line.

To convert a string to capital letters regardless of its current case, use one of the following commands.

tr

echo "Hi all" | tr '[:lower:]' '[:upper:]'
HI ALL

Attention! If you want to change the case of any letters other than Latin (national alphabets, letters with diacritics), then do not use tr, but use any other solution suggested below. This is because the classic Unix tr operates on single-byte characters and is not compatible with Unicode.

AWK

echo "Hi all" | awk '{print toupper($0)}'
HI ALL

Bash

a="Hi all"
echo "${a^^}"
HI ALL

Starting with Bash 5.1, there is a conversion option U, which is intended to convert a string to uppercase:

${var@U}

Example:

v="heLLo"
echo "${v@U}"
HELLO

sed

echo "Hi all" | sed -e 's/\(.*\)/\U\1/'
HI ALL

Or this solution:

echo "Hi all" | sed -e 's/\(.*\)/\U\1/' <<< "$a"
HI ALL

Another solution:

echo "Hi all" | sed 's/./\U&/g'

Perl

echo "Hi all" | perl -ne 'print uc'
HI ALL

Python

a="Hi all"
b=`echo "print ('$a'.upper())" | python`; echo $b

Ruby

a="Hi all"
b=`echo "print '$a'.upcase" | ruby`; echo $b

PHP

b=`php -r "print strtoupper('$a');"`; echo $b

NodeJS

b=`node -p "\"$a\".toUpperCase()"`; echo $b

In zsh

a="Hi all"
echo $a:u

How to show all errors in PHP 8

How to display all errors in PHP 8

By default, PHP 8 disables showing errors, so if there is a problem while executing a PHP script, nothing will be displayed on the screen. If an error in the program occurred before the output of the HTML code, then you will see a white screen of the web browser.

Where is the error output configured in PHP

Error output is configured in:

  • script code
  • .htaccess file
  • in the PHP configuration file (for example, in php.ini)

The settings in the script code only affect the behavior of the program in which the settings are made.

The settings in the .htaccess file affect all scripts in that directory and subdirectories.

The settings in the php.ini configuration file affect all PHP scripts that are run unless their error output settings are overridden.

Remember that error reporting is very useful while writing and debugging code, but on production servers, error reporting should be turned off to prevent sensitive data from being leaked and making it harder for an attacker to hack the site.

Configuring error output in PHP script

To display all errors, add the following lines to the beginning of the script:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

These settings enable the output of all errors and warnings to the user's web browser.

Warnings about the use of deprecated constructs will be displayed.

Error output to the web server logs is configured separately.

Remember that if fatal errors occur, that is, when the script could not even run due to incorrect PHP syntax, then the rules specified in the php.ini or .htaccess file will be used to output errors. This is due to the fact that if the syntax is incorrect, the PHP interpreter does not understand the entire file, including the above directives. That is, if a semicolon or a curly brace is missing in the code, then errors will be displayed in accordance with the settings in the php.ini file.

Configuring PHP error output in .htaccess file

Enabling error output in the .htaccess file is done by the following directives:

php_flag display_startup_errors on
php_flag display_errors on

For them to work, the web server must have .htaccess files enabled.

Error output to the web server log is performed by the following directive:

php_value error_log logs/all_errors.log

Setting the output of all errors in the php.ini file

The php.ini file is the PHP configuration file.

PHP can use more than one configuration file during its operation.

Location of php.ini file:

  • In Debian and derivative distributions (Ubuntu, Linux Mint, Kali Linux and others), it depends on the PHP version, for example, for PHP 8.1 the path to the file is: /etc/php/8.1/apache2/php.ini
  • On Arch Linux and derivative distributions (Manjaro, BlackArch and others): /etc/php/php.ini

In the php.ini file you will find the following directives:

display_errors = Off
display_startup_errors = Off

To enable error reporting, replace them with:

display_errors = On
display_startup_errors = On

The default value of error_reporting is set to:

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

This means that all errors are printed except for deprecation warnings and warnings caused by strict code checking.

To display all errors and warnings, set the following value:

error_reporting = E_ALL

Common Values:

  • E_ALL (Show all errors, warnings and notices including coding standards.)
  • E_ALL & ~E_NOTICE (Show all errors, except for notices)
  • E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
  • E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)

See the link for details: https://www.php.net/manual/errorfunc.constants.php

In order for the changes made in the php.ini file to take effect, a restart of the web server is required.

  • In Debian and derivative distributions (Ubuntu, Linux Mint, Kali Linux and others), this is done with the command:
sudo systemctl restart apache2.service
  • In Arch Linux and derivative distributions (Manjaro, BlackArch and others), this is done with the command:
sudo systemctl restart httpd.service

To check that the php.ini file settings are actually applied, create a file, for example, named info.php and copy into it:

<?php
phpinfo();

If you created the file in the root folder of the web server, in a web browser open http://localhost/info.php.

The following screenshot shows that error output is disabled in the php.ini file:

This screenshot shows that error output is enabled in the php.ini file:

Outputting errors to the web server log

Error output to the web server log is configured in the php.ini file.

The following directive is used for this:

log_errors = On

The location of the error file is configured in the web server configuration.

The “error_reporting('all');» и ошибка «Uncaught TypeError: error_reporting()”

When trying to use the following construct:

error_reporting('all');

You will encounter the Uncaught TypeError: error_reporting() error.

Full error log:

[Wed Jul 06 07:29:19.410966 2022] [php:error] [pid 14101] [client 127.0.0.1:58402] PHP Fatal error: Uncaught TypeError: error_reporting(): Argument #1 ($error_level) must be of type ?int, string given in /srv/http/suip/index.php:3\nStack trace:\n#0 /srv/http/suip/index.php(3): error_reporting('all')\n#1 {main}\n thrown in /srv/http/suip/index.php on line 3, referer: http://localhost/suip/

Instead of 'all' you need to provide a constant expressing the level of the error message. Valid values are provided on this page: https://www.php.net/manual/errorfunc.constants.php

The following entry is correct for PHP 8 and means to show all errors, notes, and recommendations:

error_reporting(E_ALL);

Error “Composer detected issues in your platform: Your Composer dependencies require the following PHP extensions to be installed: mysqli, openssl” (SOLVED)

This post explains the causes of the error and how to fix it.

When self-installing the web server on Windows, for example, following the guide “How to install Apache web server with PHP, MySQL and phpMyAdmin on Windows”, when trying to open the phpMyAdmin address, an error may occur:

Composer detected issues in your platform: Your Composer dependencies require the following PHP extensions to be installed: mysqli, openssl

It occurs in the latest version of phpMyAdmin (for example, in 5.1.1) in the following cases:

1.

The following line is not added to the php.ini file:

extension_dir = "C:\Server\bin\PHP\ext\"

Open the php.ini file and double-check the value of the extension_dir directive. Depending on the folder where you are installing, you may have a different path instead of "C:\Server\bin\PHP\ext\". This value is correct if you install according to the instructions, the link to which is given above.

2.

The following line are commented in the php.ini file:

extension=mysqli
extension=openssl

Check your php.ini file to make sure these lines are uncommented.

3.

Your system for some reason does not use the settings from the php.ini file, for example, because the php.ini file is named incorrectly.

You can check this by running at the command line:

C:\Server\bin\PHP\php --ini

The output should include the path to the file C:\Server\bin\PHP\php.ini. If it is not, you may not have renamed the file to php.ini or named it php.ini.txt or something.

4.

All the settings in the php.ini file are correct, but the web server has not been restarted, which prevented the settings from being applied.

To restart the Apache web server, run the following command (you may have a different path to the executable file):

c:\Server\bin\Apache24\bin\httpd.exe -k restart

Alternatively, restart your computer.

Conclusion

You can think of more exotic reasons, for example, when copying the PHP executable files, the “ext” folder was not copied. But the essence is always the same: PHP is not configured to use the extensions mysqli, openssl – that is, exactly what the error says.

How to fix “Configuration File (php.ini) Path” no value (SOLVED)

The phpinfo function shows complete information about the PHP environment, including which modules are enabled, where the configuration files are located, with which options the PHP binaries were compiled, and much more.

To use this function in the web server folder create a file and copy to it:

<?php

phpinfo ();

Save the file and open it in a web browser.

Why Configuration File (php.ini) Path has no value

As the name of the item “Configuration File (php.ini) Path” implies, this is the path to the configuration file php.ini. The php.ini file is important because it enables and disables modules, sets limits on the use of system hardware resources, and makes all other PHP settings.

As you can see in the screenshot, “Configuration File (php.ini) Path” is defined as “no value", that is, it is not set. You might think that something was done wrong and PHP works without modules.

But in fact, PHP and the web server on the computer from which the screenshot was taken are working as expected. Pay attention to the next item “Loaded Configuration File” after the highlighted line, it contains the value C:\Server\bin\PHP\php.ini, that is, the configuration file is loaded.

As for the “Configuration File (php.ini) Path”, the path to the file where php.ini is searched for by default is written here – this value is specified when compiling PHP, you do not need to worry about it.

That is, you need to pay attention only to the “Loaded Configuration File”, because if there is also “no value”, then it really means that the php.ini configuration file is not loaded and not used.

If some modules do not work, then carefully check the contents of php.ini – have you really uncommented the required lines?

After making changes to the php.ini file, remember to restart the web server for the changes to take effect.

How to run PHP script on the command line (without web server)

How to run PHP script on Windows command line

If you want not only the ability to run PHP from the command line, but also a full-fledged Apache + PHP + MySQL web server on Windows, then complete the installation according to this article.

To run PHP on the command line, you do not need to install a web server, just download and unpack the archive with the PHP interpreter.

Let's start by downloading the latest PHP version for Windows from the official website: https://windows.php.net/download/

There are several options that differ:

  • Version (e.g. 8.0, 7.4, 7.3)
  • Computer architecture, (x64 and x86)
  • Thread Safe or Non Thread Safe

Choose the latest version, between x64 and x86 choose the same version as your webserver. That is, if your Apache is 64-bit, then PHP must be 64-bit as well. Always choose ‘Thread Safe’ version.

There are two links for each file:

  • Zip
  • Debug Pack

Choose Zip because the debug package is only for those who really know why they need it. This does not mean debugging PHP scripts, but debugging the PHP interpreter itself.

If you often run PHP scripts from the Windows command line, it is highly recommended to To add PHP path to %PATH% environment variable on Windows. This eliminates the need to specify the full path to the php.exe file every time.

Now that PHP is installed and the path to php.exe has been added to the Windows environment variable, open a command prompt by pressing the Win+x key combination and select Windows PowerShell.

To check what works fine, look at the PHP help:

php -h

In fact, we are running the php.exe file, but the extension can be dropped. That is, the previous entry is equivalent to

php.exe -h

How to run .php script on Windows and Linux command line

The following command is used to run the .php file in the Windows console:

php -f path\to\file.php

The -f option can be skipped, that is, the previous and next commands are the same:

php path\to\file.php

I created a test file which is located in the path C:\Users\Alex\Documents\PHP\test.php then I can run it in PHP like so:

php -f C:\Users\Alex\Documents\PHP\test.php

or like this:

php C:\Users\Alex\Documents\PHP\test.php

How to pass arguments to a PHP script on the command line

To pass arguments to the script, list them after the filename, separated by a space. If the arguments themselves contain spaces or other characters that are special to the command line shell, then enclose those arguments in single or double quotes.

php path\to\file.php 'arg1' 'arg2' 'arg3' 'arg_n'

An example of running a PHP script with three arguments:

php C:\Users\Alex\Documents\PHP\test.php 'Alex' 'hackware.ru' 'Admin'

How to access arguments in a PHP script

The arguments passed are contained in the $argv array. Moreover, the ordinal number of the argument corresponds to the number in the array. That is, the first argument will be placed in $argv[1], the second in $argv[2], and so on.

The very first element of the array named $argv[0] contains the full path to the script to run.

The content of the test.php file:

<?php

echo 'Name: ' . $argv[1] . PHP_EOL;
echo 'Web site: ' . $argv[2] . PHP_EOL;
echo 'Status: ' . $argv[3] . PHP_EOL;

Let's run it and pass three arguments to the script:

php C:\Users\Alex\Documents\PHP\test.php 'Alex' 'hackware.ru' 'Admin'

How to get data from user in the console in PHP

Thanks to the passed arguments, the script can perform actions not only with the data written in it, but also with other values specified when the script was run.

By the way, when working in a web server environment, that is, when a PHP script performs tasks for a website, the ability to pass arguments to it is implemented using the HTTP GET and POST methods. These arguments are passed before starting the script, and after starting the PHP script, new data cannot be sent – you need to wait for the program to finish running, and, if necessary, run it again with new data.

While the script is running, it may be necessary to enter new data; in the console, this is achieved using a prompt, into which the user can enter a value and press Enter to pass it to the script. In the context of a website, there is no such possibility – to transfer data already during the execution of the script. That is, the console launch of PHP scripts with arguments is not only easier (no need to fiddle with an HTML form), but even more flexible.

PHP uses the readline function to query the user.

This feature works the same on both Windows and Linux. Moreover, on Linux, it has the interactive capabilities of Bash, for example, it saves the input history, to which you can return using the arrows. On Windows, this feature has appeared since PHP 7.1.

If you really need to, you can configure the auto-completion of the input data. All GNU Readline features are covered here. I will only touch on readline, which reads the line entered by the user. With this function, you can specify one optional argument – a string that will be shown to the user at the prompt.

An example of a PHP console script that asks the user for data at a command line prompt:

<?php

$len_min = readline("The minimum number of characters in a password is: ");
$len_max = readline("Maximum number of characters in a password: ");
$base = readline("Password base (0 - digits; 1 - lowercase letters; 2 - uppercase letters): ");

echo "Received initial data: \r\nPassword length from $len_min to $len_max characters ";
switch ($base) {
	case 0:
		echo "and the base of the password is in lowercase digits.";
		break;
	case 1:
		echo "and the base of the password is in lowercase letters.";
		break;
	case 2:
		echo "and the base of the password is in uppercase letters.";
		break;
}

How to execute PHP commands interactively

If you need it, then you can work with the PHP interpreter interactively, entering the code line by line. In this case, the code is executed after pressing the Enter button, but the values of the variables are saved within one session. That is, you can assign a value to a variable and then use it in other lines.

To run an interactive shell:

php -a

How to run individual PHP commands

Use the -r option to run individual commands:

php -r 'echo 2**100;'

How to install a web server (Apache, PHP, MySQL, phpMyAdmin) on Linux Mint, Ubuntu and Debian

If you are a webmaster, or a PHP programmer, or you just need to run a website on your computer, then you can do it using a web server. On Linux, the web server (Apache) and related components (PHP, MySQL, phpMyAdmin) are installed in just a few commands.

This tutorial will show you how to set up a web server for sites on Linux Mint, Ubuntu and Debian.

How to install Apache, PHP, MySQL, phpMyAdmin on Linux Mint, Ubuntu and Debian

We will do most of the operations in the command line - the Linux terminal.

Open a terminal and run the following two commands in it:

sudo apt update
sudo apt install apache2 default-mysql-server php phpmyadmin

Answer No to the configuration prompt with dbconfig-common:

Use the Tab key to move between items and Enter to continue.

Select “apache2”:

Use the Space key to select items, use the Tab key to move between items, and press Enter to continue.

That's all! The web server (a bunch of Apache, PHP, MySQL, phpMyAdmin) is installed and ready to work. Open the link http://localhost/ in your browser

You will see the standard Apache page:

phpMyAdmin is available at http://localhost/phpmyadmin/

To start the web server every time you turn on the computer, run the command:

sudo systemctl enable apache2
sudo systemctl enable mysql

How to change URL path of phpMyAdmin. How to enable and disable phpMyAdmin

If during the installation of phpMyAdmin you chose not to configure it for use with the Apache web server, use the command to enable phpMyAdmin:

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-enabled/

Restart the web server for the changes to take effect:

sudo systemctl restart apache2

To disable phpMyAdmin use the command:

sudo rm /etc/apache2/conf-enabled/phpmyadmin.conf

Restart the web server for the changes to take effect:

sudo systemctl restart apache2

There is an important line in the /etc/phpmyadmin/apache.conf file:

Alias /phpmyadmin /usr/share/phpmyadmin

Its essence is that the URL /phpmyadmin (for example, http://localhost/phpmyadmin) begins to correspond to the /usr/share/phpmyadmin folder. That is, the phpMyAdmin files (scripts) are physically located in /usr/share/phpmyadmin, and not in the web server directory (for example, /var/www/html/).

Many automatic scanners of “hidden” files and folders of a web server and sites check the “phpmyadmin”, “pma” and other similar directories. You can hide your phpMyAdmin nicely by changing the Alias. For instance:

Alias /lkjgler94345 /usr/share/phpmyadmin

phpMyAdmin will now be available at http://localhost/lkjgler94345 - not easy to find.

phpMyAdmin setup

By default phpMyAdmin does not allow login without password. If you have not set a password for the MySQL DBMS, then you have two options to choose from:

  • set password
  • make changes to phpMyAdmin setting to allow passwordless login

It is recommended to set a password for the database. To change the password, you can use the script:

sudo mysql_secure_installation

If you want to allow logging into phpMyAdmin without a password, then open the file

sudo gedit /etc/phpmyadmin/config.inc.php

Find the second (there are two) line

// $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

and uncomment it (remove the two slashes from the beginning of the line) to get:

$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Most likely, when connecting, you will receive a surprise in the form of the error “#1698 - Access denied for user 'root'@'localhost'”. Step-by-step actions for its solution in this manual.

Where are the sites on the Apache web server?

By default, the root folder for web documents is /var/www/html. In /var/www you can create your own virtual hosts.

The /var/www/html folder and all files inside it belong to the root user.

For you to be able to modify, add, delete files in this folder, you need to use sudo. For example, with the following command, you will open a file manager to manage the contents of a folder.

sudo nemo /var/www/html

All other programs that make changes to /var/www/html must also be run with sudo.

On a local server, for ease of use, you can make yourself the owner of this folder:

sudo chown -R $USER:$USER /var/www/html

Now you and the programs launched on your behalf do not need superuser privileges to work with the contents of this directory:

nemo /var/www/html

Apache index files

If the user requests from the web server not a file, but a directory, then the server looks for files index.html, index.php, index.htm, etc. in it. If these files are in this directory, then their contents are shown. These files are called index files. If there are two or more such files in a directory at once, then one of them is shown in accordance with the set priority.

You can see which files are index files for your server and in what order their priority is arranged in the file

sudo gedit /etc/apache2/mods-enabled/dir.conf

There you will see something like:

<IfModule mod_dir.c>
    DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>

Typically, users want to move the PHP index file (index.php) to the first position after DirectoryIndex, so that something looks like this:

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

After making changes, save and close the file, restart the web server.

Conclusion

This tutorial showed you how to install Apache web server on your Linux Mint machine. In terms of its functionality, this server does not differ from the capabilities of hosting. You can test your sites on it, use it when learning PHP, install WordPress, etc. Moreover, this server can be made available to the local or even global network.

What is open_basedir for and how to use open_basedir

The open_basedir directive is specified in the PHP configuration file (php.ini) and sets the directories that PHP can access. Access refers to any actions with files: opening (for example, fopen() or gzopen()), writing and executing. If the open_basedir directive is set and an attempt is made to run a file that is outside the listed directories, the script will not run and will generate an error:

[Wed Apr 1 13:11:34 2020] PHP Warning: Unknown: open_basedir restriction in effect. File(/usr/share/seeker/template/nearyou/php/info.php) is not within the allowed path(s): (/srv/http/:/etc/webapps/:/usr/share/webapps/:/tmp/:/home/mial/) in Unknown on line 0

An example of the value of open_basedir:

open_basedir = /srv/http/:/etc/webapps/:/usr/share/webapps/:/tmp/:/home/mial/

In this example, PHP scripts are allowed to run, as well as operations with files in directories:

  • /srv/http/
  • /etc/webapps/
  • /usr/share/webapps/
  • /tmp/
  • /home/mial/

The open_basedir directive affects many functions. It makes most sense when used at the level of web server configuration files at the level of directories or virtual hosts.

By default, if the open_basedir value is not set, file operations are allowed in any directories on the computer (for which there are sufficient file permissions).

The open_basedir option can be extended to more than just functions for working with the filesystem; for example, if MySQL is configured to use the mysqlnd driver, then LOAD DATA INFILE is controlled by the open_basedir option. Many PHP functions also use open_basedir.

Special meaning . (dot) indicates that the script's working directory will be used as the base directory. However, this is a little dangerous, as the current directory of the script can be easily changed with chdir().

In httpd.conf, open_basedir can be turned off (for example, for some virtual hosts) in the same way as any other configuration directive:

php_admin_value open_basedir none

On Windows, separate directories with ; (semicolon). On all other systems, separate directories with : (colon). When running as an Apache module, open_basedir paths are automatically inherited from parent directories.

Error “Unable to load dynamic library ‘xmlrpc.so’” (SOLVED)

When running a web server or running PHP scripts on the command line, you may encounter an error:

PHP Warning: PHP Startup: Unable to load dynamic library 'xmlrpc.so' (tried: /usr/lib/php/modules/xmlrpc.so (/usr/lib/php/modules/xmlrpc.so: cannot open shared object file: No such file or directory), /usr/lib/php/modules/xmlrpc.so.so (/usr/lib/php/modules/xmlrpc.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0

In fact, this is not an error at all, but just a warning. That is, the server and PHP scripts should still work fine.

This warning says that when PHP starts up, the dynamic library 'xmlrpc.so' (PHP module) cannot be loaded. An attempt was made to download this file from all typical locations, but could not be found anywhere.

XMLRPC is an extension that was included in PHP that brought XML RPC server and client functions to PHP.

This extension was relatively unused and was labeled “experimental” all along. This extension relied on some libraries that had not been supported for several years.

The xmlrpc extension is no longer bundled with PHP since PHP 8.0. You can still install the extension from PECL if your code or any dependencies require it.

If you do not need this extension, then in the php.ini file find the line

extension=xmlrpc.so

and comment it out to get:

;extension=xmlrpc.so

If you really need this extension, then install it from PECL, or use one of the following alternatives:

How to add PHP path to %PATH% environment variable on Windows

What is PATH and what is it for

It is quite possible that you have never encountered echo %PATH% and environment variable expressions before, so I will briefly explain what it is.

The PATH variable contains a list of folders in which Windows looks for executable files.

In the GUI, when shortcuts are used to launch programs, the PATH value is not very large. But if you run the program on the command line, then PATH can come in handy. Again, if you specify the full path to the file, for example, C:\Users\Alex\Documents\php.exe, then PATH is not used. But if, for example, you run the program only by the file name or just by the name (without the file extension), then whether the program starts will depend on the contents of the PATH variable.

For example, I try to run a file on the command line (without specifying the full path)

php.exe

In this case, the operating system will look at all PATH entries (several directories may be specified there). Windows will then try to find the php.exe file in each of these directories. If the file is found, it will be launched. If the file is not found, a corresponding message will be displayed.

In fact, only those who work a lot with the command line need to add something to the PATH variable. For example, you are a programmer and you place your programs in the C:\MyApps folder and you often run your command line utilities. In this case, you can add C:\MyApps to PATH and after that, to run programs from this folder, you no longer need to enter the full name each time (for example, C:\MyApps\parser.exe), but it will be enough in the command line enter only the filename:

parser.exe

Do I need to add PHP to environment variable on Windows

When installing and configuring PHP on Windows, it is not necessary to add the path to PHP to the PATH, but it is recommended to do so.

First, you can run PHP using the shorthand:

php my_script.php

instead

C:\Server\bin\PHP\php.exe my_script.php

Secondly, a number of extensions (which are included in the php.ini file) do not work correctly if you do not write the path to PHP in the PATH; this also applies to such a rather popular extension as cURL. In theory, this is some kind of bug of these extensions or PHP, but we ourselves will have to fix the situation, since this problem has existed for many years.

How to add PHP to system environment variables

So let's get started.

In the search box start typing “Edit the system environment variables

and open the corresponding settings window.

There click on “Environment Variables”, it will open:

In the “System variables” window, find and click on Path, then click “Edit”.

Then click the “New” button and enter “C:\Server\bin\PHP\” there:

Raise the entry to the very top:

Close all windows and save your changes.

Restart the server.

Loading...
X