1

I want to run a php script from the command line that is always running and constantly updating a variable.

I then want any php script that is run in the meantime (probably but not necessarily from the web) to be able to read that variable at any time.

Anyone know how I can do this?

Thanks.

1
  • I would just use Redis. Fast, easy, and the ability to do more communication between the CLI and the web script using RPC. Commented Dec 14, 2015 at 12:05

4 Answers 4

1

Here, you want some kind of inter-process communication mecanism.

You cannot use a PHP variable for that : these are local to the script they're in.

Which means you'll have to use some "external" tool to store your data, like, to only speak of a few :

  • a file
  • a database (SQLite, MySQL, ...)
  • some shared-memory segment

In each case, you'll have :

  • One script that write to the data-storage space -- i.e. your first always running script
  • One or many other scripts that will read from the data-store
Sign up to request clarification or add additional context in comments.

Comments

0

You should write the variable to a file with the CLI script and read from that with the other script.

Be sure to use flock to prevent race conditions.

1 Comment

In some circumstances, you can not rely on flock. See php.net for more information.
0

You can write a php socket based server script, which will listen on desired port. Find article here. Then your client php script can connect to it either locally or from the web and retrieve any data, including variables. You can use any simple protocol designed by you or well known like XML to transfer variables.

Comments

0

Lots of idea's:

  1. At set intervals it appends/writes to a file.
  2. You use sqlite and write your data to it.
  3. Your use a small memcached service as your intermediary.
  4. You go somewhat crazy and write a socket class, listen on a set port, then make non-blocking calls to check.

1-2 are probably the simplest 3 would work great if you need to query the value a lot 4 would be fun, but might not be worth the effort.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.