4 Tips to help you create PHP console tools

table of contents
Hello.
I'm Mandai, the Wild team member in charge of development.
We often get the urge to create a simple tool to automate tedious tasks, don't we? It's
what you might call a "spur-of-the-moment creation," but as you've probably experienced, such tools usually have a predetermined function and aren't something you'd bother opening a browser to run. So, we
want to automate even that "opening a browser" step, right?
In such cases, you might turn it into a console tool and schedule it to run periodically, but PHP can also be used for console applications, so I've gathered some handy tips for that purpose. Please
note that I have mainly only tested this on Linux.
Get the home directory path
Speaking of consoles, we're talking about shell scripts, and in the case
of shell scripts, the path to your home directory can be obtained using "~".
If you try to load a file in the user's home directory using a similar path in PHP, an error will occur
<?php echo file_get_contents('~/hogehoge.txt'); # 上記のソースを実行すると、以下のエラーが発生 PHP Warning: file_get_contents(~/hogehoge.txt): failed to open stream: No such file or directory in Command line code on line 1
So, you might be tempted to get the execution user and concatenate it with /home, and try various methods to create the path, but
the home directory path is actually stored in the superglobal variable $_SERVER.
<?php echo file_get_contents($_SERVER['HOME']. '/hogehoge.txt'); # 上記のソースを実行すると、テキストファイルの中身が表示される hogehoge
This is very useful when you want to place the configuration file in the user's home directory, similar to how bash
works. It's a blind spot (or rather, a blind spot for me) that data is stored in the $_SERVER variable even though it's a console execution.
the documentationIt's like a hidden parameter not even mentioned in
(It's briefly mentioned in the comments after the main text.)
How to take arguments
Changing behavior based on arguments is commonplace in the command line world, so of course it's possible in PHPCLI as well.
However, even though it's a superglobal variable...
- Does not start with _
- Not defined in uppercase
- Is it c? Is it v? Please be clear!
As a result, I can't remember the words right away, and if I don't use them for a while, I forget them
stores the arguments passed at runtime$argv.
Also, if you want to pass a string with line breaks to $argv, enclosing the string in "" or ' will make it work as intended
For example, prepare a source that simply var_dumps the following arguments directly
<?php var_dump($argv);
Next, let's run the source code with a string containing line breaks as an argument
php test.php hogehoge 'I'll add a newline' # When you run the above command, the following will be displayed: array(3) { [0] => string(8) "test.php" [1] => string(8) "hogehoge" [2] => string(22) "I'll add a newline" }
It looks like a lot of things will be progressing
Adding color to error messages (+bonus)
If you want to have some fun, why not try coloring your error messages?
In Linux, you can make the echoed string colorful and change the background color
This can easily be achieved using the same technique
<?php # hogehogeを赤字で表示するコード echo "\e[31mhogehoge\e[m"; echo "\033[31mhogehoge\033[m";
Both of the above codes display "hogehoge" in red, but at first glance it's hard to understand what they mean, so
let's break them down a bit.
<?php # hogehogeを赤字で表示するコード echo "\e[31m". "hogehoge". "\e[m"; echo "\033[31m". "hogehoge". "\033[m";
Let's separate the "hogehoge" part from the rest. Then, we can vaguely see a pattern. It
seems that you should enclose the string you want to change the color of with "\e[**m" or "\033[**m".
The only remaining part is the "31" at the beginning, which
specifies the text color.
We split "31" into "3" and "1," where "3" specifies the text color and "1" specifies red.
So, to change the text color to something else, you change "1" to "2," and so on.
I mentioned that the "3" in "31" specifies the text color, but if it becomes "4", it specifies the background color
.
<?php echo "\e[41m". "hogehoge". "\e[m"; echo "\033[41m". "hogehoge". "\033[m";
The above code will result in a red background
If you want to change both the text color and the background color, place them side by side with a semicolon
<?php echo "\e[31;41m". "hogehoge". "\e[m"; echo "\033[31;41m". "hogehoge". "\033[m";
The code above will just display a red rectangle and no text, but it will achieve its purpose
As for more advanced features, you can also use this setting to underline, bold, invert the text and background colors, and make the text blink
<?php echo "\e[31;1m". "hogehoge". "\e[m"; // 赤い太字で表示 echo "\e[31;42;1m". "hogehoge". "\e[m"; // 赤い太字を緑の背景で表示 echo "\e[7m". "hogehoge". "\e[m"; // 文字色と背景色を反転して表示
Inversion and other features are less likely to strain your eyes, so you can use them alone
Command options to use when you want to quickly check only specific code
When creating console tools, you
might occasionally have small questions, such as what format the execution result will take or whether a particular way of writing the code will cause an error.
In such cases, I'd like to introduce the PHP option "-r" that you can quickly try out.
For example, let's say you want to change permissions.
You can quickly change them with the chmod function, but if you want to test if it works, you don't have to write test code; you can write PHP code directly in the command line. What I
like about it is that you don't even need the PHP opening tag, "php".
php -r "chmod('/path/to/hoge', 777)" # You can see the results immediately with the ls command!
I intended to write it in a way that was similar to `chmod 777 /path/to/hoge`, but the permissions weren't actually changed. I'm
trying to figure out what's wrong by reading the documentation and going through trial and error to find the correct solution.
Edit the file → Save → Go to console → Run the php file → (´・ω・`)
To be honest, repeating this process over and over is a pain, so if you can extract something and test it easily like in the example above, it's probably less work to do it from the command line
That's all
0
