3.2. Using Operating System Commands

When you need to interact with your operating system, it's always best to use the PHP functions that are provided for this purpose. Using PHP functions is more secure than executing an operating system command directly. However, occasionally PHP doesn't provide a function to perform the task you need. In such cases, you can use PHP features that allow you to execute an operating system command.

In this section, we assume that you know the format and use of the system commands for your operating system. Describing operating system commands is outside the scope of this book. If you need to run an operating system command from your PHP script, this section shows you how.

PHP allows you to use system commands or run programs in other languages by using any of the following methods:

  • backticks: PHP executes the system command that is between two backticks (`) and displays the result.

  • system function: This function executes a system command, displays the output, and returns the last line of the output.

  • exec function: This function executes a system command, stores the output in an array, and returns the last line of the output.

  • passthru function: This function executes a system command and displays the output.

You can execute any command that you can type into the system prompt. The command is executed exactly as is. You can execute simple commands: ls or dir, rename or mv, rm or del. If your operating system allows you to pipe or redirect output, you ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.