How to run php file on windows xp. Executing PHP Files

I’ll immediately make a reservation that everything that will be discussed in this article is applicable only for Unix-like operating systems and will not work under Windows. This is exactly what we're talking about alternative to krona. Unlucky Windows lovers will have to conjure with "Task Scheduler" - Black magic will remain inaccessible to them :) In addition, you will need ssh access, and ideally - access for php scripts to the command line.

What is a daemon program and how to write a daemon in PHP

Daemon(daemon, dæmon, ancient Greek δαίμων deity) - computer program in UNIX-class systems, launched by the system itself and running in background without direct user interaction. Daemons usually start during system boot.

Applicable to PHP, it is a script that can run on its own, without stopping and without user interaction. How to get such a script? In fact, it’s very simple, you just need to break one of the first rules of programming that they teach in school, and create an infinite loop:

// For the program to work constantly, it simply must work constantly;) while(1) ( // The Daemon code will be located here // ... // The Daemon sleep time between iterations (depends on the needs of the system) sleep(1); )

The impossibly simple code still raises several questions. How to launch it? How to track its implementation? How to stop him?

How to start a php daemon

How do you run PHP scripts in general? If this is a web application, then using a browser and a web server. But this option is not suitable, because we are dealing with an endless script, and the execution time of scripts is limited by the directive max_execution_time V php.ini. Therefore, an endless script must be run via the console, because then maximum time its completion is not taken into account. The command to start the daemon looks something like this:

Php -f /path/to/your/daemon.php &

For manual start it must be entered in the ssh terminal (putty, WinSCP, etc.), and for it to be launched by the system at boot - into the corresponding startup file (the position and name of the file depends on operating system). Please note that console daemon script runs in background, without involving the user in waiting for its completion (after all, the script is endless). It is the ability to run a process in the background that is the reason that the method I am describing is not suitable for Windows servers. After launch, the console should display process id our daemon, the so-called PID.

Tracking and stopping demons

You can check whether the daemon process is running by simply opening the list of processes in the system:

PS-aux

Finding a daemon in the list of processes is easy, both by the launch command and by PID:

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND ... root 22193 0.1 0.2 393180 72132 ? S Apr24 5:05 php -f /path/to/your/daemon.php &

Stop the daemon process you can do it the same way as any other process:

Kill xxxx

In the example given, xxxx is the PID, the process identifier.

It is worth noting that this is not stopping, but rather “killing” the daemon process. The fact is that the script will be interrupted anywhere, which is not always suitable for everyone. In theory, in this case the daemon should be stopped somewhere between its iterations and no longer from the console. For example, we can create a request to stop the script in the database or in some file on the server, and between iterations of the daemon check whether such a request exists. If the application is found, stop the loop with the break statement.

Demon control system

What if you need to create and track many daemons at once? For example, in the CheckTrust service mentioned above, > 30 such scripts are involved in processing user data and projects. Creating and monitoring them from the console is very inconvenient - a more user-friendly interface is needed.

Cool, yeah? :) Just to create such a system, it would be nice to have access to the command line from php. Each daemon is an entry in the database, against which you can enter a command to launch it, as well as the PID of the process. Consequently, it becomes possible to start, stop and monitor the status of daemons directly from the web interface. As a result, the daemons themselves turned out to be part of a console application, and the system for managing them became part of a web application.

Since the system shown above is designed strictly for CheckTrust, I will not show its code. But I'll copy the code here php class for process management, which I used when creating it:

