Search code examples
phppython-3.xwebsockethttpserver

How to compile and send result php code in python http server?


I am wriritng HTTP server with python socket. I have a web page that contain PHP code like this

<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>
</html>

which a want to send to client, when i send it normally the PHP file will not be compiled and only send like a string and nothing happen in browser. if i want to cmpile and send php code what should i do? i send file like this:

    with open(filename[1:]) as f:
        outputdata = f.read()
    self.request.send(bytes('\nHTTP/1.1 200 OK\n\n','utf-8'))
    for i in range(0, len(outputdata)):
        self.request.send(bytes(outputdata[i],'utf-8'))
    self.request.close()

Solution

  • Your script is working as "intended". Python will not magically parse and execute PHP code. You need a PHP interpreter for that.

    You could of course write one in your python server if so inclined, but I would rather recommend you to take a look at either Python web development (if you want to roll your own server for educational purposes you may want to use an existing templating system like Jinja), or PHP development.