PHP Tutorial

Step 11

PHP Tutorial

In this tutorial we will create a simple twitter copycat. In step 11 we will enable our users to tweet.

Step 11

1. Let’s start by adding a form to our list.tpl. This form should only be available if the user is logged in. Before the message divs, add:

{if isset($USERNAME)}
<section id="tweet_form">
  <form action="{$BASE_URL}actions/tweets/tweet.php" method="post">
    <textarea name="tweet" placeholder="Say something"></textarea>
    <input type="submit" value="Tweet">
  </form>
</section>
{/if}

2. Let’s add some style to this form:

#tweet_form {
  background-color: #E8F4FB;
  padding: 5px;
}

#tweet_form form {
  width: 100%;
  display: flex;
}

#tweet_form textarea{
  border: none;
  flex-grow: 1;
  margin: 1em;
  padding: 1em;
}

#tweet_form input {
  background-color: #1DA1F2;
  color: white;
  border: none;
  margin: 1em;
  padding: 1em;
  border-radius: 1em;
}

3. The actions/tweets/tweet.php file should start by verifying if the user is logged in and the tweet has any data:

<?php
  include_once('../../config/init.php');
  include_once($BASE_DIR .'database/tweets.php');  

  if (!$_SESSION['username']) {
    $_SESSION['error_messages'][] = 'Not allowed!';
    header("Location: $BASE_URL");
    exit;
  }

  if (!$_POST['tweet']) {
    $_SESSION['error_messages'][] = 'You didn\'t say anything';
    header("Location: " . $_SERVER['HTTP_REFERER']);
    exit;
  }

  $username = $_SESSION['username'];
  $tweet = $_POST['tweet'];  

4. We should then try to create the tweet and veryfing if any error ocurred:

  try {
    createTweet($username, $tweet);
  } catch (PDOException $e) {
    $_SESSION['error_messages'][] = 'Error creating tweet';

    $_SESSION['form_values'] = $_POST;
    header("Location: " . $_SERVER['HTTP_REFERER']);
    exit;
  }
  $_SESSION['success_messages'][] = 'Tweet sent';  
  header("Location: " . $_SERVER['HTTP_REFERER']);
?>

Don’t forget to sanitize the tweet:

createTweet($username, strip_tags($tweet));

5. The createTweet function, in database/tweets.php, should look like this:

function createTweet($username, $tweet) {
  global $conn;
  $stmt = $conn->prepare("INSERT INTO tweets
                          VALUES (DEFAULT, CURRENT_TIMESTAMP, ?, ?)");
  $stmt->execute(array($username, $tweet));
}

You can find the complete code after step 11 here . In step 12 we will add jQuery magic to our site.