<?php /* * Process.php * An easy way to keep in track of external processes. * Ever wanted to execute a process in php, but wanted to have somewhat controll of the process? Well.. This is a way of doing it.

* @compability: Linux only. (Windows does not work). * @author: Peec */ class Process( private $pid; private $command; public function __construct($cl=false)( if ($cl != false)( $this->command = $cl; $this-> runCom(); ) ) private function runCom())( $command = "nohup ".$this->command." > /dev/null 2>&1 & echo $!"; exec($command ,$op); $ this->pid = (int)$op; ) public function setPid($pid)( $this->pid = $pid; ) public function getPid())( return $this->pid; ) public function status())( $command = "ps -p ".$this->pid; if (!isset($op))return false; else return true; this->command != "")$this->runCom(); else return true; ( $command = "kill ".$this->pid; exec($command); if ($ this->status() == false)return true; else return false;

The only drawback of this class is that I already described yours - it stops processes using the kill method, but that’s enough for me for now :) And here it is an example of its use:// Start the daemon and

getting PID (assuming the pid is saved somewhere after startup) $command = ""; $process = new Process($command); $processId = $process->getPid(); // Checking the daemon status $process = new Process(); $process->setPid($processId); $status = $process->status(); // returns true or false // Stopping the daemon $process = new Process(); $process->setPid($processId); $stopped = $process->stop(); // returns true or false To summarize, I want to say that this is not the only possible and, quite possibly, not the most optimal implementation of daemons in PHP. For example, there is a cool PHP extension PCNTL for multi-process daemons. Some might even say that for console applications

  • There are completely different programming languages. But, whatever one may say, this implementation has undeniable advantages:
  • She's simple like a slipper. A demon is just an endless loop, much simpler.
  • It is compatible with web applications- being part of a web service, my daemons rely on existing developments, use the same data models, classes and methods of working with them.

She works!

Seriously - we have had some daemons running for several months now and, being well written, do not become stupid, do not freeze, and do not consume memory. different ways run PHP code:

    Pointing specific file for start.

    $ php my_script.php $ php -f my_script.php

    Both methods (indicating the option -f or without) will run the my_script.php file. You can choose any file to run, and your PHP scripts do not have to have the extension .php and can have any name and extension you want.

    Comment:

    If you need to pass arguments to your scripts, then when using the option -f the first argument should be -- .

  1. Pass PHP code directly on the command line.

    $ php -r "print_r(get_defined_constants());"

    You need to be especially careful when using this method because shell variable substitution may occur when double quotes are used.

    Comment:

    Please read the example carefully, there are no opening or closing tags in it! Option-r

  2. it just doesn't need them. Using them will result in a parser error. Pass running PHP code via standard input ().

    stdin

    This provides the powerful ability to dynamically generate PHP code and feed it to the startup file, as shown in this (fake) example:

$some_application | some_filter | php | sort -u > final_output.txt

You cannot combine any of these three ways to run code. Like any other console application, the binary PHP file Option takes arguments, but your PHP script can also receive arguments. PHP does not limit the number of arguments passed to your script (the console shell sets some threshold for the number of characters that can be passed; this limit is usually sufficient). The passed arguments are available in the global array $argv . The first index (zero) always contains the name of the script being called from the command line. Please note that if the code is called on the fly from the command line using the option - , the value of $argv will simply be a hyphen ( ). The same is true for code piped from.

STDIN The second global variable registered is $argc, which contains the number of elements in the $argv array ((and Not

number of arguments passed to the script). - If the arguments you pass do not begin with the character , That special problems - there shouldn't be. -- By passing an argument to the script that begins with

will create problems because PHP will decide that it should handle it itself. To prevent this behavior, use an argument list delimiter this code, but will show information about PHP usage $ php -r "var_dump($argv);" -h Usage: php [-f] [...] # This command will pass the "-h" argument to your script, preventing PHP help from being shown $ php -r "var_dump($argv);" -- -h array(2) ( => string(1) "-" => string(2) "-h" )

However, on Unix systems there is another way to use PHP for console scripts. You can write a script whose first line starts with #!/usr/bin/php(if necessary, substitute the correct path to your binary file PHP CLI). After this line, you can place regular PHP code, enclosed in opening and closing PHP tags . Once you set the correct launch attributes on the file (for example, chmod +x test

), your script can be run as a regular console or perl script:

Example #1 Running a PHP script as a console script
#!/usr/bin/php
?>

var_dump ($argv);

Assuming that this file is called test and is in the current directory, we can do the following:

$ chmod +x test $ ./test -h -- foo array(4) ( => string(6) "./test" => string(2) "-h" => string(2) "--" => string(3) "foo" ) - .

As you can see, in this case you don't need to worry about passing parameters that start with The PHP executable can be used to run PHP scripts independently of the web server. In case you work in Unix-like system .php, you need to add a special first line to all scripts and make them executable to indicate which program should process these scripts. On Windows platforms, you can assign a php.exe handler for files with the extensions or create a batch (.bat) file to run scripts using PHP.:

The line added at the beginning of the script for Unix systems does not affect their operation on Windows OS, so you can create cross-platform scripts. Below is a simple example script executed from

Example #1 Running a PHP script as a console script

command line
?>

Example #2 Script designed to be run from the command line (script.php)

If ($argc != 2 || in_array ($argv [ 1 ], array("--help" , "-help" , "-h" , "-?" ))) (

type. Options --help, -help, -h,
or -? will show current help information.
}
?>

In the example above, we use a special first line to indicate that this script needs to be run using PHP. Since we are working with the CLI version, HTTP headers will not be displayed. When writing console applications in PHP, you have two variables available to you: $argc and $argv .

The first is the number of arguments passed plus one (the name of the script being executed). The second is an array of passed arguments, starting with the script name with index zero ($argv). , Also in the above example we check the number of arguments passed. , In case there is more or less one of them, and also in case the passed argument was--help -? -help

-h or, we display a help message by substituting the name of the script being executed dynamically. Otherwise, we simply print the received argument. If you want to run the above example on a Unix system, you will need to make it executable and simply run it from the console script.php echothis or:

script.php -h

. On a Windows system you can create for this

batch file Example #3 Batch file to run a PHP script from the command line (script.bat)@echo OFF "C:\php\php.exe" script.php %* Assuming the script is called script.php and the full path to the php.exe CLI is C:\php\php.exe , the given batch file will run the script with the parameters you passed:.

script.bat echothis

or script.bat -h You may also want to check out the Readline extension, which can be used to enhance your PHP console script.

Hello everyone. Today I’m starting to write in a new section -

PHP ! Basically, here will be the basics and basics of this language. And first, I’ll tell you how to open a php file in a browser? Why doesn't php open like html?

  1. Here's the thing: php is
  2. server language . Html and javascript are client-side. Accordingly, to execute PHP code you need to start the server, only in this case the file can be opened. Actually, there are only 2 ways: Create a website on real hosting where you will experiment with PHP Create local server

, where you can create for free unlimited amount sites on your computer and experiment as much as you like.

  1. And I strongly advise you exactly the second option. Accordingly, before you start opening php files, you need to install such a server. Just don’t think that it’s hard - you can do it in just a couple of minutes. Of the most famous local servers for
  2. Denwer
  3. Xammp

Personally, I only worked with Denver. I could write about its installation separately, but I decided that nothing was better official documentation it cannot be from the developers. In this regard, here it is. You can find a lot of articles and videos on the Internet about installing other servers.

How to open a php file after installing the server?

Is the server installed? Great, now you have everything to run php files. Actually, to do this, your local server must be running. This is the shortcut you should have on your desktop:

Now you need to create a new site for your local server. Again, I'm only showing how to do this in Denver. Let's go to root folder server, here we find the folder home. It will contain all your sites. Need to create new folder, its name will be the name of the new site. In the created folder, you must create a folder www, without this nothing will work. Final stage— throw the necessary php files (which need to be opened) into the www folder. It is the root of the site.

