Как добавить php в path windows 10

Вполне возможно, что вам не приходилось ранее сталкиваться с PATH и выражениями «переменная окружения», поэтому я кратко поясню, что это такое.

Вполне возможно, что вам не приходилось ранее сталкиваться с PATH и выражениями «переменная окружения», поэтому я кратко поясню, что это такое.

Переменная PATH содержит список папок, в которых Windows ищет исполнимые файлы.

В графическом интерфейсе, когда для запуска программ используются ярлыки, значение PATH не очень большое. Но если вы запускаете программу в командной строке, то PATH может пригодиться. Опять же, если вы указываете полный путь до файла, например, C:UsersAlexDocumentsphp.exe, то PATH не используется. Но если, например, вы запускаете программу только по имени файла или просто по имени (без файлового расширения), то запустится ли программа, будет зависеть от содержимого переменной PATH.

К примеру, я в командной строке пытаюсь запустить файл (без указания полного пути)

php.exe

В этом случае операционная система посмотрит все записи PATH (там может быть указано несколько каталогов). Затем в каждом из этих каталогов Windows попытается найти файл php.exe. Если файл найден, то он будет запущен. Если файл не найден, то будет выведено соответствующее сообщение.

По сути, что-то дописывать в переменную PATH нужно только тем, кто много работает с командной строкой. К примеру, вы программист и размещаете свои программы в папке C:MyApps и при этом вы часто запускаете свои утилиты командной строки. В этом случае вы можете добавить C:MyApps в PATH и после этого для запуска программ из этой папки вам уже не нужно будет каждый раз вводить полное имя (например, C:MyAppsparser.exe), а достаточно будет в командной строке ввести только имя файла:

parser.exe

Нужно ли в Windows добавлять PHP в переменную окружения

При установке и настройке PHP в Windows необязательно добавлять в PATH путь до PHP, но это рекомендуется делать.

Во-первых, вы сможете запускать PHP используя сокращённую запись:

php my_script.php

вместо

C:ServerbinPHPphp.exe my_script.php

Во-вторых, ряд расширений (которые включаются в файле php.ini) работают некорректно, если вы не прописали в PATH путь до PHP; в том числе, это касается такого довольно популярного расширения как cURL. По идее — это какой-то баг этих расширений или PHP, но нам самим придётся исправлять ситуацию, поскольку эта проблема существует уже много лет.

Как добавить PHP в системные переменные среды

Итак, приступим.

Нажмите кнопку Windows (это которая раньше была кнопкой «Пуск»), начните набирать «Изменение системных переменных среды»

и откройте соответствующее окно настроек.

Там нажмите «Переменные среды», откроется:

В окне «Системные переменные» найдите и кликните на Path, потом нажмите «Изменить»:

Далее «Создать» и впишите туда «C:ServerbinPHP»:

Поднимите запись в самый Вверх:

Закройте все окна с сохранением сделанных изменений.

Перезапустите сервер.

Связанные статьи:

  • Как подключить PHP к Apache на Windows (100%)
  • Установка Apache, PHP, MySQL и phpMyAdmin на Windows XP (100%)
  • Для чего нужен веб-сервер Apache (100%)
  • Готовая сборка Apache для Windows XP (100%)
  • Как обновить PHP (100%)
  • Как установить MariaDB 7.4 в Windows (RANDOM — 50%)

В различных руководствах и документациях часто встречается пункт «добавьте путь до чего либо в переменную PATH». Что это за переменная и как в нее что-то добавить описано ниже, в этой заметке.

Что такое переменная PATH и для чего она нужна?

Если коротко, то PATH это такая переменная, с помощью нее операционная система ищет  исполняемые объекты, которые вы пытаетесь вызвать в командной строке.

Другими словами, PATH позволяет запускать исполняемые файлы, без указания их точного местоположения на диске. Например, после установки Python на Windows, для выполнения скрипта Питона нам достаточно в командной строке набрать:

python имя_выполняемого_файла.py

Нам не пришлось указывать точного пути до интерпретатора Питона (в моем случае C:UsersAlexAppDataLocalProgramsPythonPython37-32python.exe) как раз из-за установленной переменной PATH.

соответствующую программу. Этим можно воспользоваться в своих целях двумя способами:

Как добавить PHP в системные переменные среды?

Для примера добавим PHP в переменную PATH.

У меня на компьютере интерпретатор php располагается в каталоге C:xamppphp72, поэтому чтобы выполнить php скрипт в командной строке, мне нужно ввести:

C:xamppphp72php.exe имя_скрипта.php

Но согласитесь, гораздо удобней так:

php имя_скрипта.php

К тому же некоторые программы, например IDE будут автоматически «понимать» где расположен интерпретатор php.

Итак, чтобы добраться до настроек переменной PATH, нам сначала нужно открыть Панель управления Windows, поскольку Микрософт постоянно меняет ее положение, проще всего найти ее через поиск:

Панель управления Windows 10 через поиск

Далее нужно выбрать Система -> Дополнительные параметры системы.

Дополнительные параметры системы Windows 10

В последних версия Windows 10 Дополнительные параметры системы открываются по такому пути:

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

Дополнительные параметры системы Windows 10

В открывшемся окне Свойства системы нужно выбрать вкладку Дополнительно и внизу будет кнопка Переменные среды.

Переменные среды Windows 10

Выбираем переменную среды Path и нажимаем Изменить. После этого нажимаем кнопку Создать и вводим пусть до папки, где расположен наш интерпретатор PHP, в моем случае C:xamppphp72.

Далее везде нажимаем ОК, все, переменная среды для PHP сохранена.

Теперь, если перезапустить командную строку, можно выполнять php скрипты не указывая полного пусти к интерпретатору.

php hello.php

This section holds common questions about the way to install
PHP. PHP is available for almost any OS, and almost any web server.

To install PHP, follow the instructions in Installation and Configuration.

  1. Why shouldn’t I use Apache2 with a threaded MPM in a production environment?

  2. Unix/Windows: Where should my php.ini file be
    located?

  3. Unix: I installed PHP, but every time I load a document, I get the
    message ‘Document Contains No Data’! What’s going on here?

  4. Unix: I installed PHP using RPMS, but Apache isn’t processing the
    PHP pages! What’s going on here?

  5. Unix: I patched Apache with the FrontPage extensions patch, and
    suddenly PHP stopped working. Is PHP incompatible with the
    Apache FrontPage extensions?

  6. Unix/Windows: I have installed PHP, but when I try to
    access a PHP script file via my browser, I get a blank screen.

  7. Unix/Windows: I have installed PHP, but when try to
    access a PHP script file via my browser, I get a
    server 500 error.

  8. Some operating systems: I have installed PHP without errors,
    but when I try to start Apache I get undefined symbol errors:

    [mybox:user /src/php5] root# apachectl configtest
    apachectl: /usr/local/apache/bin/httpd Undefined symbols:
    _compress
    _uncompress

  9. Windows: I have installed PHP, but when I try to access
    a PHP script file via my browser, I get the error:

    cgi error:
    The specified CGI application misbehaved by not
    returning a complete set of HTTP headers.
    The headers it did return are:

  10. Windows: I’ve followed all the instructions, but still can’t
    get PHP and IIS to work together!

  11. When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami,
    I get the following error: Security Alert! PHP CGI
    cannot be accessed directly..

  12. How do I know if my php.ini is being found and read? It
    seems like it isn’t as my changes aren’t being implemented.

  13. How do I add my PHP directory to the PATH
    on Windows?

  14. How do I make the php.ini file available to PHP on windows?

  15. Is it possible to use Apache content negotiation (MultiViews option)
    with PHP?

  16. Is PHP limited to process GET and POST request methods only?

Why shouldn’t I use Apache2 with a threaded MPM in a production environment?

PHP is glue. It is the glue used to build cool web applications by
sticking dozens of 3rd-party libraries together and making it all appear
as one coherent entity through an intuitive and easy to learn language
interface. The flexibility and power of PHP relies on the stability and
robustness of the underlying platform. It needs a working OS, a working
web server and working 3rd-party libraries to glue together. When any of
these stop working PHP needs ways to identify the problems and fix them
quickly. When you make the underlying framework more complex by not having
completely separate execution threads, completely separate memory
segments and a strong sandbox for each request to play in, further
weaknesses are introduced into PHP’s system.

If you want to use a threaded MPM, look at a FastCGI configuration
where PHP is running in its own memory space.

Unix/Windows: Where should my php.ini file be
located?

By default on Unix it should be in /usr/local/lib
which is <install-path>/lib.
Most people will want to change this at compile-time with the
—with-config-file-path
flag. You would, for example, set it with something like:

--with-config-file-path=/etc

And then you would copy php.ini-development from
the distribution to /etc/php.ini and
edit it to make any local changes you want.

--with-config-file-scan-dir=PATH

On Windows the default path for the php.ini file is the Windows
directory. If you’re using the Apache webserver, php.ini is first
searched in the Apaches install directory, e.g. c:program
filesapache groupapache
. This way you can have
different php.ini files for different versions of Apache on the same
machine.

See also the chapter about the configuration file.

Unix: I installed PHP, but every time I load a document, I get the
message ‘Document Contains No Data’! What’s going on here?

This probably means that PHP is having some sort of problem
and is core-dumping. Look in your server error log to see if
this is the case, and then try to reproduce the problem with
a small test case. If you know how to use ‘gdb’, it is very
helpful when you can provide a backtrace with your bug report
to help the developers pinpoint the problem. If you are using
PHP as an Apache module try something like:

  • Stop your httpd processes

  • gdb httpd

  • Stop your httpd processes

  • > run -X -f /path/to/httpd.conf

  • Then fetch the URL causing the problem with your browser

  • > run -X -f /path/to/httpd.conf

  • If you are getting a core dump, gdb should inform you of this now

  • type: bt

  • You should include your backtrace in your bug report. This should be submitted to
    » https://github.com/php/php-src/issues

If your script uses the regular expression functions
(preg_match() and friends), you should make sure
that you compiled PHP and Apache with the same regular
expression package. This should happen automatically with
PHP and Apache 1.3.x

Unix: I installed PHP using RPMS, but Apache isn’t processing the
PHP pages! What’s going on here?

Assuming you installed both Apache and PHP from RPM packages,
you need to uncomment or add some or all of the following lines
in your httpd.conf file:

# Extra Modules
AddModule mod_php.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so

And add:

AddType application/x-httpd-php .php

… to the global properties, or to the properties of the
VirtualDomain you want to have PHP support added to.

Unix: I patched Apache with the FrontPage extensions patch, and
suddenly PHP stopped working. Is PHP incompatible with the
Apache FrontPage extensions?

No, PHP works fine with the FrontPage extensions. The problem
is that the FrontPage patch modifies several Apache structures,
that PHP relies on. Recompiling PHP (using ‘make clean ; make’)
after the FP patch is applied would solve the problem.

Unix/Windows: I have installed PHP, but when I try to
access a PHP script file via my browser, I get a blank screen.

Do a ‘view source’ in the web browser and you will probably
find that you can see the source code of your PHP script.
This means that the web server did not send the script to
PHP for interpretation. Something is wrong with the server
configuration — double check the server configuration against
the PHP installation instructions.

Unix/Windows: I have installed PHP, but when try to
access a PHP script file via my browser, I get a
server 500 error.

Something went wrong when the server tried to run PHP. To
get to see a sensible error message, from the command line,
change to the directory containing the PHP executable
(php.exe on Windows) and run
php -i. If PHP has any problems running,
then a suitable error message will be displayed which will
give you a clue as to what needs to be done next. If you
get a screen full of HTML codes (the output of the
phpinfo() function) then PHP is working,
and your problem may be related to your server configuration
which you should double check.

Some operating systems: I have installed PHP without errors,
but when I try to start Apache I get undefined symbol errors:

[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

This has actually nothing to do with PHP, but with the MySQL
client libraries. Some need —with-zlib, others do not. This
is also covered in the MySQL FAQ.

Windows: I have installed PHP, but when I try to access
a PHP script file via my browser, I get the error:

cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

This error message means that PHP failed to output anything
at all. To get to see a sensible error message, from the
command line, change to the directory containing the PHP
executable (php.exe on Windows) and run
php -i. If PHP has any problems running,
then a suitable error message will be displayed which will
give you a clue as to what needs to be done next. If you
get a screen full of HTML codes (the output of the
phpinfo() function) then PHP is working.

Once PHP is working at the command line, try accessing the
script via the browser again. If it still fails then it
could be one of the following:


  • File permissions on your PHP script,
    php.exe, php5ts.dll,
    php.ini or any PHP extensions you are trying to load are such
    that the anonymous internet user
    ISUR_<machinename> cannot access them.

  • The script file does not exist (or possibly isn’t where you
    think it is relative to your web root directory). Note that
    for IIS you can trap this error by ticking the ‘check file
    exists’ box when setting up the script mappings in the
    Internet Services Manager. If a script file does not exist
    then the server will return a 404 error instead. There is
    also the additional benefit that IIS will do any
    authentication required for you based on the NTLanMan
    permissions on your script file.

Windows: I’ve followed all the instructions, but still can’t
get PHP and IIS to work together!

Make sure any user who needs to run a PHP script has the rights
to run php.exe! IIS uses an anonymous user
which is added at the time IIS is installed. This user needs
rights to php.exe. Also, any authenticated
user will also need rights to execute php.exe.
And for IIS4 you need to tell it that PHP is a script engine.
Also, you will want to read
this faq.

When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami,
I get the following error: Security Alert! PHP CGI
cannot be accessed directly.
.

You must set the
cgi.force_redirect directive to 0.
It defaults to 1 so be sure the directive
isn’t commented out (with a ;). Like
all directives, this is set in php.ini

Because the default is 1, it’s critical
that you’re 100% sure that the correct php.ini file is being
read. Read this faq
for details.

How do I know if my php.ini is being found and read? It
seems like it isn’t as my changes aren’t being implemented.

To be sure your php.ini is being read by PHP, make a call to
phpinfo(). Near the top, there will be a
listing called Configuration File (php.ini).
This will tell you where PHP is looking for php.ini and
whether or not it’s being read. If just a directory PATH exists,
then it’s not being read, and you should put your php.ini
in that directory. If php.ini is included within the PATH,
it is being read.

If php.ini is being read and you’re running PHP as a module,
then be sure to restart your web server after making changes to
php.ini

See also php_ini_loaded_file().

How do I add my PHP directory to the PATH
on Windows?

On Windows:

  • Go to Control Panel and open the System icon (Start → Control Panel)

  • Go to the Advanced tab

  • Click on the ‘Environment Variables’ button

  • Look into the ‘System Variables’ pane

  • Find the Path entry (you may need to scroll to find it)

  • Double click on the Path entry

  • Enter your PHP directory at the end, including ‘;’ before (e.g.
    ;C:php)

  • Press OK

Note:

Be sure to reboot after following the steps above to ensure that the
PATH changes are applied.

How do I make the php.ini file available to PHP on windows?

There are several ways of doing this. If you are using Apache,
refer to the Apache documentation, otherwise
you must set the PHPRC environment variable.

Is it possible to use Apache content negotiation (MultiViews option)
with PHP?

If links to PHP files include extension, everything works perfect. This
FAQ is only for the case when links to PHP files don’t include extension
and you want to use content negotiation to choose PHP files from URL
with no extension.
In this case, replace the line AddType application/x-httpd-php
.php
with:

AddHandler php5-script php
AddType text/html php

This solution doesn’t work for Apache 1 as PHP module doesn’t catch
php-script.

Is PHP limited to process GET and POST request methods only?

No, it is possible to handle any request method, e.g. CONNECT. Proper
response status can be sent with header().
If only GET and POST methods should be handled, it can be achieved with
this Apache configuration:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

per dot fikse at ipj dot no

17 years ago


Installing PHP 4 or 5 on Windows Server 2003 x64 results in http error 505. This is not a PHP bug. It is due to running a 32-bit ISAPI DLL under the 64-bit version of IIS 6, as documented here: http://support.microsoft.com/?id=895976

Solution: Flip the Metabase flag for Enable32bitAppOnWin64 as described in http://support.microsoft.com/?id=894435 ,
like this: CSCRIPT ADSUTIL.VBS SET W3SVC/AppPools/Enable32bitAppOnWin64 1

(Alternatively with full path: cscript %SYSTEMDRIVE%inetpubadminscriptsadsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1)


emzeperx at emzeper dot hu

17 years ago


You do not have to restart the whole system make effect of changing the PATH env var. For me (sbs2003) worked automatically.
on older systems you can use

set $Path=%path%;c:php

command to extend immediately the path var.


nigel dot salt at hotmail dot com

19 years ago


Finally got IIS 5 and PHP 5 to talk. 

What worked for me was:

1) Set
[HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServices
W3SVCParametersScript Map]
".php"="your path to php\php.exe"

2) ensure there is not a php.ini in the windows system folder and that there is one wherever you've put PHP

3) edit php.ini and set cgi force redirect to 0 and cgi.rfc2616_headers = 1

4) Put the PHP scripts in their own folder underneath the inetpub root

5) Open the IIS console, right click your new php folder
In the Directory tab
set application name to the name of the folder
set executable and script as permission
set application protection to low
Click configuration and check that .php is mapped to wherever you put
PHP

Restart IIS

Try a very simple PHP page and it should work

Nigel


john dot calder at manukau dot ac dot nz

14 years ago


WINDOWS 2003 and IIS.  BIG LESSON FOR ME was "don't mess with the optional components".
I had lots of trouble until I tried installing without asking for extras and then it was very smooth.
I have found no need to set up paths. 
I have found no need to configure IIS. 
I have found no need to change security on the PHP folder.

What works for me with Windows/IIS:

1.  You need to be logged-on as "administrator"

2.  Run  "php-5.2.6-win32-installer.msi"
Your ONLY action during this wizard is to select "IIS ISAPI" as the webserver.  Do NOT CHANGE anything else!  I am guessing that the optional extras apply only to Apache because after enabling them I see Apache-related error messages.

3.  Setup a test virtual directory as you would for an ASP or ASP.NET web app.  eg "phptest"
Then use notepad to create a test page eg "test.php"
<?php
phpinfo
();
?>

4.  In Internet Explorer, test with eg this address
http://localhost/phptest/test.php

IF this does not give you a beautiful page of details THEN start reading other advice on this page - especially helpful for me was the faq advice to test run "php.exe -i" from the command prompt.


charleslynch at xybersoftware dot com

14 years ago


One final note to the message below if you are getting the message about not having rights to execute...You need to use IIS right click on the website and choose 'Properties/Home Directory' then on the 'Execute Permissions' combo box you need to choose 'Scripts only'...Click ok...another dialog may appear asking which directories to apply the action too...choose any directories that you intend on using php in and click ok...It should work now...

JUSTANOTHERUSER

17 years ago


<LimitExcept GET POST>
Deny from all
</LimitExcept>

Does not work with Apache2+ & PHP5 . Apache Refuses to start


jimo at mail dot azhsv dot com

19 years ago


PHP 4 and IIS 6.0 (Windows Server 2003)

Had difficulty getting PHP 4.3.3 to work with Win2003 Ent Server for use with SquirrelMail.  Problem found and believed solved.  Appears to be something New with IIS 6.0 (More security by Micro$oft)  Was getting 404 error and php was not being run as a cgi even though it was in extensions and IIS user had rights to execute it. (php from command line operated correctly)

If you are installing on Windows Server 2003 (only have Enterprise Edition ? Not sure if this applies to standard edition), and you have done the normal procedures for inclusion of PHP scripts (either ISAPI or CGI) in IIS, you will still get a 404 error when attempting to execute those scripts even though IIS has rights and the extension points to the correct file.  To alleviate this problem, perform the following:

1.    Open a command prompt window
2.    Change to C:windowssystem32
3.    Execute the command:  cscript  iisext.vbs /AddFile c:phpphp.exe 1 php 0 php
4.    Execute the command:  cscript iisext.vbs /EnFile c:phpphp.exe
5.    To check for correct execution of the above,
6.    Execute the command:  cscript IisExt.vbs /ListFile ? the php extension should be listed

If you try just step 4 without step 3 you get an error that the file is not in the list (and won?t be there till you do step 3 above)

After this, IIS seems to like the php extension and work normally.

For additional reference, see the below 3 Micro$oft KB Articles:
HOWTO: Enable and Disable ISAPI Extensions and CGI Applications in IIS 6.0 (MS KB Article 328360)

HOWTO List Web Server Extensions and Extension Files in IIS 6.0 (MS KB Article 328505)

HOWTO Add and Remove Web Service Extension Files in IIS 6.0 (MS KB Article 328419)


ssaxena at nriol dot com

12 years ago


Here are my struggle to get PHP 5.2.12 working on Windows XP SP3, IIS 5.1 (Please note Win XP SP3 has issue of FastCGI)

1. Dowloaded installer and installed in C:Program FilesPHP as ISAPI module

---->Did not work

Added php5isapi.dll in ISAPI Filter and added the extension .php in Home Dir->Configuration
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

(And the Google was pointing to the Fast CGI issue; Don't know why microsoft has MS-FAST ! )
Uninstalled the PHP and cleaned up the folders, PATH environment variable & PHPRC, the IIS settings and registry entries and shut down(restart is different from shut down) the system to make it very clean

2. Reinstalled the PHP in C:PHP as ISAPI and did the same as above in IIS
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

Uninstalled and cleaned up same as above and took a breath to make sure what I am doing wrong.
Shutdown the system.

3. Unzipped the php-5.2.12-Win32.zip and did the same as above (this time manually PATH variable and security permission for the PHP folder and following settings)

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:Inetpubwwwroot"
extension_dir = "C:PHPext"
cgi.force_redirect = 0

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system.

4. Downloaded Microsoft Web Platform Installer 2.0 and select the PHP+Fast CGI+Windows Cache for PHP extension and Web Deployment Tools
restarted the system to take effect the settings

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system

5. Took the prev version of PHP php-5.2.4-Win32.zip unzip the folder and did the following changes:

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:Inetpubwwwroot"
extension_dir = "C:PHPext"
cgi.force_redirect = 0

set the security permission as IIS_machinename with full access to the C:PHP folder

------->IT GOT WOKRING

Hope people would be aware of php-5.2.12 and would love the php-5.2.4


scott at chaisson dot net

15 years ago


Windows 2000 Server and IIS (SP4 and all patches):

After many frustrating hours of trying to figure out the install (again), It took a while, but here are a couple tips:

PHP working with IIS uses c:winntphp.ini

It doesn't matter what you set the path to, nor what you set the PHPRC environment variable to. After you get PHP running correctly in the installation folder (using php -i) copy the php.ini file into the c:winnt folder.

Here's what worked for me:

- Add PHP path to System environment variable

- Add php5activescript.dll from http://snaps.php.net/ to the PHP folder, then Register it: "regsvr32 php5activescript.dll"

Set extension_dir and doc_root directives in PHP.INI:
  extension_dir = C:WWWPHPext
  doc_root = C:WWWSite
  cgi.force_redirect = 0

(the last cgi.force_redirect isn't required, but I like to set it anyway)

Copy the .INI file into WINNT folder

In IIS Manager, right-click "Default Web Site", Click "Home Directory",
  Click "Configuration", "Add" the ISAPI application:
    Executable: <your php install>php5isapi.dll
    Extension: .php
    Limit to: GET,HEAD,POST
    Check: "Script Engine"
    Uncheck: "Check that file exists"

Finally: Set up an ISAPI filter:
  Click the "ISAPI Filters" tab,
  Filter Name: PHP
  Executable: <your php install>php5isapi.dll

Notes: You don't have to set any of your folders as "Script source" folders. .PHP files aren't scripts, merely text files that require processing before being shipped off to the browser, which is what the ISAPI filter does.

Finally, working again.

Chase


Meiki67 skipthis at geemail

15 years ago


Had a hard day to MSI install 5.2.3 on WinXP with MySQL. I use a drive substitution (subst drive: path - in my case subst d: c:drive_d) and installed PHP in D:PHP - which in reality is C:DRIVE_DPHP.  To make a long story short - only after (1) changing all substituted D: back to C:DRIVE_D and (2) resolving all DOS short names to Win long names PHP started to work. The first one is clear - the substitution works only for the active console user - not for services or IUSR. For the second one I have no explanation, since DOS short names should work systemwide - maybe Win handles them correctly but PHP not ?

BTW <?php phpinfo(); ?> was of tremendeous help

Meiki


knutw at sparhell dot no

16 years ago


I recntly upgraded from PHP 5.1 to 5.2 on my Windows Server 2003 using IIS6. I selected CGI as before. My PHP folder is as always C:Program FilesPHP. I also edited my brand new php.ini, enabling all my old extensions and recommended settings for IIS. I like not to keep my old config into a new version.

After upgrade, I just got blank pages in my browser, and the response status was 404 Not found.

I checked my installation twice, using this FAQ, but got no way.

Then I went to IIS Manager, Web Service Extensions. The php Service Extension was Allowed as it should. I deleted the Service Extension and added it. The old extension used short file names containing tilde (PROGRA~) character, but I don'æt know if that gas anything to do with the problem. Anyway, after allowing my" new" Service Extension, pointing to php-cgi.exe as before, mye web sites suddenly worked. So will revommend anyone with thos problem to delete and add the Servcie Extension. It didn't help re-allowing it, restarting IIS or the complete server.


jeff_graham at datacenterservices dot net

19 years ago


As stated within the note "jimo at mail dot azhsv dot com
29-Nov-2003 04:33
PHP 4 and IIS 6.0 (Windows Server 2003)," I found the same steps were requiered for installation of PhP 5 beta 3 on my Windows 2003 server (Standard Edition)

Curtis

15 years ago


I have some additional troubleshooting tips for 53.7, which deals with getting a blank screen on your browser when running a PHP script.

In addition to server misconfiguration, it may also be that PHP isn't configured to output errors to the browser, which is the case if you or your host uses a more secure php.ini. If this is the case, you need to find out where errors are being logged to find out if any errors are preventing normal output from being delivered to the client.

If you have access to php.ini, check the 'display_errors' directive, which is, by default, located under the 'error_reporting' directive. It's helpful to have 'display_errors' on during debugging phases, but best to have it off in production environments.

Related functions: http://php.net/ini_set | http://php.net/error_reporting | http://php.net/error_log


peter dot mosinskisNOSPAM at csuci dot edu

19 years ago


Running Win2K AS + IIS5.0 + PHP 4.3.1, I ran into a nasty problem that I mistakenly thought had to do with something in the php.ini configuration. When I would try to submit a form using the HTTP method GET it would work, but I would get a "404 Page Not Found" error using the POST method.

All my permissions were set correctly, the php.ini was configured correctly. It had to do with URLScan being installed on IIS (see below)

Page 404 File Not Found Error When Using POST method in PHP (and Perl, and otherwise)
-------------------------------------------

This is related to the Microsoft URLScan utility. If you have this problem, the IIS administrator has probably run the IIS Lockdown tool as well as configured URLScan to reject this type of HTTP method when sent in a URL. These tools are meant to enhance web server security.

URLScan configuration files can be found in the WINNTsystem32inetsrvurlscan folder on the web server. Specifically, the file to modify is urlscan.ini.

The changes to make are as follows:
1. Make sure UseAllowVerbs=1 under [options]
2. Under the [AllowVerbs] section, list your allowed HTTP methods to include:
    GET
    POST

For more information on the IIS Lockdown tool and URLScan, visit http://technet.microsoft.com


christianfelix at laszlo dot com

15 years ago


For Windows XP users

Just add php.ini to windows/system 32 and also save a copy in the setup folder e.g. c:/php/php.ini, c:/php5/php.ini,

You have to follow the suggestions, add to path, uncomment extensions and voila!!


monroe at peoplego dot com

20 years ago


INSTALLATION ON OPENBSD 3.1 VIA PORTS COLLECTION
Would have succeed but no mysql support.
I commented out the FLAVORS+= dbase filepro mysql mysql_bundled postgresql iodbc in the /usr/ports/www/php4/Makefile and in the configure options added 
--with-mysql=/usr/local   and it worked.

Good Luck


joerg at fenin dot de

15 years ago


To limit HTTP Request Methods on the Apache server running PHP you should use mod_rewrite or mod_security instead of LimitExcept, to give you more control over the handling of such http errors.  Can go in .htaccess file or httpd.conf

# mod_rewrite
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|POST)$
  RewriteRule .* - [F,L]
</IfModule>

# mod_security
<IfModule mod_security.c>
  SecFilterSelective REQUEST_METHOD "!^(GET|HEAD|POST)$" "deny,log,status:403"
</IfModule>

You can use the php request method scanner at askapache to see exactly how your server deals with various request methods, and check that your server is configured properly.. 

http://www.askapache.com/online-tools/request-method-scanner/


Anonymous

16 years ago


After setting the PHPRC environment variable, none of my PHP files would hit the preprocessor. The browser was just serving out PHP source code right there in the "view source."

The manual was telling me to set this var to "c:php," but nothing was working. It's almost as if IIS/Win2000 wasn't reading my php.ini at all.

After I set that variable to "c:phpphp.ini," all of a sudden I was getting honest to goodness PHP pages working.


barry dot fagin at usafa dot af dot mil

18 years ago


Fixing 404 (file not found) errors with PHP 5.0.3 and IIS 6.0

IIS 6.0 is installed with security settings that don't permit dynamic content.  This means that even if all the hints in the FAQ are paid attention to (.ini modified correctly, security and permissions correct for IUSR_xxx user, etc), you still get 404 errors for all php files. 

To fix this:  IIS Manager -> expand local computer -> Web Services Extensions -> Add web service or extension -> .php, browse to c:phpphp-cgi.exe or wherever you had the php executable installed. That plus setting the doc_root in the .ini file solved the problem.

--BF


В этой статье вы узнаете как установить php 7.0 и выше на Windows 10, очень просто, надеюсь эта статья будет полезна для вас.

Скачать PHP:

Сначала вам надо скачать PHP 7 для Windows 10 c сайта или для Windows 7, для этого заходим по ссылки, там нажимаем на Zip.

Скачать PHP 7.0

Как можете заметить, я скачиваю тут x64 битную, но не переживаете, там также вы можете скачать x32 битную версию, для этого надо прокрутить чуть ниже и найти, где будет написано x86, если в друг у вас архитектура не x64.

Установка PHP:

После того как скачали сам PHP, пришло время его установить, для архивируем архив который скачали, и создаём папку куда положим все файлы.

Архивируем PHP

Как можете заметить, я поместил все файлы в папку в документах, но это ещё не всё.

Теперь на надо добавить PHP в path, чтобы была возможность запускать PHP скрипты из командной строки, для этого заходим в «Этот компьютер» и там нажимаем правой кнопкой мыши, выбираем «Свойства».

Заходим в свойства Windows 10

Дальше в открывшемся окне с боку выбираем «Дополнительные параметры системы».

Заходим в дополнительные параметры системы

В открывшемся окне нажимаем на кнопку «Переменные среды…».

Заходим в параметры среды

В открывшемся окне выбираем внизу «Path» и нажимаем кнопку изменить.

добавить php в path

Нажимаем «Создать» и вписываем путь, куда вы архивировали ваш PHP, на этом всё и заканчивается, поздравляю вас, вы установили и подключили PHP.

Тест PHP:

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

Программа просто выводит «Hello World!» на экран командной строки. Запускаем программу через CMD или командную строку, вот что вышло.

Тест программы на PHP

Как можете заметить всё работает нормально, значит и PHP установился нормально.

Вывод:

Вот такая статья получилась где показывалось как установить PHP 7.0 и выше на Windows 10, надеюсь для вас она была полезна, и вы ещё будите читать наши статьи.

Также посмотрите: Как выучить язык PHP с нуля и максимально эффективно.

Подписываетесь на соц-сети:

Оценка:

Загрузка…

Также рекомендую:

Первые два года своей профессиональной деятельности в создании сайтов я работал под Linux. Но при всей гибкости и мощности этой системы она, всё же, неудобна в мелочах. Однажды, эти мелочи перевесили все прочие плюсы и я решился пересесть на Windows. Сейчас я совершенно не жалею о потраченном времени на настройку среды разработки, а моим рабочим ноутбуком, который по совместительству является и домашним, стало гораздо удобнее пользоваться.

Этот пост может сэкономить время тем, кто так же как и я собирается перейти на Windows и тем, кто только ещё начинает работать PHP-программистом или веб-разработчиком. Для полноценной веб-разработки понадобятся: виртуальная среда, система контроля версий, менеджеры зависимостей, система сборки приложений, система развёртки приложений и, конечно, хороший редактор кода. Я не буду рассказывать зачем нужен каждый из компонентов, а лишь дам инструкцию по его установке в Windows. Я использую Vagrant, Composer, NPM, Bower, Git, Gulp, Capistrano и PHPStorm, дальше пойдёт речь именно об этих технологиях. Инструкции даны для Windows 10.

Начнём с установки PHP

Для разработки я использую PHP 7, чтобы мой код был совместим с ним, когда я соберусь переезжать. На боевых серверах у меня пока что PHP 5.6. Для того, чтобы случайно не написать код, который не будет работать в продакшене в моём PHPStorm указан уровень языка 5.6.

Для работы в Windows у PHP есть специальная версия языка, которую можно скачать с сайта PHP. Для того, чтобы установить PHP 7 в операционной системе Windows понадобится программа Visual C++ Redistributable for Visual Studio 2015, которую можно скачать с официального сайта Майкрософта. Установка этой программы не содержит никаких трудностей, нужно просто нажимать кнопку «Далее».

После установки Visual C++ Redistributable скачиваем архив PHP 7 для Windows (VC14 Non Thread Safe x64 или x86 в зависимости от разрядности системы) c официального сайта PHP. В архиве нет инсталлятора, его просто нужно распаковать в папку где-нибудь на диске. В пути к этой папке не должно быть пробелов и русских букв, у меня это C:php.

После распаковки нужно добавить PHP в системный PATH для того, чтобы можно было запускать PHP из любого каталога:

  1. нажимаем win+x;
  2. переходим в Advanced system settings;
    Добавляем PHP в PATH шаг 1
  3. выбираем Environment Variables;
    Добавляем PHP в PATH шаг 2
  4. выбираем переменну PATH и нажимаем кнопку Edit;
    Добавляем PHP в PATH шаг 3
  5. нажимаем кнопку New и вводим адрес каталога с распакованным PHP, например C:php;
    Добавляем PHP в PATH шаг 4
  6. нажимаем кнопку Ok.

Теперь нужно настроить PHP для работы:

  1. переименовываем файл php.ini-production в php.ini;
  2. раскоментируем (убираем знак ;) перед строчками:
    • extension=php_curl.dll;
    • extension=php_gd2.dll;
    • extension=php_mbstring.dll;
    • extension=php_openssl.dll;
    • extension=php_pdo_mysql.dll;
    • extension=php_pdo_sqlite.dll;
    • extension=php_sqlite3.dll.

Всё, PHP 7 установлен в системе и готов к использованию.

Система контроля версий

Установить Git на Windows проще простого. В качестве приятного бонуса вместе с Git поставляется консоль Git bash. Работать с этой консолью гораздо удобнее, чем со стандартной CMD в Windows. Кроме того, она понимает некоторые полезные линуксовские команды, такие как find, ls и прочие.

При установке Git под Windows вам нужно будет прописать git.exe в PATH вашей системы, чтобы Git можно было запускать из любого места в командной строке. А также указать Git’у, чтобы при получении кода он не менял символы окончания строк в файлах (эти символы отличаются на системах с Linux и Windows). Всё это делается парой кликов мышкой через инсталятор Git.

Вот скриншоты важных страниц установки Git:

  1. Экран выбора установки программ в PATH вашей системы. Выбирайте средний вариант — так вы сможете использовать Git из командной строки из любого каталога и не потревожите стандартные программы Windows find и sort;
    выбор изменений PATH при установке GIt
  2. Здесь мы указываем как Git будет поступать с символами окончания строк. На Windows и Linux эти символы разные и Git может менять их перед отправкой и получением кода из репозитория. В моём случае лучший выбор — это не вмешиваться в код при получении и следить за тем, чтобы в репозиторий не попадали файлы с символами Windows-style.
    Выбор изменения символов окончания строк при установке Git
  3. Последний экран не столь важен, здесь можно указать что будет в основе надстройки Git Bush — стандартная консоль Windows или MinTTY. Если у вас Windows до 10 версии, то лучше выбрать MinTTY.
    указание какой консолью пользоваться Git'у

После установки укажите Git’у ваше имя и электронную почту. Эти данные будут передаваться с каждым коммитом и их нельзя будет изменить.

Откройте Git Bush и запустите две команды:

  • git config --global user.name "Ваше_Имя"
  • git config --global user.email Ваша_Электронная_Почта

На этом первоначальная настройка Git закончена.

Менеджеры зависимостей NPM, Bower и Composer

Для того, чтобы получить NPM нужно установить NodeJS.

У NodeJS есть официальный установщик для Windows, поэтому установка будет проще простого:

  1. скачиваем установщик с официального сайта NodeJS;
  2. запускаем скаченный установщик и нажимаем несколько раз кнопку Next, попутно соглашаясь с условиями.

Для того, чтобы проверить, установился ли NodeJS и NPM, откройте консоль Windows или Git bush (если консоль уже была открыта, то нужно её закрыть и открыть снова, чтобы обновить системный PATH) и выполните команды:


node -v

и


npm -v

Если команды выдали версии, например: «v6.2.0» и «3.8.8», то это значит, что всё успешно установлено и можно работать.

После установки NPM можно приступить к установке Bower

Здесь всё просто, введите в командной строке:


npm install bower -g

Параметр -g нужен для того, чтобы установить Bower глобально и иметь возможность запускать его из любого каталога.

Composer

У пакетного менеджера Composer есть специальный установщик для Windows. Скачать его можно с официального сайта. Сама установка элементарна и займёт не больше 5 минут, но есть две особенности.

Во первых, перед установкой Composer нужно установить PHP. О том как это сделать написано в начале поста. Во вторых, после установки Composer нужно передать ему специальный GitHub Tokken для того, чтобы обойти ограничени GitHub’а на количество обращений по API.

Но начнём с установки. После скачивания и запуска установщика он попросит указать путь к PHP. Если вы добавили PHP в PATH, как указано у меня в инструкци, то Composer сам определит этоть путь. Если нет, то вам нужно указать этот путь самостоятельно.

Установка Composer

После этого нужно ещё несколько раз нажать Next и Composer будет установлен в систему и доступен через командную строку из любого каталога.

В процессе работы с Composer программа в какой-то момент сама предложит вам ввести GitHub Tokken и даст ссылку на его создание. Но можно не ждать этого и сделать всё самому. Создать токен можно на специальной странице GitHub’а. Для того, что передать токен Composer’у нужно ввести в командной строке команду


composer config -g github-oauth.github.com <token>

Всё, на этом Composer установлен и готов к использованию.

Система сборки проекта Gulp

Так как он часть экосистемы NPM, то тут всё просто:


npm install gulp -g

Параметр -g нужен для того, чтобы установить Gulp глобально и иметь возможность запускать его из любого каталога.

Виртуальная среда Vagrant

Для установки Vagrant в Windows предварительно понадобится установить один из провайдеров виртуальной среды. Я использую VirtualBox от Oracle. Установка обеих программ не составляет абсолютно никакого труда и требует только вовремя нажимать кнопку Next.

Ссылки на страницы откуда можно скачать установщики:

  • VirtualBox;
  • Vagrant.

После установки, Vagrant можно будет запускать из командной строки из любого каталога.

Система развёртывания Capistrano

Для того, чтобы установить Capistrano на Windows в первую очередь нужно установить язык программирования Ruby. В этом нет ничего сложного, для установки языка в Windows существует специальный проект rubyinstaller.org. Нужно лишь скачать установщик и несколько раз нажать кнопку Next. Не забудьте только поставить галочку напротив пункта о добавлении Ruby в PATH Windows.

установка ruby на windows

Это позволит запускать Capistrano из любого каталога, что очень удобно.

После установки Ruby настало время установить Capistrano. Откройте командную строку (если она была открыта, до установки Ruby, то закройте и откройте её снова, чтобы обновить данные из PATH) и введите команду:


gem install capistrano

Эта команда установит Capistrano в систему и в дальнейшем его можно будет запускать командой:


cap

Как видите, всё элементарно.

Все необходимые компоненты установлены. Осталось только выбрать хороший редактор кода. Я использую PHPStorm, так как он поддерживает все инструменты, которые перечислены в этом посте и ежемесячная индивидуальная подписка на эту программу стоит меньше $10. Но, конечно, можно установить любой редактор на свой вкус.

Сразу после установки PHPStorm на Windows нужно сделать две важные настройки:

  1. указать UTF-8 в качестве кодировки всех файлов по умолчанию;
  2. указать символ n в качестве символа окончания строки по умолчанию.

Это необходимо сделать, так как всё тестирование и работа сайтов идёт в среде Linux и неверные символы окончания строк и кодировка файлов может приветси к разным ошибкам, у которых трудно будет выявить причину.

Обе настройки находятся в разделе Editor. Попасть в настройки можно с главного экрана PHPStorm.

главный экран PHPStorm

Либо с верхнего меню через File -> Default settings.

Default settings в PHPStorm

Окончание строк в файлах настраиваем в разделе Editor -> Code Style.

настройка окончаний строк в PHPStorm

Кодировку файлов настраиваем в разделе Editor -> File Encodings.

настройка кодировки файлов по умолчанию в PHPStorm

На этом всё. На установку всех компонентов понадобится примерно час времени.

Today I will explain how to add your PHP runtime directory to your Windows 10 PATH environment variable.
This will give you global access to php.exe from any command prompt.

Please note that you must reopen your command prompt windows (if you had any open prior to the update).

Command prompt loads the PATH environment variable when it is first open.

Target audience

  • Windows 10 users
  • PHP developers that want PHP to be globally accessible from any command prompt (ex.: php.exe for “linting” or to start a dev. server)

Note that you are not limited to PHP, this can be any directory containing any program — ex.: npm

Copy shortcut: ctrl+C
Paste shortcut: ctrl+V

  1. Find your PHP installation directory and copy it somewhere (your clipboard is a good place)
    • For MAMP users it will be something like C:MAMPbinphpphp5.6.21 (the PHP version may vary).
  2. Right-click on the “Start menu”
  3. Click “System” win-path-01
  4. Click “Advanced system settings” win-path-02
  5. Click “Environment Variables…” win-path-03
  6. Select the “Path” variable (in your user or in the system list)
  7. Click “Edit…” win-path-04
  8. Click “New”
  9. Paste your PHP path win-path-05
  10. Click OK
  11. Click OK
  12. Click OK
  13. Close your “system window”

And voilà!

How to test if it worked out

  1. Open a command prompt
    1. Right-click on the start menu
    2. Click “Command Prompt” or “Command Prompt (admin)”
  2. In the command prompt, type php -?

If it displays PHP help then it worked!





Comments

I am trying to add C:xamppphp to my system PATH environment variable in Windows.

I have already added it using the Environment Variables dialog box.

But when I type into my console:

C:>path

it doesn’t show the new C:xamppphp directory:

PATH=D:Program FilesAutodeskMaya2008bin;C:Ruby192bin;C:WINDOWSsystem32;C:WINDOWS;
C:WINDOWSSystem32Wbem;C:PROGRA~1DISKEE~2DISKEE~1;c:Program FilesMicrosoft SQL
Server90Toolsbinn;C:Program FilesQuickTimeQTSystem;D:Program FilesTortoiseSVNbin
;D:Program FilesBazaar;C:Program FilesAndroidandroid-sdktools;D:Program Files
Microsoft Visual StudioCommonToolsWinNT;D:Program FilesMicrosoft Visual StudioCommon
MSDev98Bin;D:Program FilesMicrosoft Visual StudioCommonTools;D:Program Files
Microsoft Visual StudioVC98bin

I have two questions:

  1. Why did this happen? Is there something I did wrong?
  2. Also, how do I add directories to my PATH variable using the console (and programmatically, with a batch file)?

Peter Mortensen's user avatar

asked Mar 3, 2012 at 12:58

Netorica's user avatar

8

Option 1

After you change PATH with the GUI, close and reopen the console window.

This works because only programs started after the change will see the new PATH.

Option 2

This option only affects your current shell session, not the whole system. Execute this command in the command window you have open:

set PATH=%PATH%;C:yourpathhere

This command appends C:yourpathhere to the current PATH. If your path includes spaces, you do not need to include quote marks.

Breaking it down:

  • set – A command that changes cmd’s environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:yourpathhere – The %PATH% part expands to the current value of PATH, and ;C:yourpathhere is then concatenated to it. This becomes the new PATH.

Peter Mortensen's user avatar

answered Mar 3, 2012 at 13:03

JimR's user avatar

JimRJimR

15.1k2 gold badges20 silver badges26 bronze badges

12

WARNING: This solution may be destructive to your PATH, and the stability of your system. As a side effect, it will merge your user and system PATH, and truncate PATH to 1024 characters. The effect of this command is irreversible. Make a backup of PATH first. See the comments for more information.

Don’t blindly copy-and-paste this. Use with caution.

You can permanently add a path to PATH with the setx command:

setx /M path "%path%;C:yourpathhere"

Remove the /M flag if you want to set the user PATH instead of the system PATH.

Notes:

  • The setx command is only available in Windows 7 and later.
  • You should run this command from an elevated command prompt.

  • If you only want to change it for the current session, use set.

StayOnTarget's user avatar

StayOnTarget

11k10 gold badges49 silver badges75 bronze badges

answered Feb 28, 2015 at 5:12

Nafscript's user avatar

NafscriptNafscript

4,9572 gold badges16 silver badges15 bronze badges

15

This only modifies the registry. An existing process won’t use these values. A new process will do so if it is started after this change and doesn’t inherit the old environment from its parent.

You didn’t specify how you started the console session. The best way to ensure this is to exit the command shell and run it again. It should then inherit the updated PATH environment variable.

Peter Mortensen's user avatar

answered Mar 3, 2012 at 13:23

Hans Passant's user avatar

Hans PassantHans Passant

913k145 gold badges1670 silver badges2507 bronze badges

6

You don’t need any set or setx command. Simply open the terminal and type:

PATH

This shows the current value of PATH variable. Now you want to add directory to it? Simply type:

PATH %PATH%;C:xamppphp

If for any reason you want to clear the PATH variable (no paths at all or delete all paths in it), type:

PATH ;

Update

Like Danial Wilson noted in comment below, it sets the path only in the current session. To set the path permanently, use setx but be aware, although that sets the path permanently, but not in the current session, so you have to start a new command line to see the changes. More information is here.

To check if an environmental variable exist or see its value, use the ECHO command:

echo %YOUR_ENV_VARIABLE%

Peter Mortensen's user avatar

answered Jul 1, 2015 at 15:11

zar's user avatar

zarzar

10.9k13 gold badges90 silver badges171 bronze badges

6

I would use PowerShell instead!

To add a directory to PATH using PowerShell, do the following:

$PATH = [Environment]::GetEnvironmentVariable("PATH")
$xampp_path = "C:xamppphp"
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path")

To set the variable for all users, machine-wide, the last line should be like:

[Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path", "Machine")

In a PowerShell script, you might want to check for the presence of your C:xamppphp before adding to PATH (in case it has been previously added). You can wrap it in an if conditional.

So putting it all together:

$PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
$xampp_path = "C:xamppphp"
if( $PATH -notlike "*"+$xampp_path+"*" ){
    [Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path", "Machine")
}

Better still, one could create a generic function. Just supply the directory you wish to add:

function AddTo-Path{
param(
    [string]$Dir
)

    if( !(Test-Path $Dir) ){
        Write-warning "Supplied directory was not found!"
        return
    }
    $PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
    if( $PATH -notlike "*"+$Dir+"*" ){
        [Environment]::SetEnvironmentVariable("PATH", "$PATH;$Dir", "Machine")
    }
}

You could make things better by doing some polishing. For example, using Test-Path to confirm that your directory actually exists.

Mariano Desanze's user avatar

answered Mar 17, 2015 at 20:24

Ifedi Okonkwo's user avatar

Ifedi OkonkwoIfedi Okonkwo

3,3064 gold badges31 silver badges45 bronze badges

4

Safer SETX

Nod to all the comments on the @Nafscript’s initial SETX answer.

  • SETX by default will update your user path.
  • SETX ... /M will update your system path.
  • %PATH% contains the system path with the user path appended

Warnings

  1. Backup your PATHSETX will truncate your junk longer than 1024 characters
  2. Don’t call SETX %PATH%;xxx — adds the system path into the user path
  3. Don’t call SETX %PATH%;xxx /M — adds the user path into the system path
  4. Excessive batch file use can cause blindness1

The ss64 SETX page has some very good examples. Importantly it points to where the registry keys are for SETX vs SETX /M

User Variables:

HKCUEnvironment

System Variables:

HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment

Usage instructions

Append to User PATH

append_user_path.cmd

@ECHO OFF
REM usage: append_user_path "path"
SET Key="HKCUEnvironment"
FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
ECHO %CurrPath% > user_path_bak.txt
SETX PATH "%CurrPath%";%1

Append to System PATH

append_system_path.cmd. Must be run as administrator.

(It’s basically the same except with a different Key and the SETX /M modifier.)

@ECHO OFF
REM usage: append_system_path "path"
SET Key="HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment"
FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
ECHO %CurrPath% > system_path_bak.txt
SETX PATH "%CurrPath%";%1 /M

Alternatives

Finally there’s potentially an improved version called SETENV recommended by the ss64 SETX page that splits out setting the user or system environment variables.


Example

Here’s a full example that works on Windows 7 to set the PATH environment variable system wide. The example detects if the software has already been added to the PATH before attempting to change the value. There are a number of minor technical differences from the examples given above:

@echo off
set OWNPATH=%~dp0
set PLATFORM=mswin

if defined ProgramFiles(x86)                        set PLATFORM=win64
if "%PROCESSOR_ARCHITECTURE%"=="AMD64"              set PLATFORM=win64
if exist "%OWNPATH%textexmf-mswinbincontext.exe" set PLATFORM=mswin
if exist "%OWNPATH%textexmf-win64bincontext.exe" set PLATFORM=win64

rem Check if the PATH was updated previously
echo %PATH% | findstr "texmf-%PLATFORM%" > nul

rem Only update the PATH if not previously updated
if ERRORLEVEL 1 (
  set Key="HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment"
  for /F "USEBACKQ tokens=2*" %%A in (`reg query %%Key%% /v PATH`) do (
    if not "%%~B" == "" (
      rem Preserve the existing PATH
      echo %%B > currpath.txt

      rem Update the current session
      set PATH=%PATH%;%OWNPATH%textexmf-%PLATFORM%bin
      
      rem Persist the PATH environment variable
      setx PATH "%%B;%OWNPATH%textexmf-%PLATFORM%bin" /M
    )
  )
)

1. Not strictly true

Dave Jarvis's user avatar

Dave Jarvis

29.9k39 gold badges177 silver badges310 bronze badges

answered Dec 29, 2016 at 12:04

icc97's user avatar

icc97icc97

10.7k8 gold badges69 silver badges88 bronze badges

0

Handy if you are already in the directory you want to add to PATH:

set PATH=%PATH%;%CD%

It works with the standard Windows cmd, but not in PowerShell.

For PowerShell, the %CD% equivalent is [System.Environment]::CurrentDirectory.

Peter Mortensen's user avatar

answered Mar 18, 2016 at 16:09

nclord's user avatar

nclordnclord

1,2271 gold badge16 silver badges17 bronze badges

2

Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.

Try it! It’s safe to use and is awesome!

Peter Mortensen's user avatar

answered Feb 17, 2016 at 4:10

Netorica's user avatar

NetoricaNetorica

18.1k17 gold badges72 silver badges108 bronze badges

1

  • Command line changes will not be permanent and will be lost when the console closes.
  • The path works like first comes first served.
  • You may want to override other already included executables. For instance, if you already have another version on your path and you want to add different version without making a permanent change on path, you should put the directory at the beginning of the command.

To override already included executables;

set PATH=C:xamppphp;%PATH%;

Peter Mortensen's user avatar

answered Sep 6, 2016 at 14:37

hevi's user avatar

hevihevi

2,3501 gold badge32 silver badges51 bronze badges

Use pathed from gtools.

It does things in an intuitive way. For example:

pathed /REMOVE "c:myfolder"
pathed /APPEND "c:myfolder"

It shows results without the need to spawn a new cmd!

Peter Mortensen's user avatar

answered Mar 19, 2019 at 9:37

womd's user avatar

womdwomd

2,97325 silver badges19 bronze badges

1

Regarding point 2, I’m using a simple batch file that is populating PATH or other environment variables for me. Therefore, there isn’t any pollution of environment variables by default. This batch file is accessible from everywhere so I can type:

mybatchfile

Output:

-- Here all environment variables are available

And:

php file.php

Peter Mortensen's user avatar

answered Oct 30, 2015 at 14:22

Grzegorz Gajos's user avatar

3

Checking the above suggestions on Windows 10 LTSB, and with a glimpse on the «help» outlines (that can be viewed when typing ‘command /?’ on the cmd), brought me to the conclusion that the PATH command changes the system environment variable Path values only for the current session, but after reboot all the values reset to their default- just as they were prior to using the PATH command.

On the other hand using the SETX command with administrative privileges is way more powerful. It changes those values for good (or at least until the next time this command is used or until next time those values are manually GUI manipulated… ).

The best SETX syntax usage that worked for me:

SETX PATH "%PATH%;C:pathtowherethecommandresides"

where any equal sign ‘=’ should be avoided, and don’t you worry about spaces! There isn’t any need to insert any more quotation marks for a path that contains spaces inside it — the split sign ‘;’ does the job.

The PATH keyword that follows the SETX defines which set of values should be changed among the System Environment Variables possible values, and the %PATH% (the word PATH surrounded by the percent sign) inside the quotation marks, tells the OS to leave the existing PATH values as they are and add the following path (the one that follows the split sign ‘;’) to the existing values.

Peter Mortensen's user avatar

answered Nov 22, 2016 at 20:34

such_ke_nasdeeq's user avatar

1

Use these commands in the Bash shell on Windows to append a new location to the PATH variable

PATH=$PATH:/path/to/mydir

Or prepend this location

PATH=/path/to/mydir:$PATH

In your case, for instance, do

PATH=$PATH:C:xamppphp

You can echo $PATH to see the PATH variable in the shell.

Peter Mortensen's user avatar

answered Sep 1, 2021 at 6:48

kiriloff's user avatar

kiriloffkiriloff

25.2k36 gold badges143 silver badges222 bronze badges

1

If you run the command cmd, it will update all system variables for that command window.

answered Oct 17, 2018 at 2:06

Pranav Sharma's user avatar

1

In a command prompt you tell Cmd to use Windows Explorer’s command line by prefacing it with start.

So start Yourbatchname.

Note you have to register as if its name is batchfile.exe.

Programs and documents can be added to the registry so typing their name without their path in the Start — Run dialog box or shortcut enables Windows to find them.

This is a generic reg file. Copy the lines below to a new Text Document and save it as anyname.reg. Edit it with your programs or documents.

In paths, use \ to separate folder names in key paths as regedit uses a single to separate its key names. All reg files start with REGEDIT4. A semicolon turns a line into a comment. The @ symbol means to assign the value to the key rather than a named value.

The file doesn’t have to exist. This can be used to set Word.exe to open Winword.exe.

Typing start batchfile will start iexplore.exe.

REGEDIT4
;The bolded name below is the name of the document or program, <filename>.<file extension>

[HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionApp PathsBatchfile.exe]

; The @ means the path to the file is assigned to the default value for the key.
; The whole path in enclosed in a quotation mark ".

@=""C:\Program Files\Internet Explorer\iexplore.exe""

; Optional Parameters. The semicolon means don't process the line. Remove it if you want to put it in the registry

; Informs the shell that the program accepts URLs.

;"useURL"="1"

; Sets the path that a program will use as its' default directory. This is commented out.

;"Path"="C:\Program Files\Microsoft Office\Office\"

You’ve already been told about path in another answer. Also see doskey /? for cmd macros (they only work when typing).

You can run startup commands for CMD. From Windows Resource Kit Technical Reference

AutoRun

HKCUSoftwareMicrosoftCommand Processor

Data type Range Default value
REG_SZ  list of commands  There is no default value for this entry.

Description

Contains commands which are executed each time you start Cmd.exe.

Peter Mortensen's user avatar

answered Dec 21, 2016 at 1:08

A better alternative to Control Panel is to use this freeware program from SourceForge called Pathenator.

However, it only works for a system that has .NET 4.0 or greater such as Windows 7, Windows 8, or Windows 10.

Peter Mortensen's user avatar

answered Aug 28, 2017 at 1:24

Bimo's user avatar

BimoBimo

5,5972 gold badges35 silver badges57 bronze badges

0

As trivial as it may be, I had to restart Windows when faced with this problem.

I am running Windows 7 x64. I did a manual update to the system PATH variable. This worked okay if I ran cmd.exe from the stat menu. But if I type «cmd» in the Windows Explorer address bar, it seems to load the PATH from elsewhere, which doesn’t have my manual changes.

(To avoid doubt — yes, I did close and rerun cmd a couple of times before I restarted and it didn’t help.)

Peter Mortensen's user avatar

answered Oct 20, 2019 at 18:03

svinec's user avatar

svinecsvinec

6298 silver badges9 bronze badges

3

The below solution worked perfectly.

Try the below command in your Windows terminal.

setx PATH "C:myfolder;%PATH%"

SUCCESS: Specified value was saved.

You can refer to more on here.

Peter Mortensen's user avatar

answered Jun 5, 2021 at 13:42

Surendra Babu Parchuru's user avatar

  1. I have installed PHP that time. I extracted php-7***.zip into C:php</i>

  2. Back up my current PATH environment variable: run cmd, and execute command: path >C:path-backup.txt

  3. Get my current path value into C:path.txt file (the same way)

  4. Modify path.txt (sure, my path length is more than 1024 characters, and Windows is running few years)

  • I have removed duplicates paths in there, like ‘C:Windows; or C:WindowsSystem32; or C:WindowsSystem32Wbem; — I’ve got twice.
  • Remove uninstalled programs paths as well. Example: C:Program FilesNonExistSoftware;
  • This way, my path string length < 1024 :)))
  • at the end of the path string, add ;C:php
  • Copy path value only into buffer with framed double quotes! Example: «C:Windows;****;C:php» No PATH= should be there!!!
  1. Open Windows PowerShell as Administrator (e.g., Win + X).

  2. Run command:

    setx path "Here you should insert string from buffer (new path value)"

  3. Rerun your terminal (I use «Far Manager») and check:

    php -v

Peter Mortensen's user avatar

answered Oct 24, 2018 at 20:50

Serb's user avatar

SerbSerb

214 bronze badges

How to open the Environment Variables window from cmd.exe/Run… dialog

  • SystemPropertiesAdvanced and click «Environment Variables», no UAC
  • rundll32 sysdm.cpl,EditEnvironmentVariables direct, might trigger UAC

Via Can the environment variables tool in Windows be launched directly? on Server Fault.

How to open the Environment Variables window from Explorer

  1. right-click on «This PC»
  2. Click on «Properties»
  3. On the left panel of the window that pops up, click on «Advanced System Settings»
  4. Click on the «Advanced» tab
  5. Click on «Environment Variables» button at the bottom of the window

You can also search for Variables in the Start menu search.

Reference images how the Environment Variables window looks like:

Windows 10

Environment Variables window on Windows 10
via

Windows 7

Environment Variables window on Windows 7
via

Windows XP

Environment Variables window on Windows
via

On Windows 10, I was able to search for set path environment variable and got these instructions:

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation panel.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below:

C:Program Files;C:Winnt;C:WinntSystem32

The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.

answered Nov 12, 2020 at 1:38

Janin's user avatar

JaninJanin

2721 gold badge2 silver badges7 bronze badges

Установка PHP 8 на Windows 10


Найти дистрибутив PHP можно по адресу https://windows.php.net/download#php-8.1 Выберите версию Thread Safe.

В папке c:WebServerWAMP создайте новую папку PHP и скопируйте туда содержимое архива php-8.1.5 — VS16 x64 Thread Safe (2022-Apr-12 18:12:52) .

Смотрите Дерево каталогов .

Настройка конфигурационного файла php.ini


С помощью Notepad++ открываем php.ini-development в папке c:WebServerWAMPPHP и сохраняем его как  php.ini  , и вносим в него следующие изменения .

Для этого находим строку – 768 :

И заменяем ее на :

extension_dir = "C:WebServerWAMPPHPext"

Теперь найдите строки: Начинается со строки 920 .

;extension=bz2
;extension=curl
;extension=fileinfo
;extension=gd2
;extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
;extension=ldap
;extension=mbstring
;extension=exif      ; Must be after mbstring as it depends on it
;extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
;extension=openssl
;extension=pdo_firebird
;extension=pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
;extension=pdo_pgsql
;extension=pdo_sqlite
;extension=pgsql
;extension=shmop

И заменим их на :

extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
extension=gmp
extension=intl
extension=imap
;extension=interbase
extension=ldap
extension=mbstring
extension=exif      ; Must be after mbstring as it depends on it
extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
extension=openssl
;extension=pdo_firebird
extension=pdo_mysql
;extension=pdo_oci
extension=pdo_odbc
extension=pdo_pgsql
extension=pdo_sqlite
extension=pgsql
extension=shmop

