Monday, December 10, 2007

A Super Tiny PHP SQL Shell

I needed to run some adhoc queries against a MySQL database. I didn't have shell access, so running the mysql command was out, and I didn't have access to the standard phpMyAdmin tool. Instead, I rigged something up myself. Here's what I came up with - it's tiny, but takes any SQL I throw at it, and renders it reasonably well. Surprisingly, it even works well for commands like explain account or show tables.

WARNING: this code is really dangerous. If anyone ever found out it was running on your server, they could run any SQL command they wanted to against your database. If you don't know why this is a bad thing, don't use this script. Ever.

mysql_connect(<DB_HOST>, <DB_USER>, <DB_PASSWORD>);

$sql = $_REQUEST['<some secret parameter name>'];
$results = mysql_query($sql);
if($results) {
  echo "<pre>";
  while($row = mysql_fetch_assoc($results)) {
    echo "\n";
  echo "</pre>";
} else {
  echo "Failed to execute: [$sql]: " . mysql_error();

This script, combined with my URL testing hack made for a remarkably usable solution. Click a button on my browser link bar, enter a query, get the results. Who could ask for more?

No comments:

Post a Comment