[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Successor to CentOS] AlmaLinux OS server construction/migration service

[Successor to CentOS] AlmaLinux OS server construction/migration service

[For WordPress only] Cloud server “Web Speed”

[For WordPress only] Cloud server “Web Speed”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Reservation system development] EDISONE customization development service

[Reservation system development] EDISONE customization development service

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[Global exclusive service] Beyond's MSP in North America and China

[Global exclusive service] Beyond's MSP in North America and China

[YouTube] Beyond official channel “Biyomaru Channel”

[YouTube] Beyond official channel “Biyomaru Channel”

4 useful tips when creating PHP console tools

Hello.
I'm Mandai, in charge of Wild on the development team.

We often feel the urge to create a small tool to automate a tedious task.
I think it's a common saying that you create something in a hurry, but as you all have experienced, it's not something that requires you to go out of your way to launch a browser and run it, since it's what you're supposed to do with a tool. Sho.
I want to automate the process of starting up that browser...

In such cases, I turn it into a console tool and run it periodically, but since PHP can also be used as a console application, I have gathered some trivia that will be useful in such cases.
We have only confirmed its operation mainly on Linux, so don't worry.

 

Get home directory path

Speaking of consoles, we mean shell scripts, so in
the case of shell scripts, you can get the home directory path with "~".

I get an error in PHP when I specify a similar path and try to load a file that exists in the user's home directory.

<?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


 Now, I would like to somehow create a path by getting the execution user and attaching it to /home, but
the home directory path is properly stored in the super global variable $_SERVER.

<?php echo file_get_contents($_SERVER['HOME']. '/hogehoge.txt'); # 上記のソースを実行すると、テキストファイルの中身が表示される hogehoge


 This is useful when you want to put a configuration file in the user home like bash.
It is a blind spot that the $_SERVER variable contains data even though it is executed on the console.
It is a hidden parameter that is not even listed in
the documentation (It's clearly mentioned in the comment after the main text)

 

How to take arguments

Changing behavior depending on arguments is a natural thing in the world of command lines, so of course you can do it with PHPCLI as well.
However, even though it is a super global variable

  • Does not start with _
  • not defined in uppercase
  • Is it c? Is it v? Be clear!

I can't remember the words right away, and if I haven't used them for a while, I'll forget them.

The superglobal variable that stores arguments passed at runtime $argv .

Also, if you want to pass a string with line breaks to $argv, wrapping the string with "" or '' will work as intended.

For example, prepare a source that simply var_dumps the following arguments directly.

<?php var_dump($argv);

 
Next, try executing the source with the string including line breaks as an argument.

php test.php hogehoge 'Enter line break' # When you execute the above command, the following will be displayed array(3) { [0] => string(8) "test.php" [1] => string(8) "hogehoge" [2] => string(22) "line break" }

 
It looks like things are going well.

 

Try adding color to error messages (+bonus)

If you want to add some fun, why not add color to your error messages?

On Linux, you can make the echo string colorful and change the background color.

This can be easily accomplished 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 I can't understand what they mean at first glance, so
I'll break it down a bit.

<?php # hogehogeを赤字で表示するコード echo "\e[31m". "hogehoge". "\e[m"; echo "\033[31m". "hogehoge". "\033[m";


 Let's divide it into the "hogehoge" part and the non-hogehoge part. Then, I found some sort of regularity.
It seems to be a good idea to wrap the string you want to change color in "\e[**m" or "\033[**m"].

After that, the number "31" that is attached only to the first part
is used to specify the font color.
Dividing 31 into 3 and 1, 3 specifies the font color and 1 specifies the color red.
In other words, when specifying a different font color, change 1 to 2.

I wrote that the 3 part of 31 specifies the font color, but if it becomes 4, it specifies the background color.
In other words

<?php echo "\e[41m". "hogehoge". "\e[m"; echo "\033[41m". "hogehoge". "\033[m";

 
The above code will display the background color as red.

If you want to change both the font color and background color using a matching technique, place them next to each other with a semicolon between them.

<?php echo "\e[31;41m". "hogehoge". "\e[m"; echo "\033[31;41m". "hogehoge". "\033[m";

 
The above code only displays a red rectangle and no text, but it accomplishes the purpose.

In addition, you can use this setting to underline, make bold, invert the font 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"; // 文字色と背景色を反転して表示

 
You can also use it alone since it won't cause your eyes to flicker even if you use it inverted.

 

Command options to use when you want to quickly check only specific code

When you're creating a console tool, you
may come across small questions like how the execution results will be returned, or whether this way of writing will cause an error.In
such cases, there are PHP options that you can quickly try. Introducing "-r".

For example, let's say you want to change permissions.
You can quickly change it using the chmod function, but if you want to see if it works, you can write PHP code directly in the command without having to go through the trouble of writing test code.
PHP's opening tag, "

php -r "chmod('/path/to/hoge', 777)" # Get the results right away with the ls command!


 As an image, I intended to write something like chmod 777 /path/to/hoge, but the permissions are not actually changed.
I'm looking for the correct answer by reading the documentation and repeating trial and error to find out what's wrong.

Rewrite the file → Save → Move to console → Run php file → (´・ω・`)

Honestly, it's painful to repeat this process over and over again, so if you can easily extract and test something like the example above, I think it's easier to do it from the command line.

 
That's it.

If you found this article helpful , please give it a like!
0
Loading...
0 votes, average: 0.00 / 10
881
X facebook Hatena Bookmark pocket
[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

The person who wrote this article

About the author

Yoichi Bandai

My main job is developing web APIs for social games, but I'm also fortunate to be able to do a lot of other work, including marketing.
Furthermore, my portrait rights in Beyond are treated as CC0 by him.