The way to open php files is different from how to open html. You cannot open them in the browser directly, in which case you will only see the code. To open a file, you need to register the site on which it is located, as well as the path to the file on the site. I want to emphasize that if you simply enter the name of the site (without http://, but with a slash), the server will launch index.php, if there is one.

Example:
I created a phptest folder on the local server, with www in it, and then uploaded it to it necessary files. Great, now you need to restart Denver if you had it running. If not, just run it. Now in the browser line you need to type: phptest/

So you get to home page site. This file should be called index.php. For example, I created a calculator in php, put it in phptest called calc.php. I write the address before this file:

Great, the calculator has opened. You can test the application.

How not to open php?

It doesn't have to be done like html files. That is, not through "To open with""Browser". So you will only see source file, but in no case the result of its execution.

That's it, we figured out how to open a php file in a browser. It is enough to install and configure a local server once, and in the future you will be able to open files of this resolution without any problems. That's all I have for today. I hope everything worked out for you. See you.

Starting with version 4.3, PHP supports a new SAPI (Server Application Programming Interface) type called CLI, which means Command Line Interface. As the name suggests, the main purpose of this SAPI type is to develop shell (or desktop) applications using PHP. There are very minor differences between the CLI SAPI and other SAPIs, which will be discussed further in this chapter.

The SAPI CLI was first released with PHP 4.2.0, but it was an experiment back then and had to be explicitly enabled with --enable-cli on startup./configure. As of PHP 4.3.0, the SAPI CLI is no longer experimental and Always built in and installed as a php binary executable (called php.exe on Windows).

Significant differences between CLI SAPI and other SAPIs:

    Unlike CGI SAPI, no headers are written to the output.

    Although the CGI SAPI has a way to suppress HTTP headers, there is no equivalent switch to enable them in the CLI SAPI.

    There are certain php.ini directives that are overridden in the CLI SAPI because they do not make sense in a shell environment:

Table 24-1. Overriding php.ini directives
DirectiveCLI SAPI - default valueA comment
html_errors FALSE It can be quite difficult to read an error message in the shell filled with all those meaningless HTML tags, so the default value of this directive is FALSE .
implicit_flush TRUE It is desirable that any conclusion from print() , echo() and company was immediately written to the output, rather than sent to some buffer. You can still use output buffering if you want to work with standard output.
max_execution_time0 (unlimited) Because of the infinite possibilities using PHP in a shell environment, there is no maximum execution time. While applications written for the web execute within fractions of a second, shell applications try to take as long as possible to complete.
register_argc_argv TRUE Global PHP variables$argc (number of arguments, transmitted to the application) and $argv (the array of current arguments) are always registered and filled with the appropriate values ​​when using the SAPI CLI.

Note: These directives cannot be initialized with a different value from the php.ini configuration file or special file(if specified). This is somewhat of a limitation because these default values ​​are applied after all configuration files have been parsed. However, their value can be changed at runtime (which does not make sense for all other directives, for example, for register_argc_argv).

    It is easier to work in a shell environment when the following constants are defined:

    Table 24-2. Specific CLI constants
    ConstantDescription
    ). The same is true for code piped from Already opened stream in stdin. It protects the one who opens it

    You don't need to explicitly close these streams; PHP does this automatically.

  • CLI SAPI The second global variable registered is $argc, which contains the number of elements in the $argv array ((and changes the current directory to the directory of the executable script!

    Example showing the difference between CGI SAPI:

    When to use CGI version, the output will be:

    This gives greater flexibility when writing command line utilities in PHP.

    Note: CGI SAPI supports CLI SAPI behavior using the -C switch when run from the command line.

  • List of command line options executable file PHP can be obtained at any time by running PHP with the -h switch:

    The SAPI CLI has three different ways getting PHP-code to be executed:

    1. Tell PHP to execute a specific file.

      Particular care must be taken when replacing shell variables and using quotes.

      Note: Look at the example carefully, there are no start and end tags! The -r switch simply doesn't need them. Using them in in this case will result in a parser error.

    2. Provide PHP code to be executed via standard input (stdin).

      This allows you to dynamically create PHP code and pass it to the executable, as shown in this (contrived) example:

      $some_application | some_filter | php | sort -u >final_output.txt

    You cannot combine these three methods when executing code.

    As with any shell application, not only PHP itself, but also your PHP scripts also accept arguments. The number of arguments passed to the script in PHP is not limited (the shell has a limit on the number of characters passed).
    The arguments passed to your script are available through the global $argv array. The zero index always contains the name of the script (which is a character - in the case where the PHP code comes from standard input or using the -r command line switch).
    The second global variable registered is $argc, which contains the number of elements in the $argv array (and The second global variable registered is $argc, which contains the number of elements in the $argv array ((and number of arguments passed to the script).

    If the arguments you want to pass to the script do not begin with a hyphen (-) character, there is nothing special to observe. Passing an argument starting with - to the script will create problems because PHP thinks it has to handle them itself. To prevent this, use -- as the list argument separator. Once the argument is parsed by PHP, each subsequent argument is passed to your script unchanged/unparsed.

    However, here is another way to use PHP for shell scripting. You can write a script whose first line starts with #!/usr/bin/php , followed by normal PHP code contained between the PHP start and end tags, and the file's execution attributes set accordingly. This way it can be executed as a normal shell or perl script:

    As you can see, you don't have to do anything special when passing parameters to a script that starts with - .

    Table 24-3. Command Line Options
    OptionDescription
    -s

    Display syntax in color.

    This option uses the file's internal parsing mechanism and produces its colorized HTML version and writes it to standard output. Please note that only a block [...] of HTML tags is generated without an HTML header.

    Note:

    -w

    Display original text no comments or spaces.

    Note: This option does not work in conjunction with the -r option.

    -f

    Parses and executes this file. This switch is optional and can be omitted. It is enough to provide a file name for execution.

    -v

    Writes PHP, PHP SAPI and Zend versions to standard output, for example:

    -a

    Runs PHP interactively.

    -d

    This option allows you to set special meaning for each configuration directive that is allowed in php.ini . The syntax is:

    -e

    Generates extended information for debugger/profiler.

    -z

    Loads the Zend extension. If only the filename is given, PHP tries to load this extension from the current default path to the library on your system (usually specified as /etc/ld.so.conf on Linux systems). Passing filename with an absolute path will not use the library's system search path. A relative filename with directory information will tell PHP to try to load the extension relative to the current directory.

    -l

    This option provides convenient way perform a syntax check on this PHP code. If successful, the text No syntax errors detected in is written to standard output, and the shell return code will be 0 . If it fails, the text Errors parsing along with the parser's internal error message is written to standard output, and the shell's return code will be 255 .

    This option will not find fatal errors(like undefined functions). Use -f if you want to check for fatal errors as well.

    Note: This option does not work in conjunction with -r .

    -m

    Using this option, PHP prints out built-in (and loaded) PHP and Zend modules:

    $ php -m xml tokenizer standard session posix pcre overload mysql mbstring ctype
    -iThis command line option causes phpinfo() and prints the results. If PHP is not working correctly, we recommend running php -i and seeing if error messages are printed before or instead of the info tables. Keep in mind that the output will be in HTML and therefore quite jumbled.
    Option

    This option allows you to run PHP directly on the command line. PHP start and end tags () Not needed and cause parser errors.

    Note: Care must be taken when using this form of PHP to ensure there are no conflicts with command line variable substitutions performed by the shell.

    An example that produces a parser error:

    It would be correct to use single quotes" . String variables enclosed in single quotes are not expanded when sh/bash runs.

    The PHP executable can be used to run PHP scripts completely independent of the web server.
    If you are running Unix, you should add a special first line to your PHP scripts and make them executable so that the system knows which program should execute those scripts.
    Under Windows you can associate php.exe with the option double click using .php files or create a batch file (.bat) to run the script via PHP. A line added to the top of a script to run on Unix will work fine on Windows, so you can write cross-platform programs this way. Below is an example of a simple PHP program to be executed from the command line.

    Here we use a special first line to indicate that this file should be run in PHP. Here we are working with the CLI version, so HTTP headers are not output. There are two variables you can use when writing command line PHP applications: $argc and $argv. The first is the number of arguments plus 1 (name running script). The second is an array of arguments, starting with the script name with index zero ($argv).

    We check if there is less or more than one argument. Also, if the argument was --help , -help , -h or -? , we print a help message, displaying the script name dynamically. If we received any other argument, we echo it.

    If you want to run the above script on Unix, you need to make it executable and simply call it as script.php echothis or script.php -h . On Windows you can create a batch file to perform this task:

    Assuming that you named the program script.php and that your php.exe is located in c:\php\php.exe , this batch file will run it with the options you added: script.bat echothis or script.bat -h .

    See also the Readline extension documentation for features you can use to enhance your command-line PHP application.

This article provides step by step guide on installing PHP for collaboration with Apache HTTP server on Windows. This procedure has been tested on both Windows XP and Vista. It is assumed that you have already completed the Apache installation.

PHP 5 Setup Steps

1. Download PHP 5

Before you get started, download a copy of PHP 5 from download pages. Download the secure VC6 package from the "Windows Binaries" section - that is, do not download the installer. For example, select the package marked " PHP 5.2.5 zip package", if on this moment Current version — 5.2.5 .

Note: Please note that I have not tested the below procedure with PHP 5.3 versions, only with 5.2.5 which was latest version at the time of writing. Theoretically, the same steps should be performed for PHP installations 7 .

2. Install PHP 5

Create a folder on your hard drive for PHP. I suggest c:php , although you could use a different folder name and location. Personally, I prefer not to use names with spaces.

Extract all files from the downloaded archive into this folder. To do this, simply double-click on the zip file. And then drag all the files into the c:php folder.

3. For those upgrading the package: Remove the old PHP.INI file from the Windows directory

If you are upgrading to PHP 5 from over old version, go to the Windows directory, ( usually this is c:windows), and delete any php.ini files you previously placed there.

4. PHP setup

Go to the c:php folder and create a copy of the php.ini-recommended file. Name new file php.ini . You should now have a c:phpphp.in file with content identical to the c:phpphp.ini-recommended file.

Note: If you are using Apache 1 you need to either move the php.ini file to the Windows directory ( c:windows), or configure environment variable PATH to include c:php . If you don't know how to do this, just move the php.ini file to the c:windows folder. You don't need to do this if you are using Apache 2, as we will later specify a directive in the Apache 2 configuration file with the location of the php.ini file.

To install PHP on Windows 7 using text editor (for example, such as Notepad, which can be found in the System section of the Start menu)? open the php.ini file. You may need to make the following changes to the file:

a) Including short opening tags

Find the following line:

short_open_tag = Off

If short_open_tag is set to off , tags like "

Since many third party PHP scripts use the "

short_open_tag = On

b) Magic quotes

When Apache PHP is installed by default, incoming data is not automatically slash escaped. If you want the input to be prefixed with a backslash (""), for example to reproduce hosting settings, find the following line:

magic_quotes_gpc = Off

and replace it with:

magic_quotes_gpc = On

It is not recommended to do this if this parameter is not set on the hosting. Even when set to Off, you can still use PHP function addslashes() to add slashes for specific pieces of data.

c) Using global variables

A number of older scripts, when executed, assume that all data submitted through a form will automatically have a PHP variable with the same name. For example, if a form has an input field named "something", older PHP scripts assume that the PHP processor will automatically create a variable called $something that contains the value specified through that field.

If you use such scripts, you need to find the following line:

register_globals = Off

and change it to:

register_globals = On

Warning: When installing PHP on Windows, do not do this unless you have third party scripts that require this to work. When writing new scripts, it is best to always assume that the register_globals element is set to " Off«.

d) Error display

On a live site, errors in the script are usually logged without appearing in the PHP error file. But on a local machine, while you are testing and debugging a PHP script, it is more convenient to send error messages when they are detected directly to the browser window. This way you won't miss errors even if you forget to check the error log file.

To have PHP display error messages directly in the browser window, look for the following line:

display_errors = Off

and change it to:

display_errors = On

This setting should always be set to Off on a running site.

e) Session path

If the script uses sessions, find the following line:

;session.save_path = "/tmp"

session.save_path specifies the folder where PHP saves session files. Since the /tmp folder does not exist in Windows, you need to install another folder. One way is to create a folder called c:tmp ( as previously we created c:php) and specify this folder for this parameter. If you do this, change this line as follows:

session.save_path = "c:tmp"

Note that in addition to changing the path, I also removed the semicolon prefix (";") from the string.

You can also use the current TEMP folder on your computer. Or create a tmp folder in your PHP directory, such as c:phptmp and configure the config file accordingly. There can be many possible options. If you can't decide which one to choose, just create c:php and do as I said above.

f) SMTP Server

If you have installed PHP 55, if your script uses the mail() function and you want the function to successfully send mail on your local machine, look for the following section:

; For Win32 only. SMTP = localhost smtp_port = 25 ; For Win32 only. ;sendmail_from= [email protected]

