Выполнить скрипт php windows

Запуск PHP в командной строке системы Windows

Раздел содержит примечания и подсказки, которые касаются запуска PHP
из командной строки Windows.

Замечание:

Сначала прочитайте пошаговое
руководство по установке!

PHP запускают из командной строки без внесения каких бы то ни было
изменений в Windows.

C:\php\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

Но есть несколько шагов, которые упрощают запуск PHP из командной строки.
Отдельные шаги уже выполнили, но они повторяются
здесь, чтобы объяснить последовательность действий.

    Замечание:

    Переменные окружения PATH и PATHEXT
    важные переменные, которые появились в Windows в самом начале и которые
    нельзя перезаписывать, а только добавлять для них значения.

  • Добавьте расположение исполняемого файла PHP — php.exe,
    php-win.exe или php-cli.exe,
    в зависимости от версии PHP и предпочтений отображения — в переменную
    окружения PATH. Подробнее о добавлении каталога PHP
    в переменную окружения PATH рассказывает
    запись часто
    задаваемых вопросов.

  • Добавьте расширение .PHP к переменной окружения
    PATHEXT. Это делают одновременно с изменением
    переменной окружения PATH. Выполните те же действия,
    что и в ЧАВО, но измените
    переменную окружения PATHEXT, а не PATH.

    Замечание:

    Позиция, в которую помещают расширение .PHP, будет определять,
    какой скрипт или программа выполнится при совпадении имён файлов.
    Например, расположение расширения .PHP перед расширением
    .BAT запустит скрипт, а не пакетный файл, если каталог
    содержит пакетный файл с тем же названием.

  • Настройте ассоциацию расширения .PHP с типом файла
    путём запуска следующей команды:

  • Настройте ассоциацию типа файла phpfile с исполняемым файлом PHP,
    который соответствует этому типу файла, путём запуска следующей команды:

    ftype phpfile="C:\php\php.exe" -f "%1" -- %~2
    

Эти шаги настроят запуск PHP-скриптов из любого каталога
без ввода исполняемого PHP-файла или расширения
.PHP, а параметры передадутся скрипту для обработки.

Следующий пример приводит отдельные изменения в реестре,
которые вносят вручную.

Пример #1 Пример изменений в реестре

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\php\\php-win.exe,0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\php\\php.exe\" -f \"%1\" -- %~2"

С этими изменениями эту же команду получится записать вот так:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3

или, если путь "C:\PHP Scripts" записали в переменную
окружения PATH:

Замечание:

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

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3

или

dir | script -arg1 -arg2 -arg3

Иногда скрипт просто зависает и ничего не выводит.
В реестр вносят ещё одно изменение, чтобы это заработало.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001

Дополнительную информацию по этой проблеме даёт » 
статья базы знаний Microsoft: 321788.
В Windows 10 этот параметр изменили на противоположный, и стандартная
установка Windows 10 поддерживает унаследованные дескрипторы консоли. Это » 
сообщение на форуме Microsoft даёт объяснение.

Нашли ошибку?

pimroes at gmail dot com

14 years ago

Make sure your run CMD.exe as an administrator, otherwise you'll get an "access denied" when you run the commands.

rudigerw at hotmail dot com

9 years ago

On Windows 10 starting php by only typing the script name in an elevated command prompt pops up a dialog to choose an app.
It turns out Windows does that when the program associated with phpfiles through ftype cannot be executed. In this case this happens because it is trying to run php.exe in non-admin mode, even when launched from an elevated command prompt. To fix this, locate your php.exe, right-click, "Properties", "Compatibility", under Settings check "Run this program as an administrator; then also click "Change settings for all users".

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-ev-var-setup

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

php_inline_output

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/

php_server_output

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.

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:

PHPINFO Output

PHPINFO Output

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.

Для чего нужен запуск php-скриптов через командную строку? Он позволяет проверить и отладить работу скриптов на новой версии PHP или с иными значениями PHP-директив, не меняя их для всего сайта целиком (например, если на более высокой версии PHP скрипт работает некорректно, то его запуск через консоль не нарушит работу сайта, что может произойти если сменить версию на самом сайте).

Также это позволит обойти ограничение времени работы скриптов при запуске их через браузер, которое есть на всех хостингах (делается это для того, чтобы некорректно написанные скрипты, например зацикленные, не могли нарушить работу сервера в целом) — скрипт будет работать, пока достаточно ресурсов на услуге хостинга.

Подключить SSH-доступ

1. Чтобы иметь возможность запустить PHP скрипт из командной строки, необходимо иметь услугу хостинга с активным SSH-доступом. Проверить, активен ли SSH-доступ у Вас, можно в панели хостинга в разделе «Инструменты». Если при открытии данного раздела есть пункт «Shell-клиент», то SSH-доступ на Вашей услуге хостинга открыт.

Shell-клиент в панели управления ISPmanager

Если же такого пункта нет, то Вам нужно через личный аккаунт создать запрос в службу поддержки, чтобы данный доступ предоставили.

Подключение по SSH

2. После получения SSH-доступа, подключимся к нашей услуге через любой SSH-клиент.

Либо можно использовать Shell-клиент из панели хостинга, но он не совсем удобен, для тех случаев, когда команды требуется откуда-то копировать и затем вставлять в консоль.

Команды для подключения через терминал Linux или утилиту PowerShell Windows будет иметь следующий вид:

ssh -p 34716 логин@имя или IP-адрес сервера.

Логином служит имя пользователя от панели хостинга.

Примеры:
ssh -p 34716 usertest@fry.handyhost.ru

ssh -p 34716 usertest@109.95.210.219

Подключение по SSH

После подключения можем приступать к запуску.

Запуск PHP-скрипта

3. Самый простой вариант — команда вида php/путь/к/скрипту. Такая команда запустит указанный Вами скрипт через нативную версию PHP (системную версию PHP, которая по умолчанию устанавливалась для ОС сервера с Вашей услугой хостинга), с теми настройками, которые установлены на сервере по умолчанию.

Пример:
php /var/www/usertest/data/www/fryhh.onhh.ru/info.php

Как запустить PHP-скрипт на хостинге через терминал

Узнать какая версия PHP используется по умолчанию на сервер с Вашей услугой можно командой: php -v

Как узнать какая версия PHP на хостинге в терминале

В данном примере версией PHP, используемой по умолчанию является версия 7.3.

4.  Для запуска через конкретную версию PHP указать в нашей команде путь к сборке PHP соответствующей версии. Команда будет иметь вид:
/opt/alt/phpXX/usr/bin/php/путь/к/скрипту
Примеры:
/opt/alt/php53/usr/bin/php /var/www/usertest/data/www/fryhh.onhh.ru/info.php
/opt/alt/php72/usr/bin/php /var/www/usertest/data/www/fryhh.onhh.ru/info.php
/opt/alt/php81/usr/bin/php /var/www/usertest/data/www/fryhh.onhh.ru/info.php

Список доступных сборок:
/opt/alt/php51/usr/bin/php
/opt/alt/php52/usr/bin/php
/opt/alt/php53/usr/bin/php
/opt/alt/php54/usr/bin/php
/opt/alt/php55/usr/bin/php
/opt/alt/php56/usr/bin/php
/opt/alt/php70/usr/bin/php
/opt/alt/php71/usr/bin/php
/opt/alt/php72/usr/bin/php
/opt/alt/php73/usr/bin/php
/opt/alt/php74/usr/bin/php
/opt/alt/php80/usr/bin/php
/opt/alt/php81/usr/bin/php
/opt/alt/php82/usr/bin/php

На скриншоте запуск скрипта через версию PHP 5.1.

запуск скрипта через версию PHP 5.1 в терминале

5. Важно — если в настройки той версии PHP, через которую запускается скрипт, были внесены изменения через панель хостинга, то скрипт также запустится с этими настройками PHP.

Скрипт, используемый в качестве примера в данной статье, выводит информацию о версии и настройках PHP, через которые он запущен.

На скриншоте показаны результаты его запуска через нативную версию PHP 7.4, для которой значение параметра memory_limit менялось и версию PHP 7.2, для которой изменения настроек не производилось (к результатам работы применен фильтр через функцию grep по параметру memory_limit).

результаты запуска скрипта через нативную версию PHP 7.4 в терминале

Если нам по каким-то причинам требуется запустить скрипт через определенную версию PHP с настройками, отличающимися от тех, что заданы для этой версии через панель, то можно использовать опцию -n не будут учитываться никакие ini-файлы и соответственно внесенные через панель изменения, либо опцию -d для переопределения конкретной директивы.

Примеры:
/opt/alt/php74/usr/bin/php -d memory_limit=1000M /var/www/usertest/data/www/fryhh.onhh.ru/info.php

/opt/alt/php74/usr/bin/php -n /var/www/usertest/data/www/fryhh.onhh.ru/info.php

результаты запуска скрипта через PHP 7.4 с memory_limit на 350 Мб

На скриншоте показаны результаты запуска скрипта через PHP 7.4, для которой значений параметра memory_limit установлено на 350 Мб через панель хостинга. Запуск производился с опцией -n, опцией -d memory_limit=1000M, которая устанавливает значение параметра memory_limit на 1000 Мб и без дополнительных опций. К результатам вывода также применен фильтр через функцию grep по параметру memory_limit.

Купить хостинг на PHP можно на нашем сайте.

A PHP script can be executed from the command line even without having any web server software installed.

To run the PHP script from the command line you should just have a PHP CLI (PHP Command Line Interface) installed on your system.

This note shows how to run the PHP script from the command line and how to get the PHP CLI installed on Windows, Linux and MacOS.

Cool Tip: How to find the location of the php.ini file! Read more →

Let’s say we have a script.php file with the simplest PHP code:

<?php echo "Hello World!"; ?>

To run the script.php from the command line, execute:

$ php script.php
- sample output -
Hello World!

Install PHP CLI

The messages as follows mean you are missing the php-cli on your system and should install it first to be able to run the PHP scripts from the command line:

‘php’ is not recognized as an internal or external command,
operable program or batch file
– or –
php: command not found

To check whether php-cli is installed, execute:

$ php -v
- sample output -
PHP 7.4.3 (cli) (built: Nov 25 2021 23:16:22) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

MacOS comes with PHP installed out of the box.

To install php-cli on Linux:

$ sudo apt install php-cli

To install PHP on Windows, download a ZIP package with the required version, extract it to C:\php and add this folder to a %PATH% environment variable.

For this, press the ⊞ Win keybutton to open the start menu and type in envi to search for “Edit the system environment variables” or “Edit environment variables for your account” links.

Start the editor, search for the Path variable name, click on “Edit” and add C:\php.

To create the default PHP’s configuration file, that is initially missing on Windows, copy C:\php\php.ini-development to C:\php\php.ini:

C:\> copy C:\php\php.ini-development C:\php\php.ini

Finally, after getting the PHP installed, you should be able to run the script.php from the command line without any issues.

C:\> php script.php
- sample output -
Hello World!

Was it useful? Share this post with the world!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Калькулятор на паскале windows forms
  • Как транслировать экран айфона на ноутбук windows
  • 80070426 ошибка windows 10
  • Политика охлаждения системы windows 11
  • Как активировать microsoft office 2019 на windows 11