Sunday, February 23, 2014

Testing File Permission for file upload and database connectivity

On a freshly installed Linux server you need to test file permission and database connectivity.
Here are some scripts that can help you with that:

Test file permissions

This is simple form that uploads a file to server. In webroot folder create upload folder.
<!doctype html>
<html lang="us">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
echo exec('whoami');
echo "<hr/>";

$form = '<form action="'.$_SERVER['PHP_SELF'].'" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"> <input type="submit" name="submit" value="Send">
</form>';
if (isset($_POST['submit']) && $_POST['submit'] == 'Send'){
 if ($_FILES["file"]["error"] > 0)
   {
   echo "Error: " . $_FILES["file"]["error"] . "<br>";
   echo $form;
   }
 else
   {
   echo "Upload: " . $_FILES["file"]["name"] . "<br>";
   echo "Type: " . $_FILES["file"]["type"] . "<br>";
   echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
   move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
   echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
   echo $form;
   }
} else {
 echo $form;
}
?>

</body>
</html>

If something did not work you need to use chmod and chown commands to fix problem.

Testing database connection


file test_db_conn.php
<?php
$hostname = "localhost";
$user = "";
$user_password = "";
$database = "";

$mysqli = new MySQLi($hostname, $user, $user_password, $database);
if (mysqli_connect_errno()) {
 printf("Connect failed: %s\n", mysqli_connect_error());
 exit();
}

$query = "SELECT * FROM names";
$res = $mysqli->query($query);

if($res==FALSE) {
  die("<div style='background:red;border:dotted;padding:10px;'>Error Message: $mysqli->error <br> Error in: $query</div>");
}

while ( $row = $res->fetch_assoc() ){
echo "{$row['id']} {$row['name']}";
}

$res->close();
$mysqli->close();
?>

No comments:

Post a Comment