Заменим строки: – начинаются со строки 950.

;extension=soap
;extension=sockets
;extension=sqlite3
;extension=tidy
;extension=xmlrpc
;extension=xsl

На:

extension=soap
extension=sockets
extension=sqlite3
extension=tidy
extension=xmlrpc
extension=xsl

Указываем кодировку по умолчанию . Для этого находим строку – 720 :

;default_charset = "UTF-8"

И меняем ее на :

default_charset = "UTF-8"

Находим строку – 746:

;include_path = ".;c:phpincludes"

И меняем ее на :

include_path = ".;C:WebServerhomeincludes"

Предварительно создадим папку includes в C:WebServerhome
Здесь будут хранится подключаемые файлы PHP .

Заменим строку – 970:

На:

date.timezone = "Europe/Moscow"

Сохраняем и закрываем файл php.ini .
Теперь необходимо вписать поддержку PHP в файл конфигурации сервера Apache . Открываем файл httpd.conf и в конец файла добавим строки :

PHPIniDir "C:/WebServer/WAMP/PHP"
AddHandler application/x-httpd-php .php
LoadModule php_module "C:/WebServer/WAMP/PHP/php8apache2_4.dll"

Сохраняем и закрываем файл httpd.conf .

Настройка переменной среды


Далее необходимо добавить каталог с установленным интерпретатором PHP в переменную PATH операционной системы Windows 10 . Для этого нажмите кнопку Пуск на Windows 10, начните набирать «Изменение системных переменных среды» и откройте соответствующее окно настроек.

Окно path

Изменение системных переменных среды

В открывшемся окне выбираем в самом низу пункт переменные среды .

В следующем открывшемся окне :

path1.png

Выберем пункт path и нажимаем изменить .

В следующем открывшемся окне :

path2

Выбираем пункт создать и в открывшейся строке напишите C:WebServerWAMPPHP и выбираем пункт вверх и подымаем нашу строку к вверху , и нажимаем кнопку Ok , как на рисунке ниже .

path3

Во всех открытых окнах нажимаем Ok , все окна переменной среды path закрываем . После данных изменений следует перезагрузить компьютер .

После перезагрузки компьютера , открываем Notepad++ и набираем следующий код :

<?php
phpinfo();
?>

Сохраняем файл в каталоге c:WEbServerhomewww с названием i.php

В адресной строке Web – браузера набираем : http://localhost/i.php , если вы увидите данные о интерпретаторе PHP , как на рисунке , то значит все настройки сделали правильно и PHP работает .

Версия PHP

Версия PHP

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

И помните после каждого изменения конфигурационных файлов и исправлении ошибок , нужно чистить историю Web – браузера , может так получится вы нашли исправили ошибку , перезагрузили сервер , а Web – браузер выдает вам файлы из истории , и вы видите при загрузке опять ошибку .

This article explains how to install PHP 8.2 and Apache 2.4 on Windows 10 or 11 (64-bit).

Linux and macOS users often have Apache and PHP pre-installed or available via package managers. Windows requires a little more effort. The steps below may work with other editions of Windows, PHP, and Apache, but check the documentation of each dependency for specific instructions.

Contents:

  1. Why PHP?
  2. Why Install PHP Locally?
  3. Alternative Installation Options
    • Using an all-in-one package
    • Using a Linux virtual machine
    • Using Windows Subsystem for Linux 2
    • Using Docker
  4. Installing Apache (optional)
  5. Installing PHP
    • Step 1: Download the PHP files
    • Step 2: Extract the files
    • Step 3: Configure php.ini
    • Step 4: Add C:php to the PATH environment variable
    • Step 5: Configure PHP as an Apache module
    • Step 6: Test a PHP file

Why PHP?

