В CLI SAPI есть три различных способа запуска PHP-кода:
-
Указание конкретного файла для запуска.
$ php my_script.php $ php -f my_script.php
Оба способа (с указанием опции -f или без) запустят
файл my_script.php. Нет ограничений, какой
файл запускать; в частности, файлы не обязаны иметь
расширение.php
. -
Передать PHP-код напрямую в командной строке.
$ php -r 'print_r(get_defined_constants());'
Необходимо быть особо осторожным при использовании этого способа,
т.к. может произойти подстановка переменных оболочки при использовании
двойных кавычек.Замечание:
Внимательно прочтите пример: в нем нет открывающих и закрывающих тегов!
Опция -r просто в них не нуждается, и их использование
приведёт к ошибке разбора. -
Передать запускаемый PHP-код через стандартный поток ввода
(stdin
).Это даёт мощную возможность создавать PHP-код и
передавать его запускаемому файлу, как показано в этом
(вымышленном) примере:$ some_application | some_filter | php | sort -u > final_output.txt
Вы не можете комбинировать любой из этих трёх способов запуска кода.
Как и любое другое консольное приложение бинарный файл PHP
принимает аргументы, но PHP-скрипт также получает
аргументы. PHP не ограничивает количество аргументов,
передаваемых в скрипт (оболочка консоли устанавливает
некоторый порог количества символов, которые могут передать;
обычно этого лимита хватает). Переданные аргументы доступны
в глобальном массиве $argv. Первый индекс
(ноль) всегда содержит имя вызываемог из командной
строкио скрипта. Учтите, что если код вызывается из командной
строки на лету с опцией -r, значением
элемента $argv[0] будет «Стандартный поток»
(Standard input code);
до PHP 7.2.0 это был дефис ("-"
). То же самое верно и для кода,
переданного через конвейер из STDIN
.
Вторая зарегистрированная глобальная переменная —
$argc, которая содержит количество элементов
в массиве $argv
(а не количество аргументов,
которые передали скрипту).
Если передаваемые аргументы не начинаются с символа
-
, то особых проблем быть не должно.
Передаваемый в скрипт аргумент, который начинается с -
создаст проблемы, т.к. PHP решит, что он сам должен его
обработать. Для предотвращения подобного поведения
используйте разделитель списка аргументов --
.
После того, как этот разделитель будет проанализирован PHP, все последующие
аргументы будут переданы в скрипт нетронутыми.
# Эта команда не запустит данный код, но покажет информацию об использовании PHP $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] <file> [args...] [...] # Эта команда передаст аргумент '-h' в скрипт, предотвратив показ справки PHP $ php -r 'var_dump($argv);' -- -h array(2) { [0]=> string(1) "-" [1]=> string(2) "-h" }
Однако, в Unix-системах есть ещё один способ использования
PHP для консольных скриптов. Можно написать скрипт,
первая строка которого будет начинаться с
#!/usr/bin/php
(или же другой
корректный путь к бинарному файлу PHP CLI).
После этой строки можно поместить обычный PHP-код, заключённый
в открывающие и закрывающие теги PHP. Как только будут установлены
корректные атрибуты запуска на файл (например,
chmod +x test), скрипт может быть
запущен как обычный консольный или perl-скрипт:
Пример #1 Запуск PHP-скрипта как консольного
#!/usr/bin/php
<?php
var_dump($argv);
?>
Предполагая, что этот файл назван test
и находится в текущей директории, можно сделать следующее:
$ chmod +x test $ ./test -h -- foo array(4) { [0]=> string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" }
Как можно увидеть, в этом случае не нужно заботиться о
передаче параметров, которые начинаются с -
.
Исполняемый PHP-файл может использоваться для запуска PHP-скриптов
независимо от веб-сервера. В случае работы в Unix-подобной системе,
необходимо добавить в первую строку файла #!
(называемый также «shebang»)
чтобы указать, какая из программ должна запускать скрипт.
На Windows-платформах можно назначить обработчик php.exe для файлов
с расширениями .php
или создать пакетный
(.bat) файл для запуска скриптов посредством PHP.
Строка, добавляемая в начале скрипта для Unix-систем,
не влияет на их работу в ОС Windows, таким образом можно
создавать кросс-платформенные скрипты. Ниже приведён простой
пример скрипта, который выполняется из командной строки:
Пример #2 Скрипт для запуска из командной строки (script.php)
#!/usr/bin/php
<?phpif ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
Это консольный PHP-скрипт, принимающий один аргумент.
Использование:
<?php echo $argv[0]; ?> <option>
<option> Любое слово, которое вы хотели бы
напечатать. Опции --help, -help, -h,
или -? покажут текущую справочную информацию.
<?php
} else {
echo $argv[1];
}
?>
В приведённом выше скрипте в первой строке содержится shebang,
указывающий что этот файл должен запускаться PHP. Работа ведётся с CLI-версией,
поэтому не будет выведено ни одного HTTP-заголовка.
Скрипт сначала проверяет наличие обязательного одного аргумента (в дополнение к
имени скрипта, который также подсчитывается). Если их нет, или если переданный
аргумент был —help, -help,
-h или -?, выводится
справочное сообщение с использованием $argv[0], которое содержит
имя выполняемого скрипта. В противном случае просто выводится полученный аргумент.
Для запуска приведённого примера в Unix-системе, нужно сделать
его исполняемым и просто выполнить в консоли
script.php echothis или
script.php -h. В Windows-системе можно
создать пакетный файл:
Пример #3 Пакетный файл для запуска PHP-скрипта из командной строки (script.bat)
@echo OFF "C:\php\php.exe" script.php %*
Предполагая, что вышеприведённый скрипт называется
script.php, а полный путь к CLI
php.exe находится в
C:\php\php.exe, этот пакетный файл
запустит его с переданными параметрами:
script.bat echothis или
script.bat -h.
Также можно ознакомиться с модулем
Readline для получения
дополнительных функций, которые можно использовать для улучшения
консольного PHP-скрипта.
В Windows запуск PHP можно настроить без
необходимости указывать C:\php\php.exe или
расширение .php
.
Подробнее эта тема описана в разделе
Запуск PHP из
командной строки в Microsoft Windows.
Замечание:
В Windows рекомендуется запускать PHP под актуальной учётной записью пользователя.
При работе в сетевой службе некоторые операции не будут выполнены, поскольку
«сопоставление имён учётных записей и идентификаторов безопасности не выполнено».
Нашли ошибку?
php at richardneill dot org ¶
12 years ago
On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:
1: #!/usr/bin/php
2: #!/usr/bin/env php
3: #!/usr/bin/php -n
4: #!/usr/bin/php -ddisplay_errors=E_ALL
5: #!/usr/bin/php -n -ddisplay_errors=E_ALL
1. is the standard way to start a script. (compare "#!/bin/bash".)
2. uses "env" to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.
3. if you don't need to use env, you can pass ONE parameter here. For example, to ignore the system's PHP.ini, and go with the defaults, use "-n". (See "man php".)
4. or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it's too late: if your script has a parse error, it will silently die.
5. This will not (as of 2013) work on Linux. It acts as if the whole string, "-n -ddisplay_errors=E_ALL" were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.
Summary: use (2) for maximum portability, and (4) for maximum debugging.
email at alexander-bombis dot de ¶
4 years ago
For Windows:
After the years I also have the fact that I have to use double quotation marks after php -r on Windows shell.
But in the Powershell you can use single or double quotation!
gabriel at figdice dot org ¶
8 years ago
Regarding shebang:
In both Linux and Windows, when you execute a script in CLI with:
php script.php
then PHP will ignore the very first line of your script if it starts with:
#!
So, this line is not only absorbed by the kernel when the script file is executable, but it is also ignored by the PHP engine itself.
However, the engine will NOT ignore the first #! line of any included files withing your "outer" script.php.
Any "shebang" line in an included script, will result in simply outputting the line to STDOUT, just as any other text residing outside a <?php ... ?> block.
david at frankieandshadow dot com ¶
8 years ago
A gotcha when using #!/usr/bin/php at the start of the file as noted above:
if you originally edited the file on Windows and then attempt to use it on Unix, it won't work because the #! line requires a Unix line ending. Bash gives you the following error message if it has DOS line endings:
"bash: /usr/local/bin/wpreplace.php: /usr/bin/php^M: bad interpreter: No such file or directory"
(In Emacs I used "CTRL-X ENTER f" then type "unix" and ENTER to convert)
spencer at aninternetpresence dot net ¶
13 years ago
If you are running the CLI on Windows and use the "-r" option, be sure to enclose your PHP code in double (not single) quotes. Otherwise, your code will not run.
Today, we’re going to discuss how you can run PHP files. If you’re new to PHP programming, this article will help you learn how to run PHP scripts.
PHP is a server-side scripting language which is mostly used to build web-based applications. These may range from a very simple blog to a full-fledged eCommerce website. In fact, PHP is one of the most popular server-side scripting languages for web development.
If you’re a beginner in PHP programming and you don’t know what a PHP file is, I would recommend that you review the basics of a PHP file.
In this post, we’ll discuss different ways to run PHP files.
Different Ways to Run PHP Files
There are two ways to run PHP files. The preferred way of running PHP files is within a web server like Apache, Nginx, or IIS—this allows you to run PHP scripts from your browser. That’s how all PHP websites work! The other way is to run PHP scripts on the command line, and it doesn’t require you to set up a web server.
Of course, if you want to publish your PHP pages online, you’ll have to go with the web server setup. On the other hand, running PHP scripts from the command line is useful for performing routine tasks. These are generally configured to run in the background as jobs and are run by the php
command without a web server.
In fact, many PHP scripts or applications nowadays come with built-in commands that are used to perform various operations like installing software, exporting and importing database entities, clearing the cache, and more. You may have heard of Composer—it’s a dependency manager for PHP and is one of the most popular tools built for command-line PHP.
Run a PHP File on a Web Server
If you want to run PHP scripts from a web server, you need to configure it with one of the web servers that supports it. For Windows, the IIS web server is one of the most popular. On the other hand, Apache and Nginx are widely used web servers for other operating systems.
The good news is that most hosting providers will have a web server with PHP already set up for you when you log in to your new server.
Run a PHP File in the Browser for Development With XAMPP
If you want to run a PHP file in the browser on your own computer, you’ll need to set up a PHP development stack. You’ll need at least PHP, MySQL, and a server like Apache or Nginx. MySQL is used to set up databases your PHP applications can work with. Of course, you can choose to work with other database engines, but MySQL is one of the most popular databases used with PHP.
Instead of downloading all this software separately and configuring it to work together, I recommend you just download and install a program like XAMPP. It will include all the necessary software and will get you set up to run PHP in no time. And yes, it supports Windows, Linux, and macOS.
XAMPP contains everything you need to build your web pages locally. It’s hassle-free and allows you to start PHP development right away.
For this tutorial, I’ll use the XAMPP software to demonstrate PHP examples. So download and install it if you want to follow along and run the PHP examples. If you face any problems during installation, feel free to post your queries using the feed at the end of this article.
Once you’ve installed the XAMPP software locally and have it running successfully, you should be able to see the default XAMPP page at http://localhost in your browser.
Run Your PHP File in XAMPP
The first thing you’ll need to know after installing XAMPP is the location where you will put your PHP files. When you install the XAMPP software, it creates the htdocs directory, which is the document root of your default web server domain: localhost. So if you go to http://localhost/example.php, the server will try to find the example.php file under the htdocs directory.
Depending on the OS you’re using, the location of the htdocs directory varies. For Windows, it would be located at C:\xampp\htdocs. On the other hand, it would be located at /opt/lampp/htdocs for Linux users. Once you’ve found the location of the htdocs directory, you can start creating PHP files right away and running them in your browser!
phpinfo()
is a very useful function that gives you information about your server and PHP setup. Let’s create a phpinfo.php file under the htdocs directory with the following contents:
1 |
<?php
|
2 |
phpinfo(); |
3 |
?>
|
Now, go ahead and run it in your browser at http://localhost/phpinfo.php, and you should see output like this:
If you haven’t realized yet, let me tell you that you have just run your first PHP file on the web server! It may be a small one, but it’s a significant step towards learning PHP website development.
In fact, you could also create new directories under the htdocs directory to organize your PHP scripts. For example, you could create the datetime directory under htdocs for examples related to date and time. So if you create a today_date.php file under the htdocs/datetime directory, you could access it in the browser by going to http://localhost/datetime/today_date.php.
So in this way, you could create and run PHP scripts with a web server. In fact, this is what you are going to use most of the time in your day-to-day PHP development.
In the next section, we’ll see how you could run PHP scripts using the command line.
How to Run a PHP File Using the Command Line
When it comes to running PHP scripts on the command line, you should be aware of the location of the PHP executable file in your PHP installation.
For Windows users, you should be able to find the php.exe file under the directory where you have installed your PHP. On the other hand, if you’re a Linux or macOS user, you should be able to find it at /usr/bin/php. In fact, on Linux or macOS, you can just use the php
shortcut from any directory. Once you know the location of your PHP executable file, you just need to provide the name of the PHP file which you want to execute from the command-line interface.
As a Windows user, though, you’ll need to type the full path to the PHP executable to run a PHP script. The PHP executable is usually available at C:\php7\php.exe, so you can use it to execute the PHP file as shown in the following command.
1 |
C:\php7\php.exe my_example.php |
For Linux, you don’t need to type the whole path to the PHP executable.
As we discussed earlier, command-line PHP scripts are generally used for routine application-specific tasks, like:
- clearing or generating application caches
- exporting/importing system entities
- batch processing
- other general-purpose tasks
Generally, these kinds of tasks take a long time to execute and are not suited to running in a web environment since they cause timeout errors.
It’s important to note that when you’re running PHP scripts on the command line, you won’t have access to any $_SERVER
variables, since these are only initiated if you’re running PHP on a web server. Thus, it’s not recommended to rely on these variables if you’re planning to run your scripts using the command line.
As a PHP programmer, it is important to understand how the command-line PHP interface works. In fact, a lot of PHP software and frameworks nowadays come with a built-in command-line tool which allows you to perform a wide range of utility tasks from the CLI itself.
Conclusion
Today, we discussed how you could run PHP files on your system. Specifically, we went into the details of how to execute PHP scripts in a browser along with a web server and how to run it with a command-line interface as well.
As a beginner, it’s important for you to understand the basic concepts in the first place. And I hope this article has helped you to move a step further in your PHP leaning. Don’t hesitate to ask if you have any queries by using the feed below.
The Best PHP Scripts on CodeCanyon
Explore thousands of the best and most useful PHP scripts ever created on CodeCanyon. With a low-cost, one-time payment, you can purchase one of these high-quality WordPress themes and improve your website experience for you and your visitors.
Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.
Last Updated :
13 Sep, 2024
PHP Installation for Windows Users
Follow the steps to install PHP on the Windows operating system.
Step 1:
First, we have to download PHP from its official website. We have to download the .zip file from the respective section depending upon our system architecture(x86 or x64).
Step 2:
Extract the .zip file to your preferred location. It is recommended to choose the Boot Drive(C Drive) inside a folder named php (ie. C:\php).
Step 3:
- Access System Properties: Right-click on the “My Computer” or “This PC” icon, select “Properties” from the context menu, then click on “Advanced system settings.”
- Open Environment Variables: In the System Properties window, click on the “Environment Variables” button.
- Edit the PATH Variable: In the “System Variables” section, find the “PATH” variable, select it, and click “Edit.” If it doesn’t exist, click “New” to create it.
- Add PHP Path and Save: In the “Edit System Variable” window, add the path to your PHP folder (e.g., C:\php). Click “OK” to save, and close all remaining windows by clicking “OK.”
PHP Installation for Linux Users
Linux users can install php using the following command.
apt-get install php5-common libapache2-mod-php5 php5-cli
It will install php with apache server.
PHP Installation for Mac Users
Mac users can install php using the following command.
curl -s https://php-osx.liip.ch/install.sh | bash -s 7.3
It will install php in your system.
After installation of PHP, we are ready to run PHP code through command line. You just follow the steps to run PHP program using command line.
- Open terminal or command line window.
- Goto the specified folder or directory where php files are present.
Then we can run php code using the following command:
php file_name.php
We can also start server for testing the php code using the command line by the following command:
php -S localhost:port -t your_folder/
Note: While using the PHP built-in server, the name of the PHP file inside the root folder must be index.php, and all other PHP files can be hyperlinked through the main index page.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Download Article
Discover how to run PHP files in any web broswer
Download Article
This wikiHow will teach you how to run a PHP script in your web browser using a free web server called MAMP. Unlike a regular HTML file, you can’t just double-click a PHP file to run a script in your browser. Web servers like MAMP will translate your code to something that can be interpreted appropriately by any web browser on your computer.
A Quick Guide to Running PHP Files
- Download and open MAMP.
- Click “Preferences,” and make sure the defaults are set correctly.
- Map to the folder that contains the PHP file and click “OK.”
- Click “Start Servers” and open your browser.
- Navigate to “localhost:8888” and click the PHP file to run the script.
-
Go to https://www.mamp.info/en/downloads. MAMP is a free, local server environment that you’ll need to use to see PHP in your web browser.
-
If you’re using a Windows PC, you’ll run the downloaded file, then follow the installer wizard install MAMP. If you’re using a Mac, you’ll run the downloaded file, then drag-and-drop the MAMP file icon to your Applications folder.
Advertisement
-
You’ll find this program in your Start Menu or Applications folder in Finder once it’s installed.
-
This grey gear icon is on the left side of the window that opens when you launch MAMP.
-
Click through the tabs on the top and check to make sure the information is listed similarly so your server works.
- In the Start/Stop tab, make sure «Start Servers» and «Open WebStart Page» are checked under «When starting MAMP.» «Stop servers» should be selected under «When quitting MAMP.»[1]
- On the Ports tab, enter 8888 in the text field next to «Apache Port,» «Nginx Port,» and 8889 in the text field next to «MySQL Port.»[2]
- On the PHP tab, select «7.1.1» if it’s not already selected.
- On the Web Server tab, select «Apache» if it’s not already selected.
- In the Start/Stop tab, make sure «Start Servers» and «Open WebStart Page» are checked under «When starting MAMP.» «Stop servers» should be selected under «When quitting MAMP.»[1]
-
You can have multiple PHP files in that folder, but make sure you map a folder instead of a file by dragging and dropping the folder from your file browser.[3]
- For example, you can open your file browser and navigate to your PHP file, navigate one folder back, then drag-and-drop it in the open window. You’ll have MAMP set to the folder that your PHP file is inside, not the file ending in .PHP.
-
This might take about 20 seconds.[4]
-
This power icon button is toward the right side of the window that opens when you launch MAMP. Enter your computer password and username when prompted to continue.
-
You can use any browser to preview your PHP file.
-
Navigate to «localhost:8888» in your browser’s address bar. The address bar is where you normally see «https://www.» To do this, type «localhost:8888» and press (Windows) or ⏎ Return (Mac). You’ll see a directory of your PHP files displayed on the page.
-
Your PHP file now run and display its output in the browser window.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
References
About This Article
Article SummaryX
1. Download MAMP at https://www.mamp.info/en/downloads/.
2. Open MAMP.
3. Click Preferences.
4. Check that all the defaults are set correctly.
5. Map to your folder that contains the PHP file.
6. Click OK to apply your changes to preferences before continuing.
7. Click Start Servers.
8. Open your browser.
9. Type «localhost:8888» in your browser’s address bar.
10. Press Enter or Return on your keyboard.
11. Click the PHP file to view it.
Did this summary help you?
Thanks to all authors for creating a page that has been read 77,343 times.
Is this article up to date?
В данном материале мы рассмотрим такие вопросы как: настройка PHP для работы в командной строке, выполнение PHP-кода в командной строке,
запуск PHP скриптов в командной строке без аргументов и с аргументами.
«На дисерт», в последнем пункте материала, будет показан процесс установки через командную строку
менеджера зависимостей для PHP getcomposer.org.
Начиная с версии 4.3.0, PHP поддерживает новый вид SAPI (интерфейс разработки серверных приложений) под названием CLI, что означает интерфейс командной строки.
Как видно из названия, этот вид SAPI предназначен для разработки консольных (или даже десктопных) приложений на PHP.
Начиная с PHP 4.3.0 дистрибутив для Windows влючает в себя CLI-модуль php.exe, расположенный в отдельной директории cli, полное имя — cli/php.exe.
Начиная с PHP 5, CLI-модуль расположен в основной директории и называется php.exe. CGI-модуль также включен в дистрибутив под названием php-cgi.exe.
Начиная с PHP 5, в дистрибутив для Windows входит новый файл php-win.exe. Он полностью эквивалентен CLI, за исключением того,
что php-win абсолютно ничего не выводит, что приводит к отстутствию консоли (окно DOS не появляется на экране).
Настраиваем работу PHP из командной строки
Прежде всего Вы должны узнать расположение CLI-модуля, файла с именем «php.exe». В моем случае полный путь до данного файла выглядит так — «C:\php\php.exe».
Теперь нам нужно проверить работает ли PHP в командной строке. Для этого откроем командную строку (желательно от имени администратора) и выполним команду:
C:\Windows\system32>C:\php\php.exe --help
укажем полный путь до CLI-модуля, файла «php.exe» (т.е. «C:\php\php.exe»), и через пробел добавим ключ «—help».
(вызов «PHP» в консоли с ключем «—help» покажет справочную информацию).
Если после выполнения данной команды Вы получили предупреждения или сообщения об ошибках, то вероятнее всего, Вами был не верно указан путь до CLI-модуля «C:\php\php.exe».
При удачном выполнение команды должна отобразиться справочная информация. Поздравляю, Ваш PHP работает в консоли.
Вы наверное согласитесь со мной, что каждый раз указывать путь «C:\php\php.exe» довольно-таки не приятно,
и конечно же, запуск PHP можно настроить без необходимости указывать полный путь до файла «C:\php\php.exe».
Для этого необходимо в «Переменные среды» в переменную «PATH» добавить путь до этого файла.
Давайте ради интереса, до внесения изменений в переменную «PATH», попробуем вызвать в консоли PHP:
выполняем команду с опцией «php —help»
C:\Windows\system32>php --help
В ответ Вы скорее всего получите:
C:\Windows\system32>php --help "php" не является внутренней или внешней командой, исполняемой программой или пакетным файлом.
Теперь добавим путь до CLI-модуля «php.exe» в переменную «PATH». Найти данную переменную можно выполнив ряд действий (визуально представлено на изображениях ниже):
«Пуск» → пункт «Панель управления» → «Система» → «Изменить параметры» → вкладка «Дополнительно» → «Переменные среды» → в нижнем блоке (Системные переменные) выделяем Переменную «Path» или «PATH» → «Изменить»
В данной переменной уже имеются пути, которые разделены точкой с запятой (;). Вам необходимо добавить в конец переменной свой путь до CLI-модуля, файла «php.exe»,
В моем случае путь это — «C:\php\». (Будьте внимательны, при внесении изменений не удалите текущие значения).
добавим путь до CLI-модуля, файла «php.exe», в переменную «PATH»
Снова выполняем команду с ключем «php —help»
C:\Windows\system32>php --help или C:\Windows\system32>php -h
команда «php» с ключем «—help» покажет справочную информацию
Примеры работы PHP в командной строке
Откроем консоль (желательно от имени администратора) и перейдем к практике.
Рассмотрим два способа запуска PHP-кода:
- Передача PHP-кода напрямую в командной строке
- Указание конкретного файла для запуска
Первый способ. Опция «-r» (или «—run») позволяет выполнять PHP-код, указанный непосредственно в командной строке.
Открывающие и завершающие PHP-теги (<?php и ?>) не нужны.
C:\Windows\system32>php -r "printf(1);" 1
C:\Windows\system32>php -r "printf(1+2);" 3
C:\Windows\system32>php -r "printf('Hello world');" или C:\Windows\system32>php -r "print_r('Hello world');" C:\Windows\system32>php -r "echo 'Hello world';" Hello world
C:\Windows\system32>php -r "var_dump($_SERVER);"
Второй способ. Опция «-f» (или «—file») позволяет исполнять указанный файл. Является не обязательной и может отсутствовать,
достаточно просто указать имя файла.
Исполним индексный файл веб-сервера Apache с расширением «.html»
C:\Windows\system32>php -f C:\Apache24\htdocs\index.html или C:\Windows\system32>php C:\Apache24\htdocs\index.html <html><body><h1>It works!</h1></body></html>
Исполним php скрипт
C:\Windows\system32>php C:\Apache24\htdocs\phpinfo.php
Передаем аргументы php скрипту в консоли
Как и любое другое консольное приложение, PHP может принимает аргументы, а PHP-скрипт также может получать аргументы.
Рассмотрим данную возможность на примере. В корневой директории управления сайтами «C:\Apache24\htdocs» создадим файл «console.php» и внесем в него строки:
<?php // количество аргуметов переданных в консоли echo "The number of array elements \$argv = " . $_SERVER['argc'] . "\n"; // выводим массива аргументов переданных в консоли print_r($_SERVER['argv']); ?>
Исполним php скрипт «console.php» без передачи параметров
C:\Windows\system32>php C:\Apache24\htdocs\console.php The number of array elements \$argv = 1 Array ( [0] => C:\Apache24\htdocs\console.php )
количество аргуметов переданных в консоли равно 1,
этим аргументом является путь до файла «C:\Apache24\htdocs\console.php»
Исполним php скрипт «console.php» с передачей параметров
C:\Windows\system32>php C:\Apache24\htdocs\console.php param1 param2 The number of array elements \$argv = 3 Array ( [0] => C:\Apache24\htdocs\console.php [1] => param1 [2] => param2 )
количество аргуметов переданных в консоли равно 3,
первым аргументом является путь до файла «C:\Apache24\htdocs\console.php»
вторым и третим — param1, param2
Установка composer
Composer (getcomposer.org) — это инструмент для управления зависимостями в PHP. Он позволяет вам объявлять зависимые библиотеки для вашего проекта, устанавливать их и обновлять.
На официальном сайте getcomposer.org есть инструкция по его установке
для «Installation — Linux / Unix / OSX»
и для «Installation — Windows».
Перед скачиванием архива «composer.phar» убедитесь, что в конфигурационном файле «C:\php\php.ini» подключено расширение «php_openssl.dll».
(Для этого раскомментируйте строку «extension=php_openssl.dll»).
для того, чтобы скачать «composer.phar» выполните следующие команды
C:\Windows\system32>cd C:\Apache24\htdocs C:\Apache24\htdocs>php -r "readfile('https://getcomposer.org/installer');" | php #!/usr/bin/env php All setting correct for using Composer Downloading... Composer successfully installed to: C:\Apache24\htdocs\composer.phar Use it: php composer.phar
первой командой перейдем в директорию «C:\Apache24\htdocs»
второй командой скачаем архив «composer.phar» в эту директорию
Перевод:
Все настройки верны для использования Composer
Загрузка…
Composer успешно установлен: C:\Apache24\htdocs\composer.phar
Использовать: php composer.phar
создадим файл «composer.bat»
C:\Apache24\htdocs>echo @php "%~dp0composer.phar" %*>composer.bat
после выполнения данной команды рядом с архивом «composer.phar» появится файл «composer.bat»
теперь находясь в директории где расположены файлы «composer.phar» и «composer.bat» можно выполнить следующие команды
C:\Apache24\htdocs>composer -V Composer version 1.0-dev (xx...xx) 2015-xx-xx xx:xx:xx C:\Apache24\htdocs>composer -h
первая команда выводит версию composer
вторая команда выводит справочную информацию
По итогам изучения данного материала мы осуществили настройку PHP для работы в командной строке, на практике рассмотрели примеры выполнения
PHP-кода и запуска PHP скриптов в командной строке. А также нами был выполнен процесс установки composer`a.