Change it to include your SMTP server address and email account. For example, if your SMTP server mail.example.com, and the email address [email protected], change the code like this:

SMTP = mail.example.com smtp_port = 25 sendmail_from = [email protected]

Please note that after this, when the script tries to use the mail() function, it will need to connect to your ISP for it to work successfully. If you do not change the above lines and try to use the mail() function in a script, the function will return a failure code and display an error message.

How to configure Apache for PHP 5

There are two ways to install Apache PHP. First: set it to download PHP interpreter as an Apache module. Second: configure it to run the interpreter as a CGI binary. Only one of them needs to be used. Select the module method if PHP is also installed on the hosting, like the Apache module, or use the CGI method if it is implemented on the hosting.

a) Running PHP 5 as an Apache module

To configure Apache to load PHP as a module for parsing PHP scripts, use an ASCII text editor to open the Apache configuration file, httpd.conf.

If you are using Apache 1.x, the file is located in the folder c:Program FilesApache GroupApacheconf. Apache 2.0.x users can find it in the folder C:Program FilesApache GroupApache2conf, and Apache 2.2.x users are in the folder C:Program FilesApache Software FoundationApache2.2conf. Typically, it is located in the conf folder of the directory where Apache is installed.

Locate the section of the file with LoadModule statements. Declarations preceded by the hash symbol "#" are considered commented out.