PHP remains the most widespread and popular server-side programming language on the Web. It’s installed by most web hosts, and has a simple learning curve, close ties with the MySQL database, superb documentation, and a wide collection of libraries to cut your development time. PHP may not be perfect, but you should consider it for your next web application. It’s the language of choice for Facebook, Slack, Wikipedia, MailChimp, Etsy, and WordPress (the content management system which powers almost 45% of the web).

To get your PHP setup blazing fast, check out our free book on improving PHP Performance.

Why Install PHP Locally?

Installing PHP on your development PC allows you to create and test websites and applications without affecting the data or systems on your live server.

Alternative Installation Options

Before you jump in, there may be a simpler installation options…

Using an all-in-one package

All-in-one packages are available for Windows. They contain Apache, PHP, MySQL, and other useful dependencies in a single installation file. These packages include XAMPP, WampServer and Web.Developer.

These packages are easy to use, but they may not match your live server environment. Installing Apache and PHP manually will help you learn more about the system and configuration options.

Using a Linux virtual machine

Microsoft Hyper-V (provided in Windows Professional) and VirtualBox are free hypervisors which emulate a PC so you can install another operating system.

You can install any version of Linux, then follow its Apache and PHP installation instructions. Alternatively, distros such as Ubuntu Server provide them as standard (although they may not be the latest editions).

Using Windows Subsystem for Linux 2

WSL2 is also a virtual machine, but it’s tightly integrated into Windows so activities such as file sharing and localhost resolution are seamless. You can install a variety of Linux distros, so refer to the appropriate Apache and PHP instructions.

Using Docker

Docker creates a wrapper (known as a container) around pre-configured application dependencies such as Apache, PHP, MySQL, MongoDB, and most other web software. Containers look like full Linux Virtual Machines but are considerably more lightweight.

Once you’ve installed Docker Desktop on Windows, it’s easy to download, configure, and run Apache and PHP.

Docker is currently considered the best option for setting up a PHP development environment. Check out SitePoint’s article Setting Up a Modern PHP Development Environment with Docker for a complete guide to setting it up.

Installing Apache (optional)

The following sections describe how to install Apache and PHP directly on Windows.

PHP provides a built-in web server, which you can launch by navigating to a folder and running the PHP executable with an -S parameter to set the localhost port. For example:

cd myproject
php -S localhost:8000

You can then view PHP pages in a browser at http://localhost:8000.

This may be adequate for quick tests, but your live server will use Apache or similar web server software. Emulating that environment as closely as possible permits more advanced customization and should prevent development errors.

To install Apache, download the latest Win64 ZIP file from https://www.apachelounge.com/download/ and extract its Apache24 folder to the root of your C: drive. You’ll also need to install the Visual C++ Redistributable for Visual Studio 2015–2020 (vc_redist_x64); the page has a link at the top.

Open a cmd command prompt (not PowerShell) and start Apache with:

cd C:Apache24bin
httpd

You may need to accept a firewall exception before the server starts to run. Open http://localhost in a browser and an “It works!” message should appear. Note:

  • C:Apache24confhttpd.conf is Apache’s configuration file if you need to change server settings.
  • C:Apache24htdocs is the web server’s root content folder. It contains a single index.html file with the “It works!” message.

If Apache fails to start, another application could be hogging port 80. (Skype is the prime candidate, and the Windows app won’t let you disable it!) If this occurs, edit C:Apache24confhttpd.conf and change the line Listen 80 to Listen 8080 or any other free port. Restart Apache and, from that point onward, you can load web files at http://localhost:8080.

Stop the server by pressing Ctrl + C in the cmd terminal. The ReadMe file in the ZIP also provides instructions for installing Apache as a Windows service so it auto-starts on boot.

Installing PHP

Install PHP by following the steps below. Note that there’s more than one way to configure Apache and PHP, but this is possibly the quickest method.

Step 1: Download the PHP files

Get the latest PHP x64 Thread Safe ZIP package from https://windows.php.net/download/.

Create a new php folder in the root of your C: drive and extract the content of the ZIP into it.

You can install PHP anywhere on your system, but you’ll need to change the paths referenced below if you use anything other than C:php.

Step 3: Configure php.ini

PHP’s configuration file is php.ini. This doesn’t exist initially, so copy C:phpphp.ini-development to C:phpphp.ini. This default configuration provides a development setup which reports all PHP errors and warnings.

You can edit php.ini in a text editor, and you may need to change lines such as those suggested below (use search to find the setting). In most cases, you’ll need to remove a leading semicolon (;) to uncomment a value.

First, enable any required extensions according to the libraries you want to use. The following extensions should be suitable for most applications including WordPress:

extension=curl
extension=gd
extension=mbstring
extension=pdo_mysql

If you want to send emails using PHP’s mail() function, enter the details of an SMTP server in the [mail function] section (your ISP’s settings should be suitable):

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = mail.myisp.com
; http://php.net/smtp-port
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = my@emailaddress.com

Step 4: Add C:php to the PATH environment variable

To ensure Windows can find the PHP executable, you must add it to the PATH environment variable. Click the Windows Start button and type “environment”, then click Edit the system environment variables. Select the Advanced tab, and click the Environment Variables button.

Scroll down the System variables list and click Path, followed by the Edit button. Click New and add C:php.

PHP path environment variable

Note that older editions of Windows provide a single text box with paths separated by semi-colons (;).

Now OK your way out. You shouldn’t need to reboot, but you may need to close and restart any cmd terminals you have open.

Step 5: Configure PHP as an Apache module

Ensure Apache is not running and open its C:Apache24confhttpd.conf configuration file in a text editor. Add the following lines to the bottom of the file to set PHP as an Apache module (change the file locations if necessary but use forward slashes rather than Windows backslashes):

# PHP8 module
PHPIniDir "C:/php"
LoadModule php_module "C:/php/php8apache2_4.dll"
AddType application/x-httpd-php .php

Optionally, change the DirectoryIndex setting to use index.php as the default in preference to index.html. The initial setting is:

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

Change it to:

<IfModule dir_module>
    DirectoryIndex index.php index.html
</IfModule>

Save httpd.conf and test the updates from a cmd command line:

cd C:Apache24bin
httpd -t

Syntax OK will appear … unless you have errors in your configuration.

If all went well, start Apache with httpd.

Step 6: Test a PHP file

Create a new file named index.php in Apache’s web page root folder at C:Apache24htdocs. Add the following PHP code:

<?php
phpinfo();
?>

Open a web browser and enter your server address: http://localhost/. A PHP version page should appear, showing all PHP and Apache configuration settings.

You can now create PHP sites and applications in any subfolder of C:Apache24htdocs. If you need to work more than one project, consider defining Apache Virtual Hosts so you can run separate codebases on different localhost subdomains or ports.

Further information:

  • How to Install Apache
  • How to Install MySQL
  • MySQL: the Pros and Cons of MyISAM Tables
  • MySQL: the Pros and Cons of InnoDB Tables
  • How to Use MySQL Foreign Keys for Quicker Database Development
  • Book: PHP & MySQL: Novice to Ninja, 7th Edition
  • Book: Jump Start PHP Environment, as well as many more books in our library.

Best of luck!

Вернуться к: ЧАВО

Этот раздел содержит общие вопросы по установке PHP.
PHP доступен практически для любой ОС (за исключением, может быть,
MacOS предшествующей OSX) и любого web сервера.

Для установки PHP следуйте инструкциям в Установка и настройка.

  1. Почему я не должен использовать Apache2 с потоковым MPM в промышленном окружении?

  2. Unix/Windows: Где должен находиться файл php.ini?

  3. Unix: Я установил PHP, но каждый раз при загрузке документа я получаю
    сообщение ‘Document Contains No Data’ (Документ Не Содержит Данных)!
    Что происходит?

  4. Unix: Я установил PHP с помощью RPMS, но Apache не обрабатывает PHP страницы!
    Что происходит?

  5. Unix: Я установил заплатку в Apache для расширений FrontPage и
    неожиданно PHP перестал работать.
    Неужели PHP не совместим с FrontPage расширениями для Apache?

  6. Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего
    браузера, я получаю пустой экран.

  7. Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего
    браузера, я получаю ошибку сервера 500.

  8. Некоторые операционные системы: Я установил PHP без ошибок,
    но когда я пытаюсь запустить Apache, я получаю ошибки «undefined symbol»
    (неопределенный символ):

    [mybox:user /src/php5] root# apachectl configtest
    apachectl: /usr/local/apache/bin/httpd Undefined symbols:
    _compress
    _uncompress

  9. Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего
    браузера, я получаю ошибку:

    cgi error:
    The specified CGI application misbehaved by not
    returning a complete set of HTTP headers.
    The headers it did return are:

  10. Windows: Я следовал всем инструкциям, но так и не смог заставить PHP и IIS
    работать вместе!

  11. Когда PHP запускается как CGI в IIS, PWS, OmniHTTPD или Xitami,
    я получаю следующую ошибку: Security Alert! PHP CGI
    cannot be accessed directly..

  12. Как узнать, что мой php.ini был найден и прочтен?
    Похоже, что мои изменения не были восприняты?

  13. Как на Windows добавить мою PHP директорию в PATH?

  14. Как в Windows сделать файл php.ini доступным для PHP?

  15. Возможно ли использовать согласование содержания в Apache
    (опция MultiViews) c PHP?

  16. PHP может обрабатывать только GET и POST запросы?

Почему я не должен использовать Apache2 с потоковым MPM в промышленном окружении?

PHP — это клей. Клей, используемый для построения классных веб-приложений,
склеивая дюжины сторонних библиотек и создавая впечатление одного согласованного
целого, с помощью интуитивного и легко изучаемого языка.
Гибкость и мощь PHP полагается на стабильность и устойчивость используемой
платформы. Для склейки вместе ему необходимы работающая ОС, работающий
веб-сервер и работающие сторонние библиотеки. Когда что-либо из этого перестает
работать, PHP нужны способы определения проблем и их быстрого исправления.
Если вы усложняете низлежащую систему, не разделяя полностью потоки выполнения,
не выделяя раздельные сегменты памяти и не предоставляя «песочницу» для
игры для каждого запроса, то в вашей PHP системе появятся слабые места.

Если вы хотите использовать потоковый MPM,
взгляните на конфигурацию с FastCGI, где вы можете запускать PHP
в своем собственном пространстве памяти.

Unix/Windows: Где должен находиться файл php.ini?

На Unix по умолчанию он должен находиться в директории
/usr/local/lib, определяемой как
<install-path>/lib.
Большинство людей изменяют его во время компиляции с помощью опции
—with-config-file-path
Для примера, вы можете задать что-то типа:

--with-config-file-path=/etc

Затем скопировать файл php.ini-development из
дистрибутива в /etc/php.ini и отредактировать
его для ваших локальных нужд.

--with-config-file-scan-dir=PATH

На Windows по умолчанию php.ini находится в Windows директории.
Если вы используете веб-сервер Apache, php.ini сначала ищется в
директории, где был установлен Apache, например, c:program
filesapache groupapache
. В этом случае на одной машине
у вас могут быть разные файлы php.ini для разных версий Apache.

Смотрите также главу о конфигурационном файле.

