Как установить Composer и PHP в Windows (инструкция)
Для работы Composer на ПК с ОС Windows в обязательном порядке нужен php. Потому установка Компосера начинается с установки пхп. Для начала давайте проверим, возможно php уже установлен. Открываем консоль и вводим команду:
Если результатом выполнения станет сообщение:
«php» не является внутренней или внешней командой исполняемой программой или пакетным файлом
Установка php в Windows
Переходим к непосредственной установке. Для этого переходим на сайт php.net и в разделе «Downloads» кликаем по ссылке «Windows downloads».
На этом установка php закончена. Остаётся только произвести настройку. Открываем проводник, кликаем правой кнопкой мыши по «Этот компьютер», далее «Свойства». В появившемся окне выбираем пункт «Дополнительные параметры системы» в колонке слева.
Подтверждаем действие нажатием «ок».
Установка curl в php
Настоятельно рекомендую настроить поддержку curl (по умолчанию она отключена). Для этого открываем папку с нашим php, находим файл php.ini и в самый конец добавляем
Установка Composer
После того как php успешно установлен в системе установка Composer будет весьма простой. Скачиваем установщик с официального сайта. Запускаем. На шаге «Choose the command-line PHP. » скорее всего уже будет указан правильный путь до файла php.exe
Как устанавливать библиотеки с git-hub через Composer
Сам в своё время потратил кучу времени, чтобы понять, что означают инструкции типа:
Добавьте библиотеку в файл composer.json вашего проекта
На самом деле всё очень просто. Создаем на компьютере папку в которую хотим установить нужную библиотеку с гитхаба. Создаем файл с названием composer.json. В это файл засовываем тот код, который указан на гитхабе у данной библиотеки. Сохраняем.
Если у вас установлен Composer, пхп среда и активен curl, то с высокой долей вероятности запустится установка, а через какое-то время в папке появятся желаемые файл, с которыми уже можно будет спокойно работать!
Note: A Unix man ual page was added in PHP 4.3.2. You may view this by typing man php in your shell environment.
Remarkable differences of the CLI SAPI compared to other SAPI s:
Plain text error messages (no HTML formatting).
There are certain php.ini directives which are overridden by the CLI SAPI because they do not make sense in shell environments:
Table 42-1. Overridden php.ini directives
Note: These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This is a limitation because those default values are applied after all configuration files have been parsed. However, their value can be changed during runtime (which does not make sense for all of those directives, e.g. register_argc_argv ).
To ease working in the shell environment, the following constants are defined:
Table 42-2. CLI specific Constants
Given the above, you don’t need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:
You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.
The CLI SAPI does not change the current directory to the directory of the executed script!
Example showing the difference to the CGI SAPI :
// Our simple test application named test.php echo getcwd (), «\n» ; ?>
This clearly shows that PHP changes its current directory to the one of the executed script.
This allows greater flexibility when writing shell tools in PHP.
The CLI SAPI has three different ways of getting the PHP code you want to execute:
Telling PHP to execute a certain file.
Pass the PHP code to execute directly on the command line.
Special care has to be taken in regards of shell variable substitution and quoting usage.
Provide the PHP code to execute via standard input ( stdin ).
This gives the powerful ability to dynamically create PHP code and feed it to the binary, as shown in this (fictional) example:
You cannot combine any of the three ways to execute code.
Long options are available since PHP 4.3.3.
Table 42-3. Command line options
Option
Long Option
Description
-s
—syntax-highlight
Display colour syntax highlighted source.
This option uses the internal mechanism to parse the file and produces a HTML highlighted version of it and writes it to standard output. Note that all it does it to generate a block of [. ] HTML tags, no HTML headers.
Display source with stripped comments and whitespace.
Writes the PHP, PHP SAPI, and Zend version to standard output, e.g.
With this option one can either specify a directory where to look for php.ini or you can specify a custom INI file directly (which does not need to be named php.ini ), e.g.:
Ignore php.ini at all. This switch is available since PHP 4.3.0.
Runs PHP interactively.
Generate extended information for debugger/profiler.
Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually specified /etc/ld.so.conf on Linux systems). Passing a filename with an absolute path information will not use the systems library search path. A relative filename with a directory information will tell PHP only to try to load the extension relative to the current directory.
Using this option, PHP prints out the built in (and loaded) PHP and Zend modules:
Note: Care has to be taken when using this form of PHP to not collide with command line variable substitution done by the shell.
If you are using a shell different from sh/bash, you might experience further issues. Feel free to open a bug report at http://bugs.php.net/ or send a mail to phpdoc@lists.php.net. One can still easily run into troubles when trying to get shell variables into the code or using backslashes for escaping. You’ve been warned.
Example 42-1. Script intended to be run from command line (script.php)
It behaves exactly like you’d expect with cgi-php.
Even better, instead of putting that line in every file, take advantage of PHP’s auto_prepend_file directive. Put that line in its own file and set the auto_prepend_file directive in your cli-specific php.ini like so:
It will be automatically prepended to any PHP file run from the command line.
When you’re writing one line php scripts remember that ‘php://stdin’ is your friend. Here’s a simple program I use to format PHP code for inclusion on my blog:
Just a note for people trying to use interactive mode from the commandline.
The purpose of interactive mode is to parse code snippits without actually leaving php, and it works like this:
I noticed this somehow got ommited from the docs, hope it helps someone!
If your php script doesn’t run with shebang (#!/usr/bin/php), and it issues the beautifull and informative error message: «Command not found.» just dos2unix yourscript.php et voila.
If your php script doesn’t run with shebang (#/usr/bin/php), and it issues the beautifull and informative message: «Invalid null command.» it’s probably because the «!» is missing in the the shebang line (like what’s above) or something else in that area.
Parsing commandline argument GET String without changing the PHP script (linux shell): URL: index.php?a=1&b=2 Result: output.html
(no need to change php.ini)
Ok, I’ve had a heck of a time with PHP > 4.3.x and whether to use CLI vs CGI. The CGI version of 4.3.2 would return (in browser): — No input file specified. —
And the CLI version would return: — 500 Internal Server Error —
It appears that in CGI mode, PHP looks at the environment variable PATH_TRANSLATED to determine the script to execute and ignores command line. That is why in the absensce of this environment variable, you get «No input file specified.» However, in CLI mode the HTTP headers are not printed. I believe this is intended behavior for both situations but creates a problem when you have a CGI wrapper that sends environment variables but passes the actual script name on the command line.
By modifying my CGI wrapper to create this PATH_TRANSLATED environment variable, it solved my problem, and I was able to run the CGI build of 4.3.2
If you want to be interactive with the user and accept user input, all you need to do is read from stdin.
Parsing command line: optimization is evil!
One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that 🙂
/* vim: set expandtab tabstop=2 shiftwidth=2: */ ?>
i use emacs in c-mode for editing. in 4.3, starting a cli script like so:
Just another variant of previous script that group arguments doesn’t starts with ‘-‘ or ‘—‘
If you edit a php file in windows, upload and run it on linux with command line method. You may encounter a running problem probably like that:
Or you may encounter some other strange problem. Care the enter key. In windows environment, enter key generate two binary characters ‘0D0A’. But in Linux, enter key generate just only a ‘OA’. I wish it can help someone if you are using windows to code php and run it as a command line program on linux.
How to change current directory in PHP script to script’s directory when running it from command line using PHP 4.3.0? (you’ll probably need to add this to older scripts when running them under PHP 4.3.0 for backwards compatibility)
Here’s what I am using: chdir(preg_replace(‘/\\/[^\\/]+$/’,»»,$PHP_SELF));
Note: documentation says that «PHP_SELF» is not available in command-line PHP scripts. Though, it IS available. Probably this will be changed in future version, so don’t rely on this line of code.
Spawning php-win.exe as a child process to handle scripting in Windows applications has a few quirks (all having to do with pipes between Windows apps and console apps).
// We will run php.exe as a child process after creating // two pipes and attaching them to stdin and stdout // of the child process // Define sa struct such that child inherits our handles
// Create the handles for our two pipes (two handles per pipe, one for each end) // We will have one pipe for stdin, and one for stdout, each with a READ and WRITE end HANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;
// Now we have two pipes, we can create the process // First, fill out the usage structs STARTUPINFO si = < sizeof(STARTUPINFO) >; PROCESS_INFORMATION pi; si.dwFlags = STARTF_USESTDHANDLES; si.hStdOutput = hStdoutWr; si.hStdInput = hStdinRd;
// And finally, create the process CreateProcess (NULL, «c:\\php\\php-win.exe», NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
// Close the handles we aren’t using CloseHandle(hStdoutWr); CloseHandle(hStdinRd);
// When we’re done writing to stdin, we close that pipe CloseHandle(hStdinWr);
// Reading from stdout is only slightly more complicated int i;
std::string processed(«»); char buf[128];
I modified the PATHEXT environment variable in Windows XP, from the » ‘system’ control panel applet->’Advanced’ tab->’Environment Variables’ button-> ‘System variables’ text area».
Then from control panel «Folder Options» applet-> ‘File Types’ tab, I added a new file extention (php3), using the button ‘New’ and typing php3 in the window that pops up.
Then in the ‘Details for php3 extention’ area I used the ‘Change’ button to look for the Php.exe executable so that the php3 file extentions are associated with the php executable.
You have to modify also the ‘PATH’ environment variable, pointing to the folder where the php executable is installed
Hope this is useful to somebody
For those of you who want the old CGI behaviour that changes to the actual directory of the script use: chdir(dirname($_SERVER[‘argv’][0]));
at the beginning of your scripts.
This posting is not a php-only problem, but hopefully will save someone a few hours of headaches. Running on MacOS (although this could happen on any *nix I suppose), I was unable to get the script to execute without specifically envoking php from the command line:
[macg4:valencia/jobs] tim% test.php ./test.php: Command not found.
However, it worked just fine when php was envoked on the command line:
[macg4:valencia/jobs] tim% php test.php Well, here we are. Now what?
Was file access mode set for executable? Yup.
And you did, of course, remember to add the php command as the first line of your script, yeah? Of course.
Aaahhh. in BBEdit check how the file is being saved! Mac? Unix? or Dos? Bingo. It had been saved as Dos format. Change it to Unix:
NB: If you’re editing your php files on multiple platforms (i.e. Windows and Linux), make sure you double check the files are saved in a Unix format. those \r’s and \n’s ‘ll bite cha!
You can also call the script from the command line after chmod’ing the file (ie: chmod 755 file.php).
Adding a pause() function to PHP waiting for any user input returning it:
To hand over the GET-variables in interactive mode like in HTTP-Mode (e.g. your URI is myprog.html?hugo=bla&bla=hugo), you have to call
php myprog.html ‘&hugo=bla&bla=hugo’
dunno if this is on linux the same but on windows evertime you send somthing to the console screen php is waiting for the console to return. therefor if you send a lot of small short amounts of text, the console is starting to be using more cpu-cycles then php and thus slowing the script.
now this is just a small example but if you are writing an app that is outputting a lot to the console, i.e. a text based screen with frequent updates, then its much better to first cach all output, and output is as one big chunk of text instead of one char a the time.
ouput buffering is ideal for this. in my script i outputted almost 4000chars of info and just by caching it first, it speeded up by almost 400% and dropped cpu-usage.
because what is being displayed doesn’t matter, be it 2 chars or 40.0000 chars, just the call to output takes a great deal of time. remeber that.
maybe someone can test if this is the same on unix-based systems. it seems that the STDOUT stream just waits for the console to report ready, before continueing execution.
In the above example, you would use: #!/usr/local/bin/php
I was looking for a way to interactively get a single character response from user. Using STDIN with fread, fgets and such will only work after pressing enter. So I came up with this instead:
For example you can do this code:
This will just output each line of the input file without doing anything to it.
On *nix systems you usually have the php executable available in shell, so you can run command-line scripts like unit tests and such, but on Windows this isn’t usually the case. Let’s fix that!
There’s two ways to do this: Temporary and permanent
Temporary
The temporary method will affect only a single command prompt.
Open command prompt (start, run, cmd) and type in the following:
Where C:\path\to\php is the folder where your php.exe file is located. After this, you should be able to run PHP in any folder like this:
Your output may vary depending on your PHP version and extensions.
Permanent
The permanent method will affect all command prompts and will persist upon reboots. It can also be set up to affect all users on the system and not only your account.
From this screen you can edit the environment variables of the system. If you only wish to modify them on your user account, click New under your own variables box and type in the following:
COMPOSER: choose the command line php you want to use. There is nothing there
Posted by: admin April 3, 2018 Leave a comment
I’m using the Composer Windows installer and it brings me to this window,
There is nothing in the dropdown, but I’m not sure where to pick the correct command-line PHP. Should I direct it to the php.exe in XAMPP folder?
If you are using wampp do this:
Click the browser button.
Then select your file path like following path.
If you are using xampp do this:
Click the browser button.
Then select your file path like the following path.
Yes you have to select php.exe from your xampp folder if you are using localhost. choose this path… xampp > php > php.exe
I came across the same screen. I’m using Vetrigo Server and all that I did was pick the php.exe file path by clicking on “Browse…” button (on my machine it is on C:\Program Files\VertrigoServ\Php\php.exe). Hope that helps.
Related Posts
php – Call to a member function copy() on null – Stack Overflow
php – Laravel Validator: limiting unique field check to specific product – Stack Overflow
sql – set input max length with php – Stack Overflow
Questions: I’m trying to set a max value to my inputs. I can do it with html but anyone can easily overwrite that in any browser’s inspect menu. So I want to use php to set it. I don’.