Python and PHP Integration

Greetings Programmers !!!, in this tutorial we will see how to run Python scripts using PHP.

Python is a general-purpose language that is used for various purposes and PHP is another powerful scripting language that is mainly used in building dynamic and interactive web pages.


Before running any of the scripts, we need to install the XAMPP server offered by Apache Friends. After the installation process is prompted, the Apache module process has to be started. The following PHP and the Python files then have to be placed in the ‘C:\Program Files\XAMPP\htdocs’ directory. Next, open any browser and type ‘localhost/<phpFileName>.php’ and we can get the desired output.

Basic Usage

We will use some pre-defined methods in PHP to execute a python script.

Given below is the PHP code to run a Python script.

    $command = escapeshellcmd('python');
    $output = shell_exec($command);
    echo $output;

Here, we use the ‘escapeshellcmd()’ inbuilt method which escapes command line shell commands. Next, we use the ‘’shell_exec()” method to run the following command in the terminal.

Given below is the Python code which will be shown as output.

strHtml = """
         CodeSpeedy Technologies Python and PHP Integration
      <h1>CodeSpeedy Technologies</h1>
      This is an example for Python and PHP integration.

In this file, we write some basic HTML code having an h1 tag and a paragraph. The following executes only when we run the PHP file while running the XAMPP server.

XAMPP is an open-source web solution stack software that consists of some interpreters for running PHP and PERL scripts.

The output for the following scripts will be a web page displayed with ‘CodeSpeedy Technologies’ written in an ‘h1’ tag with some text on it.

Leave a Reply

Your email address will not be published. Required fields are marked *