Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Using the DDL provided, write a small PHP application that allows a user to type the title of a post in a form field and have it fetch the title and body of that post from the "posts" table.
- Key items:
- The solution must echo the typed field back to the user
- The file must work in PHP 5.2
- The DB configuration should be editable at the top of the file.
- The solution must protect against XSS, SQL Injection and CSRF attacks, but should allow for HTML in the returned content.
- Use any combination of procedural and OOP that you see fit
- Write your code sample below:
- */
- <?PHP
- $dbhost = 'localhost'; // Database Server
- $dbuser = 'root'; // Database User
- $dbpass = ''; // Database Password
- $dbname = 'test'; //Database Name
- mysql_connect($dbhost, $dbuser, $dbpass) or die("failed to connect to mysql: " . mysql_error());
- mysql_select_db($dbname) or die("failed to select db: " . mysql_error());
- if (!isset($_SESSION)) {
- session_start();
- }
- if (!isset($_SESSION['token'])) {
- $token = md5(uniqid(rand(), TRUE));
- $_SESSION['token'] = $token;
- }
- else
- {
- $token = $_SESSION['token'];
- }
- $message = NULL;
- $title = '';
- $content = '';
- $posts = array();
- if(isset($_POST['submit']) && $_POST['title'] != NULL ){
- if($_SESSION['token'] != $_POST['token']){
- die;
- }
- $title = mysql_real_escape_string($_POST['title']);
- $sql = 'SELECT id, title, content FROM `posts` WHERE title ="'. $title .'"';
- $results = dbQuery($sql);
- $i = 0;
- while( $row = mysql_fetch_array($results)) {
- $posts[$i]['title'] = $row['title'];
- $posts[$i]['content'] = $row['content'];
- ++$i;
- }
- }
- function dbQuery($sql)
- {
- $result = mysql_query($sql);
- if(!$result){
- throw new Exception(mysql_error()."\n"."Query: " . $sql);
- }
- return $result;
- }
- ?>
- <html>
- <body>
- <form action="<?PHP $_SERVER['PHP_SELF'] ?>" method="POST">
- <label for="title">Title to find:</label>
- <input type="text" id="title" name="title">
- <input type="hidden" name="token" value="<?php echo $token ?>">
- <input type="submit" value="Find" name="submit">
- </form>
- <hr>
- <?php if(!empty($posts)){ ?>
- <h2>Your search for <?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?> returned the following results</h2>
- <?php foreach($posts as $post){ ?>
- <h3><?php echo htmlspecialchars($post['title'], ENT_QUOTES, 'UTF-8'); ?></h3> <BR>
- <?php echo htmlspecialchars($post['content'], ENT_QUOTES, 'UTF-8'); ?>
- <?php } ?>
- <?php } ?>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement