Home >Backend Development >PHP Tutorial >How to use PHP to perform script operations under Linux
How to use PHP to perform script operations under Linux
In Linux systems, PHP is a very commonly used server-side scripting language. It can interact with the operating system and perform some system-level operations, such as executing commands, reading and writing files, etc. This article will introduce how to use PHP to perform script operations under Linux and provide specific code examples.
1. Execute command operations
shell_exec
function to execute the commandshell_exec
The function can be executed System command and returns the output results. The following is a simple example:
<?php $output = shell_exec('ls -l'); echo $output; ?>
The above code executes the ls -l
command and assigns the output result to the variable $output
, and finally passes The echo
statement outputs the results.
exec
function to execute the command exec
function is similar to the shell_exec
function and can also Execute system commands, but it can return the last line of output of the command. The following is an example:
<?php exec('ls -l', $output); foreach ($output as $line) { echo $line . " "; } ?>
The above code also executes the ls -l
command, but stores the output results in the array $output# through the
exec function ##, and output line by line through the
foreach loop.
<?php $file = '/path/to/file.txt'; $content = file_get_contents($file); echo $content; ?>The above code will The content of the file
/path/to/file.txt is read into the variable
$content and output through the
echo statement.
<?php $file = '/path/to/file.txt'; $content = 'Hello, World!'; file_put_contents($file, $content); ?>The above code will string
Hello, World! Write to file
/path/to/file.txt.
getenv function. The following is an example:
<?php $home = getenv('HOME'); echo $home; ?>The above code obtains the system's
HOME environment variable and outputs it through the
echo statement.
<?php // 创建目录 $dir = '/path/to/new/directory'; mkdir($dir, 0777); // 复制文件 $source = '/path/to/source/file.txt'; $destination = '/path/to/destination/file.txt'; copy($source, $destination); // 删除文件 $file = '/path/to/file.txt'; unlink($file); ?>The above code demonstrates the operations of creating directories, copying files, and deleting files . SummaryThis article introduces how to use PHP to perform script operations under the Linux system, including executing commands, reading and writing files, and other operations. The above are some basic examples, you can expand and modify them according to your actual needs. Using PHP to perform script operations under Linux can help us better manage the server and improve work efficiency. Hope this article is helpful to you!
The above is the detailed content of How to use PHP to perform script operations under Linux. For more information, please follow other related articles on the PHP Chinese website!