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; ?>
/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); ?>
Hello, World! Write to file
/path/to/file.txt.
getenv function. The following is an example:
<?php $home = getenv('HOME'); echo $home; ?>
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 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!