php run script from console

How to run php script on server through command line

I have created a php script to import rss feed into the database. The feed which is huge (from year 2004 to 2010, approx 2 million records) has to be inserted into the database. I have been running the script in browser but the pace it is inserting (approx. 1 per second) i doubt it takes another 20-25 days to input this data even if i run it 24 hrs a day. I have tried it running on different browser windows at the same time and have finished only 70000 records in last two days. I am not sure how the server would react if i run 10-12 instances of it simultaneously.

A programmer at my client’s end says that i could run it directly on the server through command line. Could anyone tell me how much difference it would make if i run it through command line? Also what is the command line syntax to run it? I am on apache, php/mysql. I tried out over the web for a similar answer but they seem quite confusing to me as i am not a system administrator or that good in linux although i have done tasks like svn repositories and installing some apache modules on server in the past so i hope i could manage this if someone tell me how to do it.

5 Answers 5

Difference in speed: Minimal. All you save on is blocking on NET I/O and connection (and the apache overhead which is negligible).

You may only have the php5-mod package installed which is php for apache, you may have to install the actual command line interpreter, however a lot of distros install both. Personally I think you have an efficiency problem in the algorithm. Something taking days and days seems like it could be sped up by caching & worst-case performance analysis (Big-O notation).

Also, php vanilla isn’t very fast, there’s lots of ways to make it really fast, but if you’re doing heavy computation, you should consider c/c++, C#/Mono (Maybe), possibly python (can be pre-compiled, may not actually be much faster).

But the exploration of these other outlets is highly recommended.

Источник

Использование 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 script from console. Смотреть фото php run script from console. Смотреть картинку php run script from console. Картинка про php run script from console. Фото php run script from console

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

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.

Источник

How to Run a PHP Script? Step By Step Guide!

php run script from console. Смотреть фото php run script from console. Смотреть картинку php run script from console. Картинка про php run script from console. Фото php run script from console
Hello and welcome to the start of codeofaninja.com’s series of web development articles!

Overview

Setting up a development environment for PHP programming is easy. Download the code editor you prefer, I personally like atom.io text editor.

Next is to install XAMPP, the most popular PHP development environment. This package contains Apache, PHP & MariaDB or MySQL database applications.

Many people emailed me with a main question: Mike, how to run a PHP script? This post is my answer to you guys and to those people who will need this in the future.

In the following tutorial, we will learn how to install XAMPP, how to run a PHP script, manage database with PhpMyAdmin and run a sample PHP script that fetches a record from the database.

Install XAMPP

Go to this link and download XAMPP for your operating system. XAMPP is available for Windows, Linux or Mac.

Here’s a video about how you can install and use XAMPP.

Run Your First PHP Script

The following is an example about how to run a PHP script. What this program does is show a «Hello World!» text on the screen or webpage.

Go to XAMPP server directory

I’m using Windows, so my root server directory is «C:\xampp\htdocs\».

Create hello.php

Create a file and name it » hello.php «

Code Inside hello.php

Open hello.php and put the following code.

Open New Tab

Run it by opening a new tab in your browser

Load hello.php

On you browser window, type http://localhost/hello.php

Output

You should see the following output.
php run script from console. Смотреть фото php run script from console. Смотреть картинку php run script from console. Картинка про php run script from console. Фото php run script from console
Great job, you just run a PHP script!

Manage MySQL with PhpMyAdmin

MySQL is an open-source relational database management system (RDBMS). MySQL is a popular choice of database for use in web applications.

phpMyAdmin is a free and open source tool written in PHP intended to handle the administration of MySQL with the use of a web browser. In the following examples, we will see how easy we can handle MySQL with PhpMyAdmin.

Create a Database

Create a Table

Insert Data

Click the «products» table.

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

Click the «Insert» tab.

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

Fill out the form, mimic the data on the following image. Click the «Go» button.

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

Great job! We now have a database, a table inside the database and a record inside the table.

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

Useful Videos

1. Create a database and import MySQL file.

2. Create a database and create table.

Run PHP Script with Database

In the following steps, we will run a PHP script that fetches one record from the MySQL database.

Go to XAMPP server directory

Go to your «C:\xampp\htdocs\» directory

Create read_one.php

Create a file and name it » read_one.php «

Code Inside read_one.php

The numbers 1-8 in the following code are called «code comments». It explains each part of our simple code below. Open read_one.php and put the following code.

Open Your Browser

Run it by opening you your browser

Load read_one.php

On you browser window, type http://localhost/read_one.php

Output

You should see the following output.
php run script from console. Смотреть фото php run script from console. Смотреть картинку php run script from console. Картинка про php run script from console. Фото php run script from console
Awesome! You are now ready to learn more about web programming and development.

Online Resources

Here in codeofaninja.com, we want to simplify learning for you to actually build something. But it is also important for you to read and study more. The following are my suggestions where to learn more.

You can always go back to the list above while you go along our series of web programming tutorials.

What’s Next?

Related Tutorials

Some Notes

Found An Issue?

Before you write a comment, remember to read this guide and our code of conduct.

Subscribe to CodeOfaNinja

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Источник

Running PHP script from command line as background process

I’m trying to run a PHP script continually in the background via the command line in Linux. I have tried the command php filename.php & but it seems like the script execution terminates very quickly, while it should keep running until the process is terminated.

4 Answers 4

Are you sure the script doesn’t contain any errors? This is what normally makes «execution terminates very quickly«.
First, append:

error_reporting(E_ALL); ini_set(‘display_errors’, 1);

at the top of your script to display any errors it may have, then you can use:

nohup php filename.php &

nohup runs a command even if the session is disconnected or the user logs out.

nohup php filename.php >/dev/null 2>&1 &

Same as above but doesn’t create nohup.out file.

You can also use:
ignore_user_abort(1);

Set whether a client disconnect should abort script execution

Limits the script maximum execution time, in this case it will run until the process finishes or the apache process restarts.

Notes

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

the process may be closed when your session is closed.

try using nohup php filename.php

Standard in, out, and error

The short explanation, therefore, is “all output from this command should be shoved into a black hole.” That’s one good way to make a program be really quiet!

& at the end puts the command in background.

Источник

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

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