PHP is not a script language that has attracted much attention, but this is a pity, because PHP has many ideals that make it the ideal choice to write a terminal application.
This series of articles will introduce how to use the Macrame library to write an interactive command line script. We will gradually complete a sample item. The script obtains the list of Mastodon user followers from beginning to end, and covers the following topics: obtain and verify user input, build interactive menu, handle command line parameters, security access files, set output text styles, and Run the function in the background when the animation loader is displayed to the user.
For more information about Macrame, visit the document site.
Example items
The project we will complete is a simple command line script that is used to return the list of followers of Mastodon users. Run the script as shown below:
In the run script operation
For anyone who wants to skip this step, the complete source code of this project is provided in the form of GIST.
Overview
In this section, how will we introduce:Install Macrame
- Create a blank script
- Read the command line parameters
- Create a dynamic menu
- Read a line of user input (optional verification)
- Set output text style
- Install Macrame
Create a script framework
composer require gbhorwood/macrameAfter installing Macrame, we can set up a basic "Hello World" script and use it as our starting model. Although technically, this framework is not necessary, but use it will make our script safer and more standardized. Let's take a look at the code:
Although there are not many code lines, many things happen here. Let's take a closer look.
#!/usr/bin/env php <?php require __DIR__ . '/vendor/autoload.php'; use Gbhorwood\Macrame\Macrame; // 实例化 Macrame 对象。 // 参数是 ps(1) 所见的脚本名称 $macrame = new Macrame("示例 Macrame 脚本"); // 强制仅在命令行上执行脚本时才运行脚本 if ($macrame->running()) { // 验证主机系统是否可以运行 Macrame 脚本。失败时退出 $macrame->preflight(); // 将文本输出到 STDOUT $macrame->text("Hello World")->write(); // 清洁退出 $macrame->exit(); }This line is "shebang". Basically, it tells our Linux operating system which interpreter to run this script. This allows us to run scripts without having to type PHP first. Shebang must be
the first line of the file, even before & lt;? PHP.
#!/usr/bin/env php
Here, we create a Macrame object that we will use it in the rest of the script. Very standard content. The only interesting part is the parameter. This is the name of the operating system that will give us the script. For example, if we run PS to display the running process list, our script will display this name.
This statement ensures that all the code in the block is executed only when the script is run on the command line.
composer require gbhorwood/macrame
When we write PHP for the command line, our control of the environment is not as much as web servers we have and manage. The preflicht () calls the local PHP environment. If it does not meet the minimum requirements, it will terminate the script and display the error message. The minimum requirements are:
- PHP 7.4
- POSIX extension
- MBSTRING Extension
Although Macrame runs on PHP 7.4 and 8.0, because PHP has changed in 8.1, The symbol string may not be aligned correctly in the output.
This will exit the script cleanly and return the success code of 0. In addition, any temporary file created during the execution will be automatically deleted. It is best to use the exit () function of the Macrame instead of the DIE () of PHP;#!/usr/bin/env php <?php require __DIR__ . '/vendor/autoload.php'; use Gbhorwood\Macrame\Macrame; // 实例化 Macrame 对象。 // 参数是 ps(1) 所见的脚本名称 $macrame = new Macrame("示例 Macrame 脚本"); // 强制仅在命令行上执行脚本时才运行脚本 if ($macrame->running()) { // 验证主机系统是否可以运行 Macrame 脚本。失败时退出 $macrame->preflight(); // 将文本输出到 STDOUT $macrame->text("Hello World")->write(); // 清洁退出 $macrame->exit(); }
Run hello world
After writing the basic "Hello World" script, we can set its permissions to allow execution and run it on the command line.
Read the parameters
#!/usr/bin/env phpMacrame provides a set of tools for analysis and reading command line parameters. Let's start with some simple things: Get the version number when using the following command to call the script:
For this situation, we only need to check whether these parameters exist.
$macrame = new Macrame("示例 Macrame 脚本");We can achieve this purpose by calling the ARGS () method on the Macrame object. This method returns an object that contains all scripts and we can check many methods. To test whether the parameters exist, we can use the Exist () method, as shown below:
Exist () method return to Boolean.
if ($macrame->running())
? Macrame calls are designed to perform chain calls.
The command line parameters can also be used to assign a value for variables. For example, to set the user name value, we may hope that users can call the script like this:
To get the value of this parameter in our script, we can use the first () method provided by ARGS (), as shown below:
$macrame->preflight();
As the name suggests, the first () method returns the
first$macrame->exit();value of the parameter. If we call the script like this:
Then first () will return the "firstuser" value. If we want the last value, we can call Last (). If we want
allchmod 755 ./examplescript.php ./examplescript.phpas an array, we will use all ().
Putting all these together, our script looks like this now:
The full method list of handling command line parameters is introduced in the Macrame parameter document.
./examplescript.php --version # 或 ./examplescript.php -vCreate a dynamic menu
We also hope to allow users to use our script in an interactive manner. If they do not pass the parameters on the command line, we will prompt them to enter the data. For MASTODON examples, we will use the menu.
Macrame menu is dynamic; users can use the arrow key to move up and down the list, and then press the
key to select.
Let's write a function that displays the menu to the user and return the value of the selected value: The core function here is to call the following: We provide a string array as the menu option, and a optional menu title text for Menu ()-& GT; Internet (), and the menu will automatically display it to users. The user's choice will be returned as a string. By adding to Erase () to our chain, you can also choose to erase the menu from the screen after the user makes a choice. This method is optional, but it can indeed be tidy. After obtaining the menu function, we can modify the way to get the Mastodon instance. We will try to read it from the command line parameters. If no value is passed, the menuinstance () function is called. By default, Macrame uses the default style and color of the terminal to display the menu, and the project that highlights the displayed display is set to reverse display. If necessary, we can change this setting by adding some additional functions to our chain. For example, if we want to highlight the displayed items displayed as a thick red text, we can write this: The menu document pages a complete overview of all methods that can be used to customize the color, style and alignment method of custom menu. Next, we will modify the way to obtain the username so that it will also accept interactive input. In this case, we will use input ()-& gt; readline () to read the user input text string. The following is the function:
In the example of how to read a line of user text, we have seen a large number of codes used to set a prompt text style. Let's study it in detail. Macrame allows the use of ANSI code to set the terminal text output style, which allows us to apply the style and color of the thick body and oblique body to our text. We can perform this operation in our script through two ways. There are some ways, such as style () and colour () (or color ()), or we can use the basic text mark system. Let's first look at the method. Here, we use Macrame's Text () method to create a "text" object, then apply style and color, and finally use get () to return it as a string. Please note that style and color methods are applied to all texts in the string. If we want to mix style and color text with pure text, we will have to create many sub -string and connect them together. This may be very troublesome, especially when dealing with a large number of texts. or, we can use Macrame's markup system to simplify the text style settings. This is an example:
marks will be thickened (of course). The document lists the complete list of all the marks. This means that nested marks will not work as we expect. For example, in this example, the first mark will be closed mark:
composer require gbhorwood/macrame
#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';
use Gbhorwood\Macrame\Macrame;
// 实例化 Macrame 对象。
// 参数是 ps(1) 所见的脚本名称
$macrame = new Macrame("示例 Macrame 脚本");
// 强制仅在命令行上执行脚本时才运行脚本
if ($macrame->running()) {
// 验证主机系统是否可以运行 Macrame 脚本。失败时退出
$macrame->preflight();
// 将文本输出到 STDOUT
$macrame->text("Hello World")->write();
// 清洁退出
$macrame->exit();
}
#!/usr/bin/env php
Supplementary description of the menu style
$macrame = new Macrame("示例 Macrame 脚本");
Read a line of users to enter
if ($macrame->running())
The last line of this function is where we inquire with users. Readline () method accepts optional $ Prompt parameters; the text we show to users tells them what they should enter. The return value is the string entered by the user.
Users will make mistakes. This is why input verification is important. $macrame->preflight();
Here, we apply two verification tests: the text must be four or more characters, and cannot include the "@" symbol. For these two verification methods, the second parameter is the error message we will display to the user if the verification fails.
If our user enters sensitive data, such as a password, we may not want to show their keys back to the terminal to avoid being seen by the spymen. $macrame->exit();
Readpassword () Each button read will be revealed in the form of a star number.
Set text style
composer require gbhorwood/macrame
#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';
use Gbhorwood\Macrame\Macrame;
// 实例化 Macrame 对象。
// 参数是 ps(1) 所见的脚本名称
$macrame = new Macrame("示例 Macrame 脚本");
// 强制仅在命令行上执行脚本时才运行脚本
if ($macrame->running()) {
// 验证主机系统是否可以运行 Macrame 脚本。失败时退出
$macrame->preflight();
// 将文本输出到 STDOUT
$macrame->text("Hello World")->write();
// 清洁退出
$macrame->exit();
}
The text between and #!/usr/bin/env php
So far, our example script is shown below:
$macrame = new Macrame("示例 Macrame 脚本");
So far, we have introduced reading command line parameters, obtaining user input from menu and text, and making some basic text styles for the output. In the next article, we will introduce:
? This article was originally published in Grant Horwood Technology Blog
The above is the detailed content of php: writing command-line applications with macrame. pt 1. For more information, please follow other related articles on the PHP Chinese website!

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