Unix: Я установил PHP, но каждый раз при загрузке документа я получаю
сообщение ‘Document Contains No Data’ (Документ Не Содержит Данных)!
Что происходит?

Вероятно, PHP падает по какой-то причине. Для того, чтобы убедиться в этом,
просмотрите лог ошибок вашего сервера и затем попытайтесь воспроизвести
проблему с помощью небольшого тестового примера. Если вы умеете пользоваться
‘gdb’, то добавьте трассировку к вашему сообщению об ошибке, это поможет
разработчикам точно определить проблему.
Если вы используете PHP как модуль Apache, попробуйте что-то типа:

  • Остановите ваши httpd процессы

  • gdb httpd

  • Остановите ваши httpd процессы

  • > run -X -f /path/to/httpd.conf

  • Затем вызовите URL, на котором возникает проблема, из вашего браузера

  • > run -X -f /path/to/httpd.conf

  • Если вы получаете дамп, gdb должен сейчас же сообщить вам об этом

  • введите: bt

  • Вам необходимо включить трассировку в ваше сообщение об ошибке, которое
    должно быть отправлено с
    » http://bugs.php.net/

Если ваш скрипт использует функции регулярных выражений
(preg_match() и другие), то вам необходимо убедиться,
что вы скомпилировали PHP и Apache с одним и тем же пакетом регулярных
выражений. Это должно происходить автоматически для PHP и Apache 1.3.x

Unix: Я установил PHP с помощью RPMS, но Apache не обрабатывает PHP страницы!
Что происходит?

Предполагается, что Apache и PHP оба были установлены из пакетов RPM.
Вам требуется в вашем файле httpd.conf раскомментировать или добавить
все или некоторые из следующих строк:

# Extra Modules
AddModule mod_php.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so

И добавить:

AddType application/x-httpd-php .php

… в глобальные свойства или в свойства VirtualDomain, для которого
вы хотите иметь поддержку PHP.

Unix: Я установил заплатку в Apache для расширений FrontPage и
неожиданно PHP перестал работать.
Неужели PHP не совместим с FrontPage расширениями для Apache?

Нет, PHP прекрасно работает с FrontPage расширениями.
Проблема в том, что FrontPage заплатка изменяет некоторые важные для
PHP структуры. Перекомпиляция PHP (с помощью ‘make clean ; make’)
после установки FP заплатки должна решить эту проблему.

Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего
браузера, я получаю пустой экран.

Сделайте просмотр исходника (‘view source’) в web браузере
и, вероятно, вы увидите исходный код вашего PHP скрипта.
Это означает, что web сервер не передал скрипт PHP для интерпретации.
Что-то не так с конфигурацией сервера, проверьте конфигурацию сервера
согласно установочным инструкциям PHP.

Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего
браузера, я получаю ошибку сервера 500.

Что-то произошло, когда сервер пытался выполнить PHP.
Чтобы увидеть более вразумительное сообщение об ошибке,
используя командную строку, перейдите в директорию где находится
исполняемый файл PHP (php.exe на Windows)
и запустите php -i. Если при запуске PHP
возникли какие-либо проблемы, то появится соответствующее сообщение
об ошибке, которое может дать вам понять что делать дальше.
Если вы получаете экран, заполненный HTML кодом (вывод функции
phpinfo()), то PHP работает и ваша
проблема возможно связана с конфигурацией вашего сервера, которую
вам необходимо проверить.

Некоторые операционные системы: Я установил PHP без ошибок,
но когда я пытаюсь запустить Apache, я получаю ошибки «undefined symbol»
(неопределенный символ):

[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

На самом деле это связано с клиентскими библиотеками MySQL и не имеет
никакого отношения к PHP. Одним нужна опция
—with-zlib
, другим — нет. Это также
описано в MySQL FAQ.

Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего
браузера, я получаю ошибку:

cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

Это сообщение об ошибке означает, что PHP не смог вывести
абсолютно ничего. Чтобы увидеть более вразумительное сообщение об ошибке,
используя командную строку, перейдите в директорию, где находится
исполняемый файл PHP (php.exe на Windows) и
запустите php -i. Если при запуске PHP
возникли какие-либо проблемы, то появится соответствующее сообщение
об ошибке, которое может дать вам понять, что делать дальше.
Если вы получаете экран, заполненый HTML кодом (вывод функции
phpinfo() функции), то PHP работает.

Как только PHP заработает из командной строки, попытайтесь опять вызвать
скрипт из браузера. Если он все также не работает, то причина может быть
одной из следующих:


  • Анонимный пользователь Internet ISUR_<machinename>
    не имеет доступ к вашему PHP скрипту,
    php.exe, php4ts.dll,
    php.ini или любому загружаемому PHP расширению из за прав доступа,
    установленных на эти файлы.

  • Файл скрипта не существует (или, вероятно, не там где вы думаете он
    должен быть, относительно вашей корневой web директории).
    Заметьте, что для IIS вы можете поймать эту ошибку пометив ‘check file
    exists’ при настройке ассоциирования скриптов (script mappings) в
    Администраторе Internet Сервисов (Internet Services Manager).
    Если файл скрипта не существует, то сервер выдаст ошибку 404.
    Также есть дополнительное преимущество, заключающееся в том, что IIS будет выполнять
    необходимую вам аутентификацию, основываясь на NTLanMan правах
    доступа на ваш скрипт.

Windows: Я следовал всем инструкциям, но так и не смог заставить PHP и IIS
работать вместе!

Убедитесь что все пользователи, кому необходимо запускать PHP скрипты,
имеют право выполнять php.exe!
IIS использует анонимного пользователя, который добавлен во время
установки IIS. Этот пользователь должен иметь права на
php.exe. Также любому аутентифицированному пользователю
будут нужны права на выполнение php.exe.
И для IIS4 вам необходимо сказать ему, что PHP является скриптовой системой.
Также вам захочется прочитать
это.

Когда PHP запускается как CGI в IIS, PWS, OmniHTTPD или Xitami,
я получаю следующую ошибку: Security Alert! PHP CGI
cannot be accessed directly.
.

Вы должны установить директиву
cgi.force_redirect в 0.
По умолчанию она установлена в 1, поэтому убедитесь, что
директива не закоммментирована (с ;). Как все директивы,
она задается в php.ini

Так как значение по умолчанию 1, то очень важно
быть уверенным на 100%, что был прочитан верный php.ini файл.
Для подробностей читайте
здесь.

Как узнать, что мой php.ini был найден и прочтен?
Похоже, что мои изменения не были восприняты?

Чтобы убедиться, что PHP прочитал ваш php.ini, вызовите
phpinfo() и недалеко от начала будет находиться
строка, озаглавленная Configuration File (php.ini).
Она скажет вам, где PHP ищет php.ini и был ли файл прочитан.
Если указана только PATH директория, то файл не был прочитан и вы должны поместить
ваш php.ini в эту директорию. Если php.ini включен в PATH, то он
был прочитан.

Если php.ini был прочитан и вы запускаете PHP как модуль, то
не забудьте перезапустить ваш web сервер после внесения изменений в
php.ini.

Смотрите также php_ini_loaded_file().

Как на Windows добавить мою PHP директорию в PATH?

На Windows NT+ и Windows Server 2000+:

  • Зайдите в Control Panel и откройте системную иконку (Start -> Settings
    -> Control Panel -> System, или просто Start -> Control Panel
    -> System for Windows XP/2003)

  • Перейдите в закладку Advanced

  • Нажмите кнопку ‘Environment Variables’

  • Смотрите в окошко ‘System Variables’

  • Найдите Path (возможно, вам придется сделать прокрутку, чтобы найти его)

  • Двойной щелчок на Path

  • Добавьте в конец вашу PHP директорию, поставив спереди ‘;’ (например
    ;C:php)

  • Нажмите OK

На Windows 98/Me вам необходимо отредактировать файл
autoexec.bat:

  • Откройте Notepad (Start -> Run и введите notepad)

  • Откройте файл C:autoexec.bat

  • Найдите строку с PATH=C:WINDOWS;C:WINDOWSCOMMAND;….. и добавьте
    в конец строки:
    ;C:php

  • Сохраните файл и перезапустите ваш компьютер

Замечание:

Обязательно перезагрузитесь после указанных шагов для
уверенности, что внесенные вами изменения были применены к
PATH.

Прежде в руководстве по PHP рекомендовалось копировать файлы в системную
директорию Windows, так как эта директория
(C:Windows, C:WINNT и т.п.)
входит в системный PATH по умолчанию. Копирование файлов в системную директорию
Windows давно уже противопоказано и может вызвать проблемы.

Как в Windows сделать файл php.ini доступным для PHP?

Для этого есть несколько путей. Если вы используете Apache, то читайте
инструкции по его установке (Apache 1,
Apache 2),
в ином случае, вы должны установить переменную окружения
PHPRC:

На Windows NT, 2000, XP и 2003:

  • Зайдите в Control Panel и откройте системную иконку (Start -> Settings
    -> Control Panel -> System, или просто Start -> Control Panel
    -> System for Windows XP/2003)

  • Перейдите в закладку Advanced

  • Нажмите кнопку ‘Environment Variables’

  • Посмотрите в окошко ‘System variables’

  • Щелкните на ‘New’ и введите ‘PHPRC’ как имя переменной и директорию,
    где находится php.ini, как значение переменной (например,
    C:php)

  • Нажмите OK и перезапустите ваш компьютер

На Windows 98/Me вам необходимо отредактировать файл
autoexec.bat:

  • Откройте Notepad (Start -> Run и введите notepad)

  • Откройте файл C:autoexec.bat

  • Добавьте новую строку в конец файла: set
    PHPRC=C:php
    (замените C:php на директорию,
    где находится php.ini). Учтите, что путь не должен содержать
    пробелы. Например, если вы установили PHP в
    C:Program FilesPHP, вы можете
    вместо этого ввести C:PROGRA~1PHP.

  • Сохраните файл и перезапустите ваш компьютер

Возможно ли использовать согласование содержания в Apache
(опция MultiViews) c PHP?

Все работает замечательно, если ссылки на PHP файлы имеют расширение.
Этот FAQ рассматривает только случай, когда ссылки на PHP файлы не имеют расширения
и вы хотите использовать согласование содержания для отбора PHP файлов из
URL без расширений.
В этом случае, замените строку AddType application/x-httpd-php
.php
на:

AddHandler php5-script php
AddType text/html php

Это решение не работает в Apache 1, так как в нем PHP модуль не ловит
php-script.

PHP может обрабатывать только GET и POST запросы?

Нет, можно обрабатывать любые запросы, например, CONNECT.
Необходимый статус ответа можно послать с помощью функции
header().
Если нужно обрабатывать только GET и POST запросы, то этого
можно достигнуть с помощью такой конфигурации Apache:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

Вернуться к: ЧАВО

Понравилась статья? Поделить с друзьями:
  • Как добавить paint в меню пуск windows 10
  • Как добавить outlook в автозагрузку windows 10
  • Как добавить onedrive в проводник windows 10
  • Как добавить office в образ windows
  • Как добавить astra linux в домен windows