Running the Python script over PHP5

It took some time to get this working so I’m quite proud that it does actually work now. There were a couple of subtleties that needed ironing out and I want to share them for those trying to do something similar. Here’s the code and then I’ll note a few lines in detail after…

<html>
<head>
<title>A first go at web control...</title>
</head>
<body>
<?php
if ( isset( $_POST['angle'] ) )
{
#Pass the variables and remove any system characters
$angle=escapeshellcmd($_POST['angle']);
$servo=escapeshellcmd($_POST['servo']);
$output=system("/usr/bin/python2.5 /var/www/cgi-bin/controlsscii.py pos  $servo $angle");
}
?>
<form action="page1.php" method="POST">
Input area:<p>
Servo number (0-7 limited resolution, 8-15 full sweep):
<input type="text" name="servo"><p>
Value (0-180 degrees):
<input type="text" name="angle"><p>
<input type="SUBMIT" name="submit" value="Try it!">
</form>
</body>
</html>

So firstly I had an issue with PHP going from v4->v5. Before the change variables were passed from forms with method=”POST” directly into variables. Now one has to access the $_POST environmental variable. escapeshellcmd() is used to ensure arbitrary scripts can’t be run.

$angle=escapeshellcmd($_POST['angle']);

The main problem I came across was getting the paths correct to the call to python. The correct eventual line is:

$output=system("/usr/bin/python2.5 /var/www/cgi-bin/controlsscii.py pos  $servo $angle");

I initially had the full path to the script but not that of python itself. An exhaustive web search and eventual examination of the Apache error log helped me narrow down this and subsequent problems.

The final tweak I had to make was to the serial port file (/dev/ttyS0) – I had to set the correct permissions such that the script could access it.

Updated: The code wasn’t formatted well enough for my liking. Some of it may go out of bounds. I will work this out, I’m sure.

Advertisements

2 Responses to Running the Python script over PHP5

  1. […] The client sees the following when entering the servo control test page: […]

  2. I searched on google and I had a hard time located the right info….until I found your blog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: