Friday, July 5, 2013

php 101 boilerplate

I grew up on Perl, especially for quick and dirty web things, and in general PHP didn't differentiate itself enough for me to switch. However, my team at work seems more comfortable with PHP, and actually PHP often has a lot of useful libraries baked-in that would me more of a pain to install on Perl.

But I always have to look up a ton of little things in PHP, so here is a trivial file editor in PHP that will show me some basic stuff like reading and writing a file, loading POST'd data, escaping HTML characters, catching errors, comparing strings, etc -- it even has a S00PER SEKRIT password function.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>admin</title>
</head>
<body>
<?php
$secretpassword = "test";
$pass = $_POST["pass"];
$contents = $_POST["contents"];
set_error_handler("customError");

if($pass != ""){
        if($pass == $secretpassword){
                if(file_put_contents("file.txt",$contents) !== FALSE){
                        echo "Wrote File";
                }
        } else {
                echo "Incorrect Password";
        }
}
$contents = htmlspecialchars(file_get_contents("file.txt"));

function customError($errno, $errstr) {
  echo "<b>Error:</b> [$errno] $errstr";
}  



?>

<form method="POST" action="admin.php">
<textarea ROWS="8" COLS="80" name="contents"><?php echo $contents ?></textarea>
<br/>
Password: <input type="password" name="pass"><br/>
<input type="submit" value="update file">
</body>
</html>

Ain't rocket science, but might save me a few minutes in the future.

No comments:

Post a Comment