If you are using Apache 1.x, add the following line after all LoadModule statements:

LoadModule php5_module "c:/php/php5apache.dll"

If you are using Apache 2.0.x, add the following line after all LoadModule statements:

LoadModule php5_module "c:/php/php5apache2.dll"

If you are using Apache 2.2.x, add the following line:

LoadModule php5_module "c:/php/php5apache2_2.dll"

Note that this example PHP installation uses the forward slash character (“/”) instead of the traditional Windows backslash (“”). This is not a typo.

If you are using Apache 1.x, find the "AddModule" series of statements and add the following after all the lines.

AddModule mod_php5.c

Then find the AddType block in the file and add the following line after the last AddType statement. This needs to be done no matter what version of Apache you are using. For Apache 2.2.x you need to find the AddType lines in the section . Add a line just before closingfor this section.

If you need support for other file types, such as ".phtml", add them to the list, for example like this:

For those using one of the Apache 2 versions, you need to specify the location of the PHP ini file. Add the following line to the end of httpd.conf.

PHPIniDir "c:/php"

If you used a different directory, you will need to change c:/php to the correct path. Don't forget to use a forward slash ("/").

If you are using Apache 1, you have already placed the php.ini file in your Windows folder or somewhere in your PATH. So PHP will have to find it on its own.

Running PHP 5 as a CGI binary

If you have configured PHP 5 to load as an Apache module, you can skip this section. It is intended for those who want to configure PHP to run as a CGI binary.

The procedure for doing this when installing PHP 7 is the same for both Apache 1.x and all versions of the 2.x series.

Locate the part of the Apache configuration file that contains the ScriptAlias ​​section. Add the line below immediately after the ScriptAlias ​​line for " cgi-bin" If you are using Apache 2.2.x, make sure the line is before closingfor section .

note: If you installed PHP in another location, for example c:Program Filesphp , you need to specify the appropriate path instead c:/php/ (for example, c:Program Filesphp). Don't forget that here we are using the forward slash ("/") instead of the Windows backslash ("").

ScriptAlias ​​/php/ "c:/php/"

Apache needs to configure the PHP MIME type. Find the AddType comment block explaining its use and add the following line below it. For Apache 2.2.x, find the AddType lines under . Add the below line just before closing for this section.

AddType application/x-httpd-php .php

As with installing PHP as an Apache module, you can add any extensions to make Apache recognize them as PHP scripts, for example:

AddType application/x-httpd-php .phtml

Then you need to tell the server to execute the PHP executable every time it encounters a PHP script. Add the following code to the file, for example after a block of comments explaining " Action«.

If you are using Apache 2.2.x, then add the code immediately after the AddType statement described above; Apache 2.2.x does not have a comment block " Action«.

Action application/x-httpd-php "/php/php-cgi.exe"

Note: The "/php/" part will be recognized as a ScriptAlias, a kind of macro that will be expanded by Apache to "c:/php/" ( or "c:/Program Files/php/" if you installed PHP there). In other words, do not put the path "c:/php/php.exe" or "c:/Program Files/php/php.exe", but use “/php/php-cgi.exe” .

If you are using Apache 2.2.x, find the following section in the httpd.conf file:

Add the lines below right after the section you just found.

AllowOverride None Options None Order allow,deny Allow from all

c) Setting the default index page

This section applies to the option of installing PHP on Windows as both an Apache module and a CGI binary.

If you create an index.php file and want Apache to load it as the site's home page, you will have to add another line to the httpd.conf file. Find the line that starts with " DirectoryIndex", and add " index.php" to the list of files. For example, if you had code like this:

DirectoryIndex index.html

change it to:

DirectoryIndex index.php index.html

The next time you log into the web server through a directory name such as " localhost" or " localhost/directory/", Apache will send all scripts from index.php or the contents of the index.html file if index.php is not available.

Restart the Apache web server

Restart the Apache server. This is necessary for Apache to read the new PHP configuration directives that you have placed in the httpd.conf file. The Apache 2.2 server can be restarted by double-clicking on the Apache Service Monitor icon in the taskbar and clicking the “ Restart” button in the window that appears.

Testing the PHP Installation

After installing PHP 5 5 or another version of the language, create a php file with the following line:

Save a file named test.php to the Apache htdocs directory. If you use Notepad, be sure to save the name " test.php" with quotation marks. Otherwise, the program will automatically add the .txt extension.

Open this file in your browser by entering “localhost/test.php” (without quotes) into the address bar. Don't open the file directly through Explorer—you'll only see the code you entered earlier. You need to use the above URL to have the browser try to access the Apache web server, which runs PHP to interpret the script.

If everything goes well, you will see a page with information about setting up PHP. Congratulations - you have successfully installed PHP and configured Apache to work with it. You can upload the same test.php file to your hosting and run it there to find out how the hosting has configured PHP and try to reproduce these settings on your machine.

If this doesn't work, check to see if the PHP installation or Apache installation is throwing errors. To do this, open a command prompt window and run php-cgi.exe on the test.php file, for example c:phpphp-cgi test.php .

If you called PHP from the command line and saw a large HTML file with all the PHP configuration information, then PHP is configured correctly. The problem is probably related to the Apache configuration. Make sure you restart Apache after making configuration changes and that you have configured the web server correctly.