php run code from command line

Php run code from command line

There are three different ways of supplying the CLI SAPI with PHP code to be executed:

    Tell PHP to execute a certain file.

    Pass the PHP code to execute directly on the command line.

    Special care has to be taken with regard to shell variable substitution and usage of quotes.

    Provide the PHP code to execute via standard input ( stdin ).

    This gives the powerful ability to create PHP code dynamically and feed it to the binary, as shown in this (fictional) example:

    Example #1 Execute PHP script as shell script

    Assuming this file is named test in the current directory, it is now possible to do the following:

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

    The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.

    Example #3 Batch file to run a command line PHP script (script.bat)

    See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.

    On Windows it is recommended to run PHP under an actual user account. When running under a network service certain operations will fail, because «No mapping between account names and security IDs was done».

    User Contributed Notes 7 notes

    On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
    For example:

    1. is the standard way to start a script. (compare «#!/bin/bash».)

    3. if you don’t need to use env, you can pass ONE parameter here. For example, to ignore the system’s PHP.ini, and go with the defaults, use «-n». (See «man php».)

    4. or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it’s too late: if your script has a parse error, it will silently die.

    Summary: use (2) for maximum portability, and (4) for maximum debugging.

    Источник

    Использование PHP в командной строке

    Содержание

    User Contributed Notes 35 notes

    ?>

    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 🙂

    Here is a proposal:

    $ret = array
    (
    ‘commands’ => array(),
    ‘options’ => array(),
    ‘flags’ => array(),
    ‘arguments’ => array(),
    );

    /* 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.

    an another «another variant» :

    [arg2] => val2
    [arg3] => arg3
    [arg4] => true
    [arg5] => true
    [arg5] => false
    )

    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

    SECURITY_ATTRIBUTES sa = < sizeof(SECURITY_ATTRIBUTES) >;
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;

    // 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.

    Источник

    Running PHP script from the command line

    How can I run a PHP script from the command line using the PHP interpreter which is used to parse web scripts?

    3 Answers 3

    To run php interactively:

    (So you can paste/write code in the console.)

    To make it parse a file and output to the console:

    Parse a file and output to another file:

    Do you need something else?

    To run only a small part, one line or like, you can use:

    If you are running Linux then do man php at the console.

    If you need/want to run PHP through fpm (FastCGI Process Manager), use cli fcgi:

    Where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an «apache2» directory and a «cli» directory. Each has a «php.ini» file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.

    If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn’t. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.

    You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.

    Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.

    Источник

    Run PHP Files From the Command Line

    I’ve been brushing up on my shell scripting lately. I just got a MacBook and never felt compelled to spend too much time with Cygwin. I’m learning quite a bit now but there are still some tasks that I’d need to accomplish sooner rather than later. I know how to accomplish the task using PHP so I’ve got that to my advantage. What’s awesome is that I can quickly and easily run my PHP files from the command line.

    The Shell Script

    I’m not sure whether I consider using PHP instead of a straight shell script as being resourceful or using PHP as a crutch. What are your thoughts?

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    Recent Features

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    Responsive and Infinitely Scalable JS Animations

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    Convert XML to JSON with JavaScript

    Incredible Demos

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    jQuery UI DatePicker: Disable Specified Days

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    Create a Photo Stack Effect with Pure CSS Animations or MooTools

    Discussion

    I don’t consider it a crutch. There are many useful reasons to run PHP in command line. You may have already seen this, but IBM has a nice article about it here: http://www.ibm.com/developerworks/opensource/library/os-php-command/

    I’m also using PHP scripts from the command line, but instead of invoking scripts through php executable I prefer the ‘#!/usr/bin/php’ header at the top of the script and marking it as executable. It’s like a RAD tool for me and, I believe, for others too.

    PHP makes a decent command line language, but Perl is more suited to the task imho

    Since I run windows and haven’t the heart to setup cygwin+php, I made a little php executer which more or less works like a command line. It doesn’t use eval but I think it could still be better. I’d advise to put this in a production environment of course, just development.

    More often than not I work in the command line with vim. running php from the command line is better suited for perl, but I do use it from time to time with php scripts.

    Primarily scraper scripts where I want to ensure the code is returning the values I want. It’s quick and easy to get the dirt.

    I’m a telecom programmer. I process hundreds of millions of records daily – with PHP. Yes, I know – awk is faster, perl is faster…..

    Perl? Such ugly code. No thanks.

    Guess what, PHP does a great job and is fast enough to meet my needs. I literally have dozens of scripts that process different data sets each day.

    The good thing about being able to run PHP from the command line is you can use the framework/libraries that your website uses.

    I’ve come to agree: not a crutch. It works for a reason. PHP (and MooTools) FTW!

    I use php for some cron jobs 🙂

    Are you following me? I just setup my work PC to run PHP for the command line. Do you have cygwin setup to run through your command line as well? I find it more and more useful.

    I’m a PHP CLI fan as well.. In addition to the other posts I have the following use as well:
    I have quite a few scripts that will run continuously and when you press CTRL-C (SIGINT) you process this info and show some statistics for the retrieved data.
    Try that on a website, it would be nearly impossible to do this safely without a chance that this test will run for days or weeks. (without the chance to see the statistics after warts)
    If you combine the above with the use of ‘screen’, you get the change to do some testing over days and see the statistics of that after (for instance) a week.
    I use this for testing connection and if things are working properly.
    This could have been done with perl or bash as well but the same problem as stated earlier arises: talking with a sql database is tough.
    Aside from this I just like php more than other languages.

    I invoke the Salesforce API with CLI PHP to do various testing and administration tasks. I also use it to generate CSV from mysql. I like Perl, but it’s a matter of preference, not a crutch.

    Источник

    How To Run PHP From Windows Command Line in WAMPServer

    I’m new to php and wanted to run php from command line. I have installed WAMP and set the «System Variables» to my php folder ( which is C:\wamp\bin\php\php5.4.3 ).

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    11 Answers 11

    The PHP CLI as its called ( php for the Command Line Interface ) is called php.exe It lives in c:\wamp\bin\php\php5.x.y\php.exe ( where x and y are the version numbers of php that you have installed )

    If you want to create php scrips to run from the command line then great its easy and very useful.

    Create yourself a batch file like this, lets call it phppath.cmd :

    Change x.y.z to a valid folder name for a version of PHP that you have installed within WAMPServer

    Save this into one of your folders that is already on your PATH, so you can run it from anywhere.

    Now from a command window, cd into your source folder and run >phppath.

    It should work like a dream.

    Here is an example that configures PHP Composer and PEAR if required and they exist

    Call this command file like this to use the default version of PHP

    Or to get a specific version of PHP like this

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    I remember one time when I stumbled upon this issue a few years ago, it’s because windows don’t have readline, therefore no interactive shell, to use php interactive mode without readline support, you can do this instead:

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    Try using batch file

    Dependency

    if you got error php not recognize any internal or external command then goto environment variable and edit path to php.exe «C:\wamp\bin\php\php5.4.3»

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    The problem you are describing sounds like your version of PHP might be missing the readline PHP module, causing the interactive shell to not work. I base this on this PHP bug submission.

    And see if «readline» appears in the output.

    There might be good reasons for omitting readline from the distribution. PHP is typically executed by a web server; so it is not really need for most use cases. I am sure you can execute PHP code in a file from the command prompt, using:

    There is also the phpsh project which provides a (better) interactive shell for PHP. However, some people have had trouble running it under Windows (I did not try this myself).

    Edit: According to the documentation here, readline is not supported under Windows:

    Note: This extension is not available on Windows platforms.

    So, if that is correct, your options are:

    -r allows to run code without using script tags

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    You can run php pages using php.exe create some php file with php code and in the cmd write «[PATH to php.ext]\php.exe [path_to_file]\file.php»

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    php run code from command line. Смотреть фото php run code from command line. Смотреть картинку php run code from command line. Картинка про php run code from command line. Фото php run code from command line

    You can also use «Bat to Exe» converter to easy use.

    Источник

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *