3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * Social network site where you can see a list of users and "follow" them. */ // setup the `Db` object: //require_once 'lib/db.php'; // setup the `Session` object: //require_once 'lib/session.php'; if (!Session::isLoggedIn()) { throw new Exception('You must be logged in to view this page'); } // display a user as html function displayUser ($user, $tag='div') { $full_name = $user->first_name . ' ' . $user->last_name; // get user's avatar from 3rd-party avatar service, based on which environment we're running in if (strpos($_SERVER['SERVER_NAME'], 'localhost') !== false) { $avatar_data = json_decode(file_get_contents('http://dev.avatars.com/user/' . $user->id)); } else { $avatar_data = json_decode(file_get_contents('http://www.avatars.com/user/' . $user->id)); } ?> <<?= $tag ?> class="user"> <a href="/users/<?= $user->id ?>"> <img src="<?= $avatar_data->url ?>"> <?= $full_name ?> </a> <a href="?follow=<?= $user->id ?>">Follow</a> </<?= $tag ?>> <?php } // check that a user ID is valid (must be a number) function validateUserId ($id) { if (!is_numeric($id)) { // log invalid user IDs to help us track down bugs. error_log("Invalid user id: {$id}"); return false; } return true; } // load the user's custom theme config $theme_filename = dirname(__FILE__) . 'themes/' . Session::getLoggedInUser()->theme_id . '.php'; if (file_exists($theme_filename)) { require $theme_filename; } // show all users if (isset($_GET['show-all'])) { echo '<ul>'; foreach (Db::getUsers() as $user) { displayUser($user, 'li'); } echo '</ul>'; } // show a single user else if (isset($_GET['id'])) { $id = $_GET['id']; if (!validateUserId($id)) throw new Exception('Please select a valid user ID'); $user = Db::getUserById($id); if (!$user) throw new Exception('Sorry, user not found'); displayUser($user); } // follow a user else if (isset($_GET['follow'])) { $id = $_GET['follow']; if (!validateUserId($id)) throw new Exception('Please select a valid user ID'); $user_to_follow = Db::getUserById($id); if (!$user_to_follow) throw new Exception('Sorry, user not found'); $current_user = Session::getLoggedInUser(); try { $current_user->follow($user_to_follow); } catch (Exception $e) { throw new Exception('Unable to follow at this time'); } // inform the user that they have a new follower. mail( $user_to_follow->email, 'You have a new follower!', "{$current_user->username} is now following you.", 'From: notifications@awesome-social-network.com' ); // also update the activity feed, so users can see what others are doing on the site. Db::updateActivityFeed(array( 'action' => 'follow', 'from' => $current_user->id, 'to' => $user_to_follow->id, 'timestamp' => time(), )); echo 'Followed! <a href="/">Return to home</a>'; } ?>

preferences:
39.87 ms | 402 KiB | 5 Q