The Finale!
After a week of working on the project, I decided to clean up a lot of it, re-factor where necessary, add a lot of neat features, and here they are explained. The entire sha-bang!
folder structure
|-- admin
| |-- helpers
| | |-- footer.php
| | |-- header.php
| |-- js
| | |-- main.js
| |-- index.php
| |-- credentials.php
| |-- usermanagement.php
|-- helpers
| |-- email_templates
| | |-- etc...
| |-- fixtures.php
| |-- flashes.php
| |-- footer.php
| |-- functions.php
| |-- header.php
| |-- search.php
| |-- zip_distance_assistant.php
| |-- zip_radius_assistant.php
|-- js
| |-main.js
|-- .htaccess
|-- about.php
|-- credentials
|-- index.php
|-- profile.php
Now, let’s go through just about every file and see why it’s there and what it does. We won’t touch the email template as much, simply because that’s more of a marketing thing. But the only thing we need to put in it is the link to verify the email address.
The Admin
We could easily refactor some of these pages to combine functionality
admin/helpers/footer.php
1 2 | </body> </html> |
Easy does it. Same old footer.
admin/helpers/header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Our Admin</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="/admin/js/main.js"></script> </head> <body> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/flashes.php'); ?> <ul> <li><a href="/admin/">Dashboard</a></li> <li><a href="/admin/usermanagement">User Managememt</a></li> <?php if (isAdminLoggedIn()) { ?> <li><a href="/admin/logout">Logout</a></li> <?php } ?> </ul> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/search.php'); renderSearchForm(); ?> |
So, we added jquery, some JavaScript, and included a search for for the profiles. One module under helpers search.php and the render function. We’ll see that later.
admin/js/main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | $(document).ready(function() { performSearch = function () { var gender = $('#gender').val(); var ethnicity = $('#ethnicity').val(); var profile = $('#profile').val(); var min_age = $('#min_age').val(); var max_age = $('#max_age').val(); var min_height = $('#min_height').val(); var max_height = $('#max_height').val(); var min_weight = $('#min_weight').val(); var max_weight = $('#max_weight').val(); var distance = $('#distance').val(); var zipcode = $('#zipcode').val(); if (gender == "*") {gender = ''} else {gender = '/gender-'+gender;} if (ethnicity == "*") {ethnicity = ''} else {ethnicity = '/ethnicity-'+ethnicity;} if (profile == "*") {profile = ''} else {profile = '/profile-'+profile;} if (min_age == "*" && max_age == "*") { age = ''; } else { age = '/age-'+min_age+'-'+max_age; } if (min_height == "*" && max_height == "*") { height = ''; } else { height = '/height-'+min_height+'-'+max_height; } if (min_weight == "*" && max_weight == "*") { weight = ''; } else { weight = '/weight-'+min_weight+'-'+max_weight; } if (distance == "*" && zipcode == "") { distance = ''; } else { distance = '/distance-'+distance+'-'+zipcode; } var urlOut = '/admin/usermanagement/list/page-1'+gender+ethnicity+profile+age+height+weight+distance; $('#searchForm').attr("action",urlOut); $('#searchForm').submit(); } }); |
This is functionality added for our search form. There’s some customization to it, such as the submit url of the form. Notice how we make use of jQuery. Include this if you want your search form to work. This way you can easier find users in admin. Of course, we could also add more fields, such as username, first name, last name, email, etc… That will probably be better for admin searches.
admin/credentials.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php'); $link = connect(); if ( isset($_GET['action']) ) { switch ($_GET['action']) { case "login": loginAction(); break; case "logout": logoutAction(); break; default: showLoginFormAction(); } } else { showLoginFormAction(); } close($link); function logoutAction() { switch (isAdminLoggedIn()) { case true: logoutAdminAction(); break; case false: showLogoutSuccessAction(); break; } } function logoutAdminAction () { // kill session, and later, kill cookies. $_SESSION['admin_username'] == null; session_destroy(); header('Location: /admin/logout.php'); } function showLogoutSuccessAction() { require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/header.php'); ?>You have been logged out.<?php require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/footer.php'); } function showLoginFormAction () { require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/header.php'); ?> <form action="?action=login" method="post"> <label for="email">Username</label> <input type="text" name="username" value="<?php if (isset($_POST['username'])) { echo $_POST['username']; } ?>"> <label for="email">Password</label> <input type="password" name="password" value=""> <input type="submit" value="Login"> </form> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/footer.php'); } function loginAction () { $_SESSION['error'] = null; // clean up against SQL injection. $username = $_POST['username']; $password = $_POST['password']; verifyAdminLogin($username, $password); if (is_null($_SESSION['error'])) { $_SESSION['admin_username'] = $username; $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "Welcome back, $username!"; header('Location: /admin'); } else { // this shows our submit form. showLoginFormAction(); } } ?> |
Used to be our login and logout page for admin. Now, combined, takes care of all of our credentials for loggin in and out.
admin/index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php'); if ( !(isset($_SESSION['admin_username']) && $_SESSION['admin_username'] != '') ) { // checking to see if admin_username session variable is either set or holds a value. // Notice the ! at the beginning. We're checking to see if the user is NOT logged in. // If the user is not logged in, we need to redirect them. header('location: /admin/login'); } $link = connect(); viewAction(); close($link); function viewAction() { ?> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/header.php'); ?> <p>Dashboard</p> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/footer.php'); } ?> |
BAM! Simple index page. Include our main functions.php file, check to see if you’re not logged in, connect, render the view, and close the connection. Done!
admin/usermanagement.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php'); if ( !(isset($_SESSION['admin_username']) && $_SESSION['admin_username'] != '') ) { // checking to see if admin_username session variable is either set or holds a value. // Notice the ! at the beginning. We're checking to see if the user is NOT logged in. // If the user is not logged in, we need to redirect them. header('location: /admin/login'); } $link = connect(); if ( isset($_GET['action']) ) { switch ($_GET['action']) { case "view": viewAction(); break; case "edit": editAction(); break; case "update": updateAction(); break; case "delete": deleteAction(); break; case "add": addAction(); break; default: listAction(); } } else { listAction(); } close($link); function listAction () { require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/header.php'); $search_engine_results = getProfileSearchSQL(); $current_page = getSearchUrlParam('page'); if (is_null($current_page)) {$current_page = 1;} $params = array( 'current_page' => $current_page, 'limit' => 12 ); $users = getProfiles($search_engine_results, $params); drawProfilePagination($search_engine_results, '/admin/usermanagement/list/'); ?> <p>Users</p> <table> <thead> <tr> <th>ID</th> <th>username</th> <th>First Name</th> <th>Last Name</th> <th>E-Mail Address</th> </tr> </thead> <tbody> <?php while ($user = mysql_fetch_array($users) ) { ?> <tr> <td><?php echo $user['id']; ?></td> <td><a href="/admin/usermanagement/view/<?php echo $user['username']; ?>"><?php echo $user['username']; ?></a></td> <td><?php echo $user['fname']; ?></td> <td><?php echo $user['lname']; ?></td> <td><?php echo $user['email']; ?></td> <td><a href="javascript:if (confirm('Are you sure you want to remove this user?')) {window.location='/admin/usermanagement/delete/<?php echo $user['username']; ?>';} void(0);">[X] Delete</a></td> </tr> <?php } ?> </tbody> </table> <!-- The NEW user form --> <form action="/admin/usermanagement/add" method="post"> <label for="fname">First Name</label> <input type="text" name="fname" value="<?php if (isset($_POST['fname'])) { echo $_POST['fname']; } ?>"> <label for="lname">Last Name</label> <input type="text" name="lname" value="<?php if (isset($_POST['lname'])) { echo $_POST['lname']; } ?>"> <label for="email">Username</label> <input type="text" name="username" value="<?php if (isset($_POST['username'])) { echo $_POST['username']; } ?>"> <label for="email">Password</label> <input type="password" name="password" value=""> <label for="email">E-Mail Address</label> <input type="text" name="email" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>"> <input type="submit" value="Add"> </form> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/footer.php'); } function viewAction () { $user = getProfile($_GET['username']); require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/header.php'); if ($user) { ?> <a href="/admin/usermanagement">« Back to users</a> <table> <tr> <td><?php echo $user['id']; ?></td> <td><?php echo $user['username']; ?></td> <td><?php echo $user['fname']; ?></td> <td><?php echo $user['lname']; ?></td> <td><?php echo $user['email']; ?></td> </tr> </table> <a href="/admin/usermanagement/edit/<?php echo $user['username']; ?>">Edit User</a> <?php } require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/footer.php'); } function editAction () { $user = getProfile($_GET['username']); require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/header.php'); if ($user) { ?> <form action="/admin/usermanagement/update/<?php echo $user['username']; ?>" method="post"> <label for="fname">First Name</label> <input type="text" name="fname" value="<?php echo $user['fname']; ?>"> <label for="lname">Last Name</label> <input type="text" name="lname" value="<?php echo $user['lname']; ?>"> <label for="email">E-Mail Address</label> <input type="text" name="email" value="<?php echo $user['email']; ?>"> <input type="submit" value="Update"> </form> <a href="/admin/usermanagement/view/<?php echo $user['username']; ?>">Cancel</a> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/admin/helpers/footer.php'); } } function addAction () { $_SESSION['error'] = null; // clean up against SQL injection. $username = $_POST['username']; $password = $_POST['password']; $secretPw = md5($password); $email = $_POST['email']; $fname = $_POST['fname']; $lname = $_POST['lname']; verifyUsername($username); verifyName ($fname); verifyName ($lname); verifyPassword($password); verifyEmail ($username, $email); if (is_null($_SESSION['error'])) { $sql = "INSERT INTO profiles ( `username`,`fname`,`lname`,`password`,`email` ) VALUES ( '".$username."','".$fname."','".$lname."','".$secretPw."','".$email."' )"; mysql_query($sql); $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "User added!"; header('Location: /admin/usermanagement'); } else { // this shows our submit form. listAction(); } } function updateAction () { $username = $_GET['username']; $email = $_POST['email']; $fname = $_POST['fname']; $lname = $_POST['lname']; verifyEmail($username,$email); if (is_null($_SESSION['error'])) { $sql = "UPDATE profiles SET `fname` = '".$_POST['fname']."', `lname` = '".$_POST['lname']."', `email` = '".$_POST['email']."' WHERE username = '".$username."'"; mysql_query($sql); $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "User $username updated!"; header('Location: /admin/usermanagement/view/'.$username); } editAction(); } function deleteAction () { $username = $_GET['username']; $sql = "DELETE FROM profiles WHERE username = '".$username."'"; mysql_query($sql); $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "User $username removed!"; header('Location: /admin/usermanagement'); } ?> |
The main user management module. viewing, editing, updating, deleting, adding, and listing the end users can be taken care of from here. I didn’t add all of the fields to be editable, but you get the idea. Just copy paste the other fields you want to be editable, and call it a day.
The Font End
A similar structure can be found here. You can also see some of the common functions also used in the admin section. Let’s see the helper files that helped us to already build the admin section.
helpers/fixtures.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | <?php if (isset($_GET['action'])) { $count = 20; if (isset($_GET['count']) && is_numeric($_GET['count']) && $_GET['count'] < 150 && $_GET['count'] > 1) { $count = $_GET['count']; } switch ($_GET['action']) { case "runfixtures": runFixtures($count); break; default: showDefault(); } } else { showDefault(); } function showDefault() { ?> <form method="get" action="?action=runfixtures"> <input type="hidden" name="action" value="runfixtures"> <input type="text" name="count" value=""> <input type="submit" value="Run Fixtures"> </form> <?php } function runFixtures($count = 150) { ini_set('max_execution_time', ($count * 2)); require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php'); require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/search.php'); connect(); $sql = "CREATE DATABASE IF NOT EXISTS `my_website`"; $res = mysql_query($sql); var_dump($res); $sql = "DROP TABLE IF EXISTS `admin`"; $res = mysql_query($sql); var_dump($res); $sql = "CREATE TABLE `admin` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(20) COLLATE utf8_bin NOT NULL, `password` varchar(50) COLLATE utf8_bin NOT NULL, `email` varchar(100) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`,`username`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;"; $res = mysql_query($sql); var_dump($res); /*Data for the table `admin` */ $sql = "insert into `admin`(`id`,`username`,`password`,`email`) values (1,'administrator',md5('password123'),'[email protected]');"; $res = mysql_query($sql); var_dump($res); /*Table structure for table `profiles` */ $sql = "DROP TABLE IF EXISTS `profiles`;"; $res = mysql_query($sql); var_dump($res); $sql = "CREATE TABLE `profiles` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(40) COLLATE utf8_bin NOT NULL, `password` varchar(100) COLLATE utf8_bin NOT NULL, `fname` varchar(100) COLLATE utf8_bin NOT NULL, `lname` varchar(100) COLLATE utf8_bin NOT NULL, `active` tinyint(1) NOT NULL DEFAULT '1', `emailverified` tinyint(1) NOT NULL DEFAULT '0', `verifycode` varchar(100) COLLATE utf8_bin NOT NULL, `email` varchar(255) COLLATE utf8_bin NOT NULL, `profile` enum('Talent','Producer','Makeup Artist','Photographer') COLLATE utf8_bin NOT NULL, `gender` enum('Female','Male') COLLATE utf8_bin NOT NULL, `ethnicity` enum('White','Black','Hispanic','Asian','Middle Eastern','Other') COLLATE utf8_bin NOT NULL, `height` int(11) unsigned NOT NULL DEFAULT '0', `weight` int(11) unsigned NOT NULL DEFAULT '0', `birthdate` datetime NOT NULL, `zipcode` varchar(10) COLLATE utf8_bin NOT NULL, `city` varchar(100) COLLATE utf8_bin NOT NULL, `county` varchar(100) COLLATE utf8_bin NOT NULL DEFAULT '', `state` varchar(10) COLLATE utf8_bin NOT NULL, `country` varchar(100) COLLATE utf8_bin NOT NULL, `latitude` FLOAT NOT NULL, `longitude` FLOAT NOT NULL, `created` int(11) unsigned NOT NULL DEFAULT '0', `updated` int(11) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;"; $res = mysql_query($sql); var_dump($res); /*Data for the table `profiles` */ $created = strtotime("now"); $updated = strtotime("now"); $myzip = "44102"; $zip_obj = verifyZipCode($myzip); if ($zip_obj !== false) { $latitude = $zip_obj->latLng->lat; $longitude = $zip_obj->latLng->lng; $city = $zip_obj->adminArea5; $county = $zip_obj->adminArea4; $state = $zip_obj->adminArea3; $country = $zip_obj->adminArea1; $sql = "insert into `profiles`( `username`,`password`,`fname`,`lname`,`active`,`emailverified`,`verifycode`,`email`,`profile`,`gender`,`ethnicity`,`height`,`weight`,`birthdate`,`city`,`state`,`country`,`zipcode`,`latitude`,`longitude`,`created`,`updated` ) values ( 'gbutiri',md5('password123'),'George','Butiri',1,1,'".md5(uniqid())."','[email protected]','Producer','Male','White',".rand(60,84).",".(intval(rand(120,300) / 5)*5).",'1978-04-04','".$city."','".$state."','".$country."','".$myzip."',".$latitude.",".$longitude.",".$created.",".$updated.");"; $res = mysql_query($sql); } for ($iUser = 1; $iUser <= $count; $iUser++) { $created = strtotime("now"); $updated = strtotime("now"); $gender = array("Male","Female"); $ethnicity = array( "White", "Black", "Hispanic", "Asian", "Middle Eastern", "Other" ); $profile = array( "Producer", "Talent", "Photographer", "Makeup Artist" ); $birthdate = date('Y-m-d', rand(strtotime('1900-01-01'), strtotime('1993-01-01'))); $zip_obj = findZipCode(); $zipcode = $zip_obj->postalCode; if ($zip_obj !== false) { $latitude = $zip_obj->latLng->lat; $longitude = $zip_obj->latLng->lng; $city = $zip_obj->adminArea5; $county = $zip_obj->adminArea4; $state = $zip_obj->adminArea3; $country = $zip_obj->adminArea1; $sql = "insert into `profiles`( `username`,`password`,`fname`,`lname`,`active`,`emailverified`,`verifycode`,`email`,`profile`,`gender`,`ethnicity`,`height`,`weight`,`birthdate`,`city`,`state`,`country`,`zipcode`,`latitude`,`longitude`,`created`,`updated` ) values ( 'username".$iUser."',md5('password123'),'Name".$iUser."','Lastname".$iUser."',1,1,'".md5(uniqid())."','user".$iUser."@actingshowcase.com','".$profile[rand(0,count($profile)-1)]."','".$gender[rand(0,count($gender)-1)]."','".$ethnicity[rand(0,count($ethnicity)-1)]."',".rand(60,84).",".(intval(rand(120,300) / 5)*5).",'".$birthdate."','".$city."','".$state."','".$country."','".$zipcode."',".$latitude.",".$longitude.",".$created.",".$updated.");"; $res = mysql_query($sql); echo '<div>'.number_format(($iUser/$count)*100,2).'%</div>'; echo '<div style="display:none;">'; var_dump($sql); echo '</div>'; } } showDefault(); } function findZipCode() { $zipcode = rand(10000,99999); //var_dump($zipcode); $zip_obj = verifyZipCode($zipcode); if ($zip_obj === false) { return findZipCode(); } else { return $zip_obj; } } ?> |
This is an awesome idea to help us populate the database with existing values. It also creates the entire database from scratch if it doesn’t exist. Let’s quickly run through it.
- Router controller at the top to decide what part of the module to run.
- in case no params are passed in, show the default rendered screen.
- upon running the script, we set a max execution timeout about 2 seconds per user since we have to do a zipcode check that involved mapquest’s geolocation API.
- The rest is simply database creation and filling in data.
- With one exception of the
findZipCode()function which uses the commonfunctions.phpsearch function to find a valid zip code.
helpers/flashes.php
1 2 3 4 5 6 7 8 9 10 11 | <?php if (isset($_SESSION['error']) && !is_null($_SESSION['error'])) { ?> <div style="border: 1px solid #900; background: #faa; border-radius:5px;display:block;padding:5px 10px;"> <?php var_dump( $_SESSION['error'] ); ?> </div> <?php } ?> <?php if (isset($_SESSION['notice']) && !is_null($_SESSION['notice'])) { ?> <div style="border: 1px solid #090; background: #afa; border-radius:5px;display:block;padding:5px 10px;"> <?php var_dump( $_SESSION['notice'] ); ?> </div> <?php } ?> |
The flash messages you get in the header every time you do something like update, delete, login, etc. These are driven by the $_SESSION['error'] and $_SESSION['notice'] variables. If you set these, they will show up one time on the following page request only.
helpers/footer.php
1 2 3 4 5 6 7 | </div><!-- class page_content --> </div><!-- class body --> <div class="footer"> </div> </body> </html> |
The typical footer file with some declared CSS classes for later use.
helpers/functions.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | <?php session_start(); // FLHASHERS ---------------------------------> if (isset($_SESSION['error_count'])) { unset($_SESSION['error_count']); } else { $_SESSION['error'] = null; } if (isset($_SESSION['notice_count'])) { unset($_SESSION['notice_count']); } else { $_SESSION['notice'] = null; } // <--------------------------------- FLHASHERS // DATABASE ---------------------------------> function connect() { $link = mysql_connect('localhost','root',''); mysql_select_db('my_website'); return $link; } function close($link) { mysql_close($link); } // <--------------------------------- DATABASE // DATA MODELS ---------------------------------> function getProfile ($username) { $sql = "SELECT * FROM profiles WHERE active = 1 AND username = '".$username."'"; $res = mysql_query($sql); $profile = mysql_fetch_assoc($res); return $profile; } // <--------------------------------- DATA MODELS // Common Functions ---------------------------------> function cleanUp($valueIn) { $valueOut = htmlentities($valueIn); $valueOut = stripslashes($valueOut); return $valueOut; } function getEnumVals($table,$column) { $sql = "SELECT REPLACE(COLUMN_TYPE,'enum(','') AS enumVals FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_website' AND TABLE_NAME = '".$table."' AND DATA_TYPE = 'enum' AND COLUMN_NAME = '".$column."';"; //var_dump($sql); //exit(0); $res = mysql_query($sql); $row = mysql_fetch_assoc($res); $enumVals = substr($row['enumVals'],1,strlen($row['enumVals'])-3); $enumVals = explode("','",$enumVals); return $enumVals; //str_replace($row['enumVals'] } // <--------------------------------- Common Functions // LOGGED IN CHECKS ---------------------------------> function isLoggedIn() { return (isset($_SESSION['username']) && $_SESSION['username'] != ''); } function isAdminLoggedIn() { return (isset($_SESSION['admin_username']) && $_SESSION['admin_username'] != ''); } function isLoggedInUser($username) { if (isLoggedIn()) { if (strtolower($username) === strtolower($_SESSION['username'])) { return true; } else { return false; } } else { return false; } } // <--------------------------------- LOGGED IN CHECKS // Form Validations ---------------------------------> function verifyAdminLogin($username, $password) { verifyPassword($password); if (validateUsername ($username) && is_null($_SESSION['error']) ) { $sql = "SELECT COUNT(*) AS usercount FROM admin WHERE username LIKE '".$username."' AND password = md5('".$password."')"; $res = mysql_query($sql); $row = mysql_fetch_assoc($res); if (intval($row['usercount']) != 1) { $_SESSION['error'][] = "Incorrect login. Please try again!"; } } } function verifyDate ($year,$month,$day) { $year_diff = date("Y") - $year; if ($year_diff < 18) {$_SESSION['error'][] = "Must be 18 to join!";} if ($year_diff > 18) { /* Do nothing */ } if ($year_diff == 18) { $month_diff = date("n") - $month; if ($month_diff<0) {$_SESSION['error'][] = "Must be 18 to join!";} if ($month_diff>0) { /* Do nothing */ } if ($month_diff == 0) { $day_diff = date("j") - $day; if ($day_diff < -1) { $_SESSION['error'][] = "Must be 18 to join!"; } else { /* Do nothing */ } } } } function verifyLogin($username, $password) { verifyPassword($password); if (validateUsername ($username) && is_null($_SESSION['error']) ) { $sql = "SELECT COUNT(*) AS usercount, active FROM profiles WHERE username LIKE '".$username."' AND password = md5('".$password."')"; $res = mysql_query($sql); $row = mysql_fetch_assoc($res); if (intval($row['usercount']) != 1) { $_SESSION['error'][] = "Incorrect login. Please try again!"; } if (!is_null($row['active']) && !$row['active']) { $_SESSION['error'][] = "This account has been disabled! Contact our admin to resolve this issue."; } } } function verifyName ($name) { // check length if (strlen($name) < 2 || strlen($name) > 20) { $_SESSION['error'][] = "Name must be between 2 and 20 characters long."; } } function verifyEmail($username, $email) { if (validateUsername($username) && validateEmail($email) ) { // check for same email different username $sql = "SELECT COUNT(*) usercount FROM profiles WHERE email LIKE '".$email."' AND username NOT LIKE '".$username."'"; $res = mysql_query($sql); $row = mysql_fetch_assoc($res); if (intval($row['usercount']) > 0) { $_SESSION['error'][] = "Email address already exists. Try a different email address."; } } } function validateEmail ($email, $strict = false) { // check length $regex = $strict? '/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' : '/^([*+!.$¦\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' ; if (preg_match($regex, trim($email), $matches)) { $email_valid = true; } else { $_SESSION['error'][] = "Invalid Email Address. Format should be [email protected] or something similar."; $email_valid = false; } return $email_valid; } function verifyPassword ($password) { if( strlen($password) < 6 || strlen($password) > 20 ) {$_SESSION['error'][] = "Password length should be between 6 and 20 characters.";} if( !preg_match("#[0-9]+#", $password) ) {$_SESSION['error'][] = "Password must include at least one number!";} if( !preg_match("#[a-zA-Z]+#", $password) ) {$_SESSION['error'][] = "Password must include at least one letter!";} if( !preg_match("/^[A-Za-z0-9]+\z/", $password) ) {$_SESSION['error'][] = "Password can only be numbers and letters!";} //if( !preg_match("#[a-z]+#", $password) ) {$_SESSION['error'][] = "Password must include at least one lowercase letter!";} //if( !preg_match("#[A-Z]+#", $password) ) {$_SESSION['error'][] = "Password must include at least one uppercase letter!";} //if( !preg_match("#\W+#", $password) ) {$_SESSION['error'][] = "Password must include at least one symbol!";} } function verifyUsername ($username) { if (validateUsername ($username)) { // check duplicate entries. $sql = "SELECT COUNT(*) AS usercount FROM profiles WHERE username LIKE '".$username."'"; $res = mysql_query ($sql); $row = mysql_fetch_assoc ($res); if ($row['usercount'] > 0) { $_SESSION['error'][] = "Username already exists. Try something different."; } } } function validateUsername ($username) { // check valid characters $validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"; $username_valid = true; for ($iChar = 0; $iChar < strlen($username); $iChar ++) { if ( false === strpos($validChars, $username[$iChar]) ) { $_SESSION['error'][] = "Username uses only letters, numbers and dash (-) and underscores (_) only."; $username_valid = false; break 1; } } // check length if (strlen($username) < 6 || strlen($username) > 20) { $_SESSION['error'][] = "The length of the username should be between 6 and 20 characters."; $username_valid = false; } return $username_valid; } // Form Validations <--------------------------------- ?> |
The usual engine that helps everything run. Common functionality, database connection, form validations, etc.
helpers/header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Another Hello World website</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="/js/main.js"></script> </head> <body> <div class="header"> <ul> <li><a href="/">Home</a></li> <li><a href="/users">Users</a></li> <li><a href="/aboutus">About Us</a></li> <?php if ( isLoggedIn() ) { ?> <li><a href="/<?php echo $_SESSION['username']; ?>">Profile</a></li> <li><a href="/logout">Log out</a></li> <?php } else { ?> <li><a href="/signup">Sign up</a></li> <li><a href="/login">Log in</a></li> <?php } ?> </ul> </div> <div class="body"> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/search.php'); require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/flashes.php'); renderSearchForm(); ?> <div class="page_content"> |
We’ve rearranged some of the order of rendered elements, and created some class names that we’ll use later to lay out the look and feel. Notice our flashes and search module included here. We also added jQuery and a similar main.js file as we had in admin.
helpers/search.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | <?php function renderSearchForm() { $s_params = getSearchArray(); ?> <div class="search-field"> <label for="search_gender">Gender:</label> <select name="search_gender" class="field" id="gender"> <option value="*">Any</option> <option value="Female" <?php if ($s_params['search_gender'] == "Female") { echo 'selected="selected"'; }?>>Female</option> <option value="Male" <?php if ($s_params['search_gender'] == "Male") { echo 'selected="selected"'; }?>>Male</option> </select> </div> <div class="search-field"> <label for="search_ethnicity">Ethnicity:</label> <select name="search_ethnicity" class="field" id="ethnicity"> <option value="*">Any</option> <?php $ethnicities = getEnumVals('profiles','ethnicity'); foreach ($ethnicities as $ethnicity) { ?><option value="<?php echo $ethnicity; ?>" <?php if ($s_params['search_ethnicity'] == $ethnicity) { echo 'selected="selected"'; }?>><?php echo $ethnicity; ?></option><?php } ?> </select> </div> <div class="search-field"> <label for="search_profile">Profile:</label> <select name="search_profile" class="field" id="profile"> <option value="*">Any</option> <?php $profiles = getEnumVals('profiles','profile'); foreach ($profiles as $search_profile) { ?><option value="<?php echo $search_profile; ?>" <?php if ($s_params['search_profile'] == $search_profile) { echo 'selected="selected"'; }?>><?php echo $search_profile; ?></option><?php } ?> </select> </div> <div class="search-field"> <label for="search_min_age">Age Range:</label> <select name="search_min_age" class="field" id="min_age"> <option value="*">Any</option> <?php for ($age = 1; $age<100; $age++) { ?> <option value="<?php echo $age; ?>" <?php if ($s_params['search_min_age'] == $age) { echo 'selected="selected"'; }?>><?php echo $age; ?></option> <?php } ?> </select> <select name="search_max_age" class="field" id="max_age"> <option value="*"<?php if ($s_params['search_max_age']=="*") {echo ' selected="selected" ';} ?>>Any</option> <?php for ($age = 1; $age<100; $age++) { ?> <option value="<?php echo $age; ?>" <?php if (($s_params['search_max_age'] == $age)) { echo 'selected="selected"'; } ?>><?php echo $age; ?></option> <?php } ?> </select> </div> <div class="search-field"> <label for="search_min_height">Height:</label> <select name="search_min_height" class="field" id="min_height"> <option value="*">Any</option> <?php for ($height = 12; $height<119; $height++) { ?> <option value="<?php echo $height; ?>" <?php if ($s_params['search_min_height'] == $height) { echo 'selected="selected"'; }?>><?php echo (intval($height/12))."' ".(intval($height)%12).'"'; ?></option> <?php } ?> </select> <select name="search_max_height" class="field" id="max_height"> <option value="*" <?php if ($s_params['search_max_height']=="*") {echo ' selected="selected" ';} ?>>Any</option> <?php for ($height = 12; $height<119; $height++) { ?> <option value="<?php echo $height; ?>" <?php if (($s_params['search_max_height'] == $height)) { echo 'selected="selected"'; }?>><?php echo (intval($height/12))."' ".(intval($height)%12).'"'; ?></option> <?php } ?> </select> </div> <div class="search-field"> <label for="search_min_weight">Weight:</label> <select name="search_min_weight" class="field" id="min_weight"> <option value="*">Any</option> <?php for ($weight = 5; $weight<=400; $weight+=5) { ?> <option value="<?php echo $weight; ?>" <?php if ($s_params['search_min_weight'] == $weight) { echo 'selected="selected"'; }?>><?php echo $weight; ?></option> <?php } ?> </select> <select name="search_max_weight" class="field" id="max_weight"> <option value="*" <?php if ($s_params['search_max_weight']=="*") {echo ' selected="selected" ';} ?>>Any</option> <?php for ($weight = 5; $weight<=400; $weight+=5) { ?> <option value="<?php echo $weight; ?>" <?php if (($s_params['search_max_weight'] == $weight)) { echo 'selected="selected"'; }?>><?php echo $weight; ?></option> <?php } ?> </select> </div> <div class="search-field"> <label for="search_distance">Distance:</label> <select name="search_distance" class="field" id="distance"> <option value="*">Any</option> <option value="5" <?php if ($s_params['search_distance'] == "5") { echo 'selected="selected"'; } ?>>5</option> <option value="10" <?php if ($s_params['search_distance'] == "10") { echo 'selected="selected"'; } ?>>10</option> <option value="15" <?php if ($s_params['search_distance'] == "15") { echo 'selected="selected"'; } ?>>15</option> <option value="20" <?php if ($s_params['search_distance'] == "20") { echo 'selected="selected"'; } ?>>20</option> <option value="25" <?php if ($s_params['search_distance'] == "25") { echo 'selected="selected"'; } ?>>25</option> <option value="50" <?php if ($s_params['search_distance'] == "50") { echo 'selected="selected"'; } ?>>50</option> <option value="100" <?php if ($s_params['search_distance'] == "100") { echo 'selected="selected"'; } ?>>100</option> <option value="150" <?php if ($s_params['search_distance'] == "150") { echo 'selected="selected"'; } ?>>150</option> <option value="250" <?php if ($s_params['search_distance'] == "250") { echo 'selected="selected"'; } ?>>250</option> <option value="500" <?php if ($s_params['search_distance'] == "500") { echo 'selected="selected"'; } ?>>500</option> <option value="1000" <?php if ($s_params['search_distance'] == "1000") { echo 'selected="selected"'; } ?>>1000</option> <option value="1500" <?php if ($s_params['search_distance'] == "1500") { echo 'selected="selected"'; } ?>>1500</option> <option value="2000" <?php if ($s_params['search_distance'] == "2000") { echo 'selected="selected"'; } ?>>2000</option> <option value="2500" <?php if ($s_params['search_distance'] == "2500") { echo 'selected="selected"'; } ?>>2500</option> <option value="3000" <?php if ($s_params['search_distance'] == "3000") { echo 'selected="selected"'; } ?>>3000</option> </select> <input type="text" name="search_zipcode" id="zipcode" size="10" value="<?php if ($s_params['search_distance']!= "*") { echo $s_params['search_zipcode']; } ?>"> </div> <div class="search-field"> <form class="search-form" name="searchForm" id="searchForm" method="get" action="/actors/<?php echo getPageParams(1); ?>"> <label> </label> <input type="button" value="Search Actors" onclick="javascript:performSearch();"> </form> </div> <?php } // ---------------------------------> Search Params function getSearchUrlParam($param,$number = 1) { $_SESSION['searchparams_url'] = null; if (isset($_GET['searchparams'])) { //var_dump($_GET['searchparams']); $_SESSION['searchparams_url'] = $_GET['searchparams']; $searchparams = explode("/",$_GET['searchparams']); foreach($searchparams as $searchparam) { $param_details = explode("-",$searchparam); if ($param_details[0] == $param) { return $param_details[$number]; } } } return null; } function getPageParams($page) { $final_search_string = ""; if (isset($_GET['searchparams'])) { $searchparams = explode("/",$_GET['searchparams']); $ip = 0; foreach ($searchparams as $searchparam) { $param_info = explode("-",$searchparam); if ($param_info[0] == 'page') { $final_search_string .= "page-".$page; } else { $final_search_string .= $searchparam; } if ($ip != count($searchparams)-1) { $final_search_string .= "/"; } $ip ++; } } else { $final_search_string = "page-".$page; } return($final_search_string); } function getProfilePageCount($ipp = 12, $search_engine_results) { //$search_engine_results = getProfileSearchSQL(); $sql_build = "WHERE active = 1 AND emailverified = 1 ".$search_engine_results." "; $sql_count = "SELECT CEIL(COUNT(*)/".$ipp.") AS 'page_count' FROM profiles ".$sql_build; // var_dump($sql_count); $res = mysql_query($sql_count); $count = mysql_fetch_array($res); return $count['page_count']; } function getProfiles ($search_engine_results, $params=null) { //$search_engine_results = getProfileSearchSQL(); (isset($params['current_page'])) ?($page = $params['current_page']) :($page=1); (isset($params['limit'])) ?($limit = $params['limit']) :($limit=1); (isset($params['active'])) ?($active = $params['active']) :($active=1); (isset($params['emailverified'])) ?($emailverified = $params['emailverified']) :($emailverified=1); $from = ($page * $limit) - $limit; $sql_build = "WHERE active = ".$active." AND emailverified = ".$active." ". $search_engine_results; $sql_orig = "SELECT * FROM profiles ".$sql_build." ". //"ORDER BY logintime DESC ". "LIMIT $from, $limit "; $res = mysql_query($sql_orig); //var_dump($sql_orig); //exit(0); return $res; } function getProfileSearchSQL() { $searchparams = getSearchArray(); $search_engine_results = ""; // *********** GENDER *********** // if ($searchparams['search_gender'] != "*") { $search_engine_results .= " AND gender LIKE '" . $searchparams['search_gender'] . "' " ; } // *********** ETHNICITY *********** // if ($searchparams['search_ethnicity'] != "*") { $search_engine_results .= " AND ethnicity LIKE '" . $searchparams['search_ethnicity'] . "' " ; } // *********** PROFILE *********** // if ($searchparams['search_profile'] != "*") { $search_engine_results .= " AND profile LIKE '" . $searchparams['search_profile'] . "' " ; } // *********** AGE *********** // $date_min = date( "Y-m-d",mktime(date("g")-5,date("i"),0,date("m"),date("d"),date("Y")-$searchparams['search_max_age']-1 ) ); $date_max = date( "Y-m-d",mktime(date("g")-5,date("i"),0,date("m"),date("d"),date("Y")-$searchparams['search_min_age'] ) ); if ($searchparams['search_min_age'] != "*" && $searchparams['search_max_age'] != "*") { $search_engine_results .= " AND birthdate BETWEEN '".$date_min."' AND '".$date_max."'"; } elseif ($searchparams['search_min_age'] == "*" && $searchparams['search_max_age'] != "*") { // NO MIN AGE - YES MAX AGE $search_engine_results .= " AND birthdate BETWEEN '".$date_min."' AND NOW()"; } elseif ($searchparams['search_min_age'] != "*" && $searchparams['search_max_age'] == "*") { // YES MIN AGE - NO MAX AGE $search_engine_results .= " AND birthdate <= '".$date_max."' "; } //var_dump($date_min, $date_max); // *********** HEIGHT *********** // // TODO Fix the height to allow for optional min/max values like age. if ( !($searchparams['search_min_height'] == "*" || $searchparams['search_max_height'] == "*") ) { if ($searchparams['search_min_height'] == "*") {$searchparams['search_min_height'] = 12;} if ($searchparams['search_max_height'] == "*") {$searchparams['search_max_height'] = 119;} $search_engine_results .= " AND height BETWEEN " . $searchparams['search_min_height'] . " AND " . $searchparams['search_max_height'] . " "; } if ( $searchparams['search_min_height'] != "*" && $searchparams['search_max_height'] == "*" ) { $search_engine_results .= " AND height >= " . $searchparams['search_min_height'] . " "; } if ( $searchparams['search_max_height'] != "*" && $searchparams['search_min_height'] == "*" ) { $search_engine_results .= " AND height <= " . $searchparams['search_max_height'] . " "; } // *********** WEIGHT *********** // // TODO Fix the height to allow for optional min/max values like age. if ( !($searchparams['search_min_weight'] == "*" || $searchparams['search_max_weight'] == "*") ) { if ($searchparams['search_min_weight'] == "*") {$searchparams['search_min_weight'] = 12;} if ($searchparams['search_max_weight'] == "*") {$searchparams['search_max_weight'] = 119;} $search_engine_results .= " AND weight BETWEEN " . $searchparams['search_min_weight'] . " AND " . $searchparams['search_max_weight'] . " "; } if ( $searchparams['search_min_weight'] != "*" && $searchparams['search_max_weight'] == "*" ) { $search_engine_results .= " AND weight >= " . $searchparams['search_min_weight'] . " "; } if ( $searchparams['search_max_weight'] != "*" && $searchparams['search_min_weight'] == "*" ) { $search_engine_results .= " AND height <= " . $searchparams['search_max_weight'] . " "; } // *********** ZIPCODE *********** // if ($searchparams['search_zipcode'] != "*" && $searchparams['search_distance'] != "*") { $zip_string = urlencode(trim($searchparams['search_zipcode'])); //$zipcode = trim($searchparams['search_zipcode']); //$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$zip_string."&sensor=true"; //$zip_obj = file_get_contents($url); $zip_obj = verifyZipCode($zip_string); if ($zip_obj !== false) { $Latitude = $zip_obj->latLng->lat; $Longitude = $zip_obj->latLng->lng; if ($zip_obj->adminArea5 != '' && $zip_obj->adminArea4 != '' && $zip_obj->adminArea3 != '') { if ($Longitude != '' && $Latitude != '') { // echo "OK!"; $zcdRadius = new RadiusAssistant($Latitude,$Longitude,$searchparams['search_distance']); $minLat = $zcdRadius->MinLatitude(); $maxLat = $zcdRadius->MaxLatitude(); $minLong = $zcdRadius->MinLongitude(); $maxLong = $zcdRadius->MaxLongitude(); //$query_z = "SELECT ZC.Latitude, ZC.Longitude, ZC.StateAbbr FROM ZIPCodes WHERE 1 "; $search_engine_results .= " AND Latitude >= " . $minLat . " ". " AND Latitude <= " . $maxLat . " ". " AND Longitude >= " . $minLong . " ". " AND Longitude <= " . $maxLong . " "; } } else { $_SESSION['error'][] = 'Not a valid US Postal Code!'; } } // ZIP CODE STATUS //$zip_status = $zip_obj->status; } //var_dump($search_engine_results); return $search_engine_results; } function getSearchArray() { $finalArray = array(); $finalArray["page"] = '1'; $finalArray["search_gender"] = '*'; $finalArray["search_ethnicity"] = '*'; $finalArray["search_profile"] = '*'; $finalArray["search_min_age"] = '*'; $finalArray["search_max_age"] = '*'; $finalArray["search_min_height"] = '*'; $finalArray["search_max_height"] = '*'; $finalArray["search_min_weight"] = '*'; $finalArray["search_max_weight"] = '*'; $finalArray["search_distance"] = '*'; $finalArray["search_zipcode"] = '*'; if (isset($_GET['searchparams'])) { $searchparams = explode("/",$_GET['searchparams']); foreach ($searchparams as $searchparam) { $param_info = explode("-",$searchparam); //var_dump($param_info); switch ($param_info[0]) { case 'page': $finalArray["page"] = $param_info[1]; break; case 'gender': $finalArray["search_gender"] = $param_info[1]; break; case 'ethnicity': $finalArray["search_ethnicity"] = $param_info[1]; break; case 'profile': $finalArray["search_profile"] = $param_info[1]; break; case 'age': $finalArray["search_min_age"] = $param_info[1]; $finalArray["search_max_age"] = $param_info[2]; break; case 'height': $finalArray["search_min_height"] = $param_info[1]; $finalArray["search_max_height"] = $param_info[2]; break; case 'weight': $finalArray["search_min_weight"] = $param_info[1]; $finalArray["search_max_weight"] = $param_info[2]; break; case 'distance': $finalArray["search_distance"] = $param_info[1]; $finalArray["search_zipcode"] = $param_info[2]; break; } } } return $finalArray; } function verifyZipCode ($zipcode) { $zip_obj = getZipObject($zipcode); if ($zip_obj != '') { // ZIP CODE STATUS if ($zip_obj->adminArea5 != '' && $zip_obj->adminArea4 != '' && $zip_obj->adminArea3 != '') { return $zip_obj; } else { return false; } } else { return false; } } function getZipObject($zipcode) { require_once($_SERVER['DOCUMENT_ROOT']."/helpers/zip_distance_assistant.php"); require_once($_SERVER['DOCUMENT_ROOT']."/helpers/zip_radius_assistant.php"); $latlong = array(); $url = "http://www.mapquestapi.com/geocoding/v1/address?key=Fmjtd%7Cluua20a7n5%2C22%3Do5-9622q0&location=".urlencode($zipcode)."&thumbMaps=false"; $locationOutput = ""; $zip_obj = json_decode(file_get_contents($url)); if ($zip_obj->info->statuscode == 0) { $locationOutput = $zip_obj->results[0]->locations[0]; //var_dump($locationOutput); //exit(0); } return $locationOutput; } // <--------------------------------- Search Params function drawProfilePagination($search_engine_results, $base_url = '/users/') { $pages = getProfilePageCount($ipp = 12, $search_engine_results); $current_page = getSearchUrlParam('page'); ?><div class="pagination"><?php for ($ii = 1; $ii <= $pages; $ii ++) { ?><a class="<?php if ($ii == $current_page) { echo "active "; } ?>" href="<?php echo $base_url.getPageParams($ii); ?>"><?php echo $ii; ?></a><?php } ?></div><?php } |
The search submodule. This is dependent on the profile module. This module includes the render function, along with the many functionalities to help make the search feature possible. We can go into details later into what each function does.
helpers/zip_distance_assistant.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <?php class DistanceAssistant { function DistanceAssistant() { } function Calculate( $dblLat1, $dblLong1, $dblLat2, $dblLong2 ) { $EARTH_RADIUS_MILES = 3963; $dist = 0; //convert degrees to radians $dblLat1 = $dblLat1 * M_PI / 180; $dblLong1 = $dblLong1 * M_PI / 180; $dblLat2 = $dblLat2 * M_PI / 180; $dblLong2 = $dblLong2 * M_PI / 180; if ($dblLat1 != $dblLat2 || $dblLong1 != $dblLong2) { //the two points are not the same $dist = sin($dblLat1) * sin($dblLat2) + cos($dblLat1) * cos($dblLat2) * cos($dblLong2 - $dblLong1); $dist = $EARTH_RADIUS_MILES * (-1 * atan($dist / sqrt(1 - $dist * $dist)) + M_PI / 2); } return $dist; } } ?> |
helpers/zip_radius_assistant.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <?php class RadiusAssistant { var $maxLat; var $minLat; var $maxLong; var $minLong; function RadiusAssistant($Latitude, $Longitude, $Miles) { global $maxLat,$minLat,$maxLong,$minLong; $EQUATOR_LAT_MILE = 69.172; $maxLat = $Latitude + $Miles / $EQUATOR_LAT_MILE; $minLat = $Latitude - ($maxLat - $Latitude); $maxLong = $Longitude + $Miles / (cos($minLat * M_PI / 180) * $EQUATOR_LAT_MILE); $minLong = $Longitude - ($maxLong - $Longitude); } function MaxLatitude() { return $GLOBALS["maxLat"]; } function MinLatitude() { return $GLOBALS["minLat"]; } function MaxLongitude() { return $GLOBALS["maxLong"]; } function MinLongitude() { return $GLOBALS["minLong"]; } } ?> |
These last two were classes that I downloaded from some other site. This is the only OOP code you will find in this site. I could re-write them as procedural, but why reinvent the wheel? These help with finding geocodes within a certain zipcode.
js/main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | $(document).ready(function() { performSearch = function () { var gender = $('#gender').val(); var ethnicity = $('#ethnicity').val(); var profile = $('#profile').val(); var min_age = $('#min_age').val(); var max_age = $('#max_age').val(); var min_height = $('#min_height').val(); var max_height = $('#max_height').val(); var min_weight = $('#min_weight').val(); var max_weight = $('#max_weight').val(); var distance = $('#distance').val(); var zipcode = $('#zipcode').val(); if (gender == "*") {gender = ''} else {gender = '/gender-'+gender;} if (ethnicity == "*") {ethnicity = ''} else {ethnicity = '/ethnicity-'+ethnicity;} if (profile == "*") {profile = ''} else {profile = '/profile-'+profile;} if (min_age == "*" && max_age == "*") { age = ''; } else { age = '/age-'+min_age+'-'+max_age; } if (min_height == "*" && max_height == "*") { height = ''; } else { height = '/height-'+min_height+'-'+max_height; } if (min_weight == "*" && max_weight == "*") { weight = ''; } else { weight = '/weight-'+min_weight+'-'+max_weight; } if (distance == "*" && zipcode == "") { distance = ''; } else { distance = '/distance-'+distance+'-'+zipcode; } var urlOut = '/users/page-1'+gender+ethnicity+profile+age+height+weight+distance; $('#searchForm').attr("action",urlOut); $('#searchForm').submit(); } }); |
Same as our other main.js file. This holds the controls of the search form.
.htaccess
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | SetEnv PHP_VER 5 RewriteEngine on Options +FollowSymLinks RewriteCond %{REQUEST_FILENAME} -f [NC,OR] RewriteCond %{REQUEST_FILENAME} -d [NC] RewriteRule .* - [L] # admin reserved RewriteRule ^admin/login admin/credentials.php [L,QSA] RewriteRule ^admin/logout admin/credentials.php?action=logout [L,QSA] RewriteRule ^admin/usermanagement/list/(.*) admin/usermanagement.php?action=list&searchparams=$1 RewriteRule ^admin/usermanagement/list admin/usermanagement.php?action=list RewriteRule ^admin/usermanagement/add admin/usermanagement.php?action=add RewriteRule ^admin/usermanagement/view/(.*) admin/usermanagement.php?action=view&username=$1 RewriteRule ^admin/usermanagement/edit/(.*) admin/usermanagement.php?action=edit&username=$1 RewriteRule ^admin/usermanagement/update/(.*) admin/usermanagement.php?action=update&username=$1 RewriteRule ^admin/usermanagement/delete/(.*) admin/usermanagement.php?action=delete&username=$1 RewriteRule ^admin/usermanagement admin/usermanagement.php [L,QSA] # Main and static pages RewriteRule ^$ index.php RewriteRule ^about about.php # Credential pages RewriteRule ^signup/(.*) credentials.php?action=$1 RewriteRule ^signup credentials.php?action=showsignup RewriteRule ^login/(.*) credentials.php?action=$1 RewriteRule ^login credentials.php?action=showlogin RewriteRule ^logout credentials.php?action=logout RewriteRule ^resetpassword credentials.php?action=resetpassword RewriteRule ^doresetpassword credentials.php?action=doresetpassword RewriteRule ^verifyemail/(.*)/(.*) credentials.php?action=verifyemail&verifycode=$1&email=$2 RewriteRule ^emailverified credentials.php?action=emailverified # Profile pages RewriteRule ^users/(.*) profile.php?action=list&searchparams=$1 RewriteRule ^users profile.php?action=list # Profile single page RewriteRule ^([^/\.]+)?/(.*)$ profile.php?un=$1&action=$2 [L,QSA] RewriteRule ^([^/\.]+)?/?$ profile.php?un=$1 [L,QSA] RewriteRule ^(.*)\.htm$ $1.php [NC] RewriteRule ^(.*)\.html$ $1.php [NC] |
And now for the .htaccess file. Notice how we removed the .htaccess file from the admin section, simply because we could control the routes from here. We added the admin routes to this file as well. We set everything before the profile pages because we don’t want conflicts with htaccess confusing different routes with usernames. For any new page, or modification of existing pages, this is your main router. If you need to change the route to a file, make sure you do a search throughout your site for the old request URL first.
about.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php'); $link = connect(); showAction(); close($link); function showAction () { require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?><p>This is the section you write about yourself.</p><?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } ?> |
Same ol’ same ol’.
credentials.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php'); $link = connect(); if ( isset($_GET['action']) ) { switch ($_GET['action']) { case "showsignup": showSignupFormAction(); break; case "trysignup": signupAction(); break; case "showlogin": showLoginFormAction(); break; case "trylogin": loginAction(); break; case "logout": tryLogout(); break; case "resetpassword": resetPasswordShowAction(); break; case "doresetpassword": resetPasswordAction(); break; case "verifyemail": verifyEmailAction(); break; default: header('Location: /'); } } else { header('Location: /'); } close($link); function showSignupFormAction () { require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?> <form action="/signup/trysignup" method="post"> <label for="fname">First Name</label> <input type="text" name="fname" value="<?php if (isset($_POST['fname'])) { echo $_POST['fname']; } ?>"> <label for="lname">Last Name</label> <input type="text" name="lname" value="<?php if (isset($_POST['lname'])) { echo $_POST['lname']; } ?>"> <label for="zipcode">Postal Code</label> <input type="text" name="zipcode" value="<?php if (isset($_POST['zipcode'])) { echo $_POST['zipcode']; } ?>"> <label for="username">Username</label> <input type="text" name="username" value="<?php if (isset($_POST['username'])) { echo $_POST['username']; } ?>"> <label for="password">Password</label> <input type="password" name="password" value=""> <label for="password2">Retype Password</label> <input type="password" name="password2" value=""> <label for="email">E-Mail Address</label> <input type="text" name="email" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>"> <label for="profile">Profile Type</label> <select name="profile"> <option value="Talent" <?php if (isset($_POST['profile']) && $_POST['profile'] == "Talent") { echo " selected ";}?>>Talent</option> <option value="Producer" <?php if (isset($_POST['profile']) && $_POST['profile'] == "Producer") { echo " selected ";}?>>Producer</option> <option value="Makeup Artist" <?php if (isset($_POST['profile']) && $_POST['profile'] == "Makeup Artist") { echo " selected ";}?>>Makeup Artist</option> <option value="Photographer" <?php if (isset($_POST['profile']) && $_POST['profile'] == "Photographer") { echo " selected ";}?>>Photographer</option> </select> <label for="gender">Gender</label> <select name="gender"> <option value="Female" <?php if (isset($_POST['gender']) && $_POST['gender'] == "Female") { echo " selected ";}?>>Female</option> <option value="Male" <?php if (isset($_POST['gender']) && $_POST['gender'] == "Male") { echo " selected ";}?>>Male</option> </select> <label for="month">Birthdate</label> <select name="month"> <?php for($iMonth = 1; $iMonth <= 12; $iMonth ++) { ?> <option value="<?php echo $iMonth; ?>" <?php if (isset($_POST['month']) && $_POST['month'] == $iMonth) { echo " selected ";}?>><?php echo $iMonth; ?></option> <?php } ?> </select> <select name="day"> <?php for($iDay = 1; $iDay <= 31; $iDay ++) { ?> <option value="<?php echo $iDay; ?>" <?php if (isset($_POST['day']) && $_POST['day'] == $iDay) { echo " selected ";}?>><?php echo $iDay; ?></option> <?php } ?> </select> <select name="year"> <?php for($iYear = 2000; $iYear >= 1900; $iYear --) { ?> <option value="<?php echo $iYear; ?>" <?php if (isset($_POST['year']) && $_POST['year'] == $iYear) { echo " selected ";}?>><?php echo $iYear; ?></option> <?php } ?> </select> <input type="submit" value="Register"> </form> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function signupAction () { $_SESSION['error'] = null; // clean up against SQL injection. $fname = $_POST['fname']; $lname = $_POST['lname']; $username = $_POST['username']; $password = $_POST['password']; $password2 = $_POST['password2']; $secretPw = md5($password); $email = $_POST['email']; $verifycode = md5(uniqid()); $profile = $_POST['profile']; $gender = $_POST['gender']; $zipcode = $_POST['zipcode']; $year = intval($_POST['year']); $month = intval($_POST['month']); $day = intval($_POST['day']); $birthdate = $year.'-'.$month.'-'.$day; $created = strtotime("now"); $updated = strtotime("now"); if (!checkdate($month,$day,$year)) { $_SESSION['error'][] = "Invalid date selected!"; } else { verifyDate($year,$month,$day); } $latlong = verifyZipCode($zipcode); if ($latlong === false){ $_SESSION['error'][] = "Incorect Postal Code or Location!"; } else { $latitude = $latlong->latLng->lat; $longitude = $latlong->latLng->lng; $city = $latlong->adminArea5; $county = $latlong->adminArea4; $state = $latlong->adminArea3; $country = $latlong->adminArea1; } verifyUsername($username); verifyName ($fname); verifyName ($lname); verifyPassword($password); if ( $password != $password2 ) { $_SESSION['error'][] = "Passwords do not match."; } verifyEmail ($username, $email); if (is_null($_SESSION['error'])) { $sql = "INSERT INTO profiles ( `username`,`fname`,`lname`,`password`,`email`,`profile`,`gender`,`birthdate`,`city`,`state`,`country`,`zipcode`,`latitude`,`longitude`,`created`,`updated`,`verifycode` ) VALUES ( '".$username."','".$fname."','".$lname."','".$secretPw."','".$email."','".$profile."','".$gender."','".$birthdate."','".$city."','".$state."','".$country."','".$zipcode."',".$latitude.",".$longitude.",".$created.",".$updated.",'".$verifycode."' )"; //var_dump($sql); //exit(0); mysql_query($sql); $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "Your account has been successfully been created! Check your email to verify your account!"; // build email $body = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/helpers/email_templates/cool/html/full_width.html'); $body = str_replace('__BODY__','<a href="http://dev.website.com/verifyemail/'.$verifycode.'/'.urlencode($email).'">Click here to verify your email</a> Or copy paste this in your browser http://dev.website.com/verifyemail/'.$verifycode.'',$body); //var_dump($body); // send email out: $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: [email protected]' . "\r\n"; mail($email,"Verify your new account on mywebsite.com",$body,$headers); // redirect to personal profile page header('Location: /login'); } else { // this shows our submit form. showSignupFormAction(); } } function showLoginFormAction () { require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?> <form action="/login/trylogin" method="post"> <label for="email">Username</label> <input type="text" name="username" value="<?php if (isset($_POST['username'])) { echo $_POST['username']; } ?>"> <label for="email">Password</label> <input type="password" name="password" value=""> <input type="submit" value="Login"> </form> <a href="/resetpassword">Recover Password</a> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function loginAction () { $username = $_POST['username']; $password = $_POST['password']; verifyLogin($username, $password); if (is_null($_SESSION['error'])) { $_SESSION['username'] = $username; $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "Welcome back, $username!"; header('Location: /'.$username); } else { // this shows our submit form. showLoginFormAction(); } } function tryLogout () { if (isLoggedIn()) { logoutAction(); } else { showLogoutSuccessAction(); } } function logoutAction () { // kill session, and later, kill cookies. $_SESSION['username'] == null; session_destroy(); header('Location: /logout'); } function showLogoutSuccessAction() { require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?>You have been logged out.<?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function resetPasswordShowAction() { require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?> <form action="/doresetpassword" method="post"> <label for="email">Username or Email</label> <input type="text" name="usernameemail" value="<?php if (isset($_POST['usernameemail'])) { echo $_POST['usernameemail']; } ?>"> <input type="submit" value="Recover"> </form> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function resetPasswordAction() { $usernameemail = $_POST['usernameemail']; $email_validated = true; $username_validated = true; validateUsername ($usernameemail); if (!is_null($_SESSION['error'])) { $email_validated = false; $_SESSION['error'] = null; } validateEmail ($usernameemail); if (!is_null($_SESSION['error'])) { $username_validated = false; $_SESSION['error'] = null; } if ($username_validated || $email_validated) { $_SESSION['error'] = null; $sql = "SELECT COUNT(*) AS usercount, email, username FROM profiles WHERE username LIKE '".$usernameemail."' OR email LIKE '".$usernameemail."';"; $res = mysql_query($sql); $row = mysql_fetch_assoc($res); if (intval($row['usercount']) > 0) { // update the database with new password; $newPass = uniqid(); $newPassEnc = md5($newPass); $sql = "UPDATE profile SET password = '".$newPassEnc."' WHERE username = '".$row['username']."';"; mysql_query($sql); // success, email out and show success page. $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: [email protected]' . "\r\n"; mail($row['email'],"Your new password has arrived.","You have requested to reset your password. Your username is <strong>".$row['username']."</strong> and your new password is: <strong>".$newPass."</strong>",$headers); $_SESSION['notice_count'] = 1; $_SESSION['notice'][] = 'Your new password has been sent to your email address that you used to register. Please check your email address for your new password.'; header('Location: /login'); } else { // failed, show the form again. $_SESSION['error'][] = "Email or username not registered or found."; resetPasswordShowAction(); } } else { validateUsername ($usernameemail); validateEmail ($usernameemail); resetPasswordShowAction(); } } function verifyEmailAction() { $_SESSION['error'] = null; $_SESSION['notice'] = null; //var_dump($_GET); $sql = "SELECT COUNT(*) AS usercount FROM profiles WHERE email = '".$_GET['email']."' AND verifycode = '".$_GET['verifycode']."';"; $res = mysql_query($sql); $row = mysql_fetch_assoc($res); if ($row['usercount'] > 0) { $sql = "UPDATE profiles SET emailverified = 1 WHERE email = '".$_GET['email']."' AND verifycode = '".$_GET['verifycode']."';"; $res = mysql_query($sql); if ($res) { $_SESSION['notice_count'] = 1; $_SESSION['notice'][] = "Your email has been verified. You may log in!"; header('Location: /login'); } else { $_SESSION['error_count'] = 1; $_SESSION['error'][] = "Your email has not been verified. Contact us to fix it."; header('Location: /login'); } } else { $_SESSION['error_count'] = 1; $_SESSION['error'][] = "Your email has not been verified. Contact us to fix it."; header('Location: /login'); } } ?> |
This one has everything to do with logging in, loggin out, signing up, email verifications, resetting passwords, etc. It’s our cerdentials module.
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php'); $link = connect(); showAction(); close($link); function showAction () { require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?><p>Hello World!</p><?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } ?> |
Not much changed here either. Next.
profile.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/functions.php'); $link = connect(); if (isset($_GET['action'])) { switch ($_GET['action']) { case "list": listAction (); break; case "edit": editAction(); break; case "editemail": editEmailAction(); break; case "editpassword": editPasswordAction(); break; case "save": saveAction(); break; case "saveemail": saveEmailAction(); break; case "savepassword": savePasswordAction(); break; case "deactivateaccount": deactivateAccountAction(); break; default: showAction(); } } else { showAction(); } close($link); function deactivateAccountAction () { if (isLoggedIn()) { $username = $_SESSION['username']; $sql = "UPDATE profiles SET active = 0 WHERE username ='".$username."'"; mysql_query($sql); session_destroy(); } header('Location: /'); } function showAction () { $user = getProfile($_GET['un']); require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); if ($user) { list($year,$month,$day) = explode("-",$user['birthdate']); ?> <div> <div>username <span><?php echo $user['username']; ?></span></div> <div>name <span><?php echo $user['fname']; ?></span> <span><?php echo $user['lname'] ?></span></div> <div>profile <span><?php echo $user['profile']; ?></span></div> <div>gender <span><?php echo $user['gender']; ?></span></div> <div>ethnicity <span><?php echo $user['ethnicity']; ?></span></div> <div>height <span><?php echo (intval($user['height']/12))."' ".(intval($user['height'])%12).'"'; ?></span></div> <div>weight <span><?php echo $user['weight']; ?> lbs</span></div> <div>age <span><?php echo $year_diff = date("Y") - $year; ?> years</span></div> <div>City <span><?php echo $user['city'] ?></span></div> <div>State <span><?php echo $user['state'] ?></span></div> <div>Countrry <span><?php echo $user['country'] ?></span></div> <div>ZIP Code <span><?php echo $user['zipcode'] ?></span></div> </div> <?php if ( isLoggedInUser($user['username']) && intval($user['emailverified']) === 1 ) { ?> <a href="/<?php echo $_SESSION['username']; ?>/edit">Change Profile</a><br> <div><?php echo $user['email']; ?></div> <a href="/<?php echo $_SESSION['username']; ?>/editemail">Change Email</a> <div>password is securely stored</div> <a href="/<?php echo $_SESSION['username']; ?>/editpassword">Change Password</a> <div>account is active</div> <a href="/<?php echo $_SESSION['username']; ?>/deactivateaccount">Deactivate My Account</a> <?php } } else { echo "No profile found with that username: ".$_GET['un']; } require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function listAction () { require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); $search_engine_results = getProfileSearchSQL(); $current_page = getSearchUrlParam('page'); if (is_null($current_page)) {$current_page = 1;} $params = array( 'current_page' => $current_page, 'limit' => 12 ); $users = getProfiles($search_engine_results, $params); drawProfilePagination($search_engine_results); ?><ul class="profiles-list"><?php while ($user = mysql_fetch_array($users)) { ?> <li> <a href="/<?php echo $user['username']; ?>"> <img src="/users/<?php echo $user['id']; ?>.jpg" alt="<?php echo $user['fname']." ".$user['lname'] ; ?>"> <span><?php echo $user['fname']." ".$user['lname'] ; ?></span> <span><?php echo $user['city'] ; ?></span> <span><?php echo $user['state'] ; ?></span> </a> </li> <?php } ?></ul><?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function editAction () { $profile = getProfile($_GET['un']); if (!isLoggedInUser($profile['username'])) { header('Location: /'.$profile['username']); } require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?> <form method="post" action="/<?php echo $_SESSION['username']; ?>/save"> <label for="fname">First Name</label> <input type="text" name="fname" value="<?php if (isset($_POST['fname'])) { echo $_POST['fname']; } else {echo $profile['fname'];} ?>"> <label for="lname">Last Name</label> <input type="text" name="lname" value="<?php if (isset($_POST['lname'])) { echo $_POST['lname']; } else {echo $profile['lname'];} ?>"> <label for="zipcode">Postal Code</label> <input type="text" name="zipcode" value="<?php if (isset($_POST['zipcode'])) { echo $_POST['zipcode']; } else {echo $profile['zipcode'];} ?>"> <label for="profile">Profile Type</label> <select name="profile"> <option value="Talent" <?php if (isset($_POST['profile']) && $_POST['profile'] == "Talent") { echo " selected ";} elseif ($profile['profile']=="Talent") { echo " selected "; } ?>>Talent</option> <option value="Producer" <?php if (isset($_POST['profile']) && $_POST['profile'] == "Producer") { echo " selected ";} elseif ($profile['profile']=="Producer") { echo " selected "; }?>>Producer</option> <option value="Makeup Artist" <?php if (isset($_POST['profile']) && $_POST['profile'] == "Makeup Artist") { echo " selected ";} elseif ($profile['profile']=="Makeup Artist") { echo " selected "; }?>>Makeup Artist</option> <option value="Photographer" <?php if (isset($_POST['profile']) && $_POST['profile'] == "Photographer") { echo " selected ";} elseif ($profile['profile']=="Photographer") { echo " selected "; }?>>Photographer</option> </select> <label for="gender">Gender</label> <select name="gender"> <option value="Female" <?php if (isset($_POST['gender']) && $_POST['gender'] == "Female") { echo " selected ";} elseif ($profile['gender']=="Female") { echo " selected "; }?>>Female</option> <option value="Male" <?php if (isset($_POST['gender']) && $_POST['gender'] == "Male") { echo " selected ";} elseif ($profile['gender']=="Male") { echo " selected "; }?>>Male</option> </select> <label for="ethnicity">Ethnicity</label> <select name="ethnicity"> <?php $ethnicities = getEnumVals('profiles','ethnicity'); foreach ($ethnicities as $ethnicity) { ?> <option value="<?php echo $ethnicity; ?>" <?php if (isset($_POST['ethnicity']) && $_POST['ethnicity'] == $ethnicity) { echo " selected ";} elseif ($profile['ethnicity']==$ethnicity) { echo " selected "; }?>><?php echo $ethnicity; ?></option> <?php } ?> </select> <label for="height">Height</label> <select name="height"> <?php for ($iH = 20; $iH <= 110; $iH++) { ?><option value="<?php echo $iH; ?>" <?php if (isset($_POST['height']) && $_POST['height'] == $iH) { echo " selected ";} elseif ($profile['height']==$iH) { echo " selected "; }?>><?php echo intval($iH/12) ."'". $iH%12 . '"'; ?></option><?php } ?> </select> <label for="weight">Weight</label> <select name="weight"> <?php for ($iW = 20; $iW <= 600; $iW+=5) { ?><option value="<?php echo $iW; ?>" <?php if (isset($_POST['weight']) && $_POST['weight'] == $iW) { echo " selected ";} elseif ($profile['weight']==$iW) { echo " selected "; }?>><?php echo $iW; ?> lbs</option><?php } ?> </select> <label for="month">Birthdate</label> <select name="month"> <?php for($iMonth = 1; $iMonth <= 12; $iMonth ++) { ?> <option value="<?php echo $iMonth; ?>" <?php if (isset($_POST['month']) && $_POST['month'] == $iMonth) { echo " selected ";}elseif (intval(date("n", strtotime($profile['birthdate'])))== $iMonth) { echo " selected "; }?>><?php echo $iMonth; ?></option> <?php } ?> </select> <select name="day"> <?php for($iDay = 1; $iDay <= 31; $iDay ++) { ?> <option value="<?php echo $iDay; ?>" <?php if (isset($_POST['day']) && $_POST['day'] == $iDay) { echo " selected ";}elseif (intval(date("j", strtotime($profile['birthdate'])))== $iDay) { echo " selected "; }?>><?php echo $iDay; ?></option> <?php } ?> </select> <select name="year"> <?php for($iYear = 2000; $iYear >= 1900; $iYear --) { ?> <option value="<?php echo $iYear; ?>" <?php if (isset($_POST['year']) && $_POST['year'] == $iYear) { echo " selected ";}elseif (intval(date("Y", strtotime($profile['birthdate'])))== $iYear) { echo " selected "; }?>><?php echo $iYear; ?></option> <?php } ?> </select> <input type="submit" value="Update Profile"> </form> <a href="/<?php echo $_SESSION['username']; ?>">[-] Cancel</a> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function editEmailAction () { $profile = getProfile($_GET['un']); if (!isLoggedInUser($profile['username'])) { header('Location: /'.$profile['username']); } require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?> <form method="post" action="/<?php echo $_SESSION['username']; ?>/saveemail"> <label for="email">E-Mail Address</label> <input type="text" name="email" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>"> <input type="submit" value="Update Email"> </form> <a href="/<?php echo $_SESSION['username']; ?>">[-] Cancel</a> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function editPasswordAction () { $profile = getProfile($_GET['un']); if (!isLoggedInUser($profile['username'])) { header('Location: /'.$profile['username']); } require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/header.php'); ?> <form method="post" action="/<?php echo $_SESSION['username']; ?>/savepassword"> <label for="email">Old Password</label> <input type="password" name="oldpassword" value=""> <label for="email">Password</label> <input type="password" name="password" value=""> <label for="email">Retype Password</label> <input type="password" name="password2" value=""> <input type="submit" value="Update Password"> </form> <a href="/<?php echo $_SESSION['username']; ?>">[-] Cancel</a> <?php require_once($_SERVER['DOCUMENT_ROOT'].'/helpers/footer.php'); } function saveAction () { $fname = $_POST['fname']; $lname = $_POST['lname']; $username = $_SESSION['username']; $profile = $_POST['profile']; $gender = $_POST['gender']; $ethnicity = $_POST['ethnicity']; $year = intval($_POST['year']); $month = intval($_POST['month']); $day = intval($_POST['day']); $height = intval($_POST['height']); $weight = intval($_POST['weight']); $birthdate = $year.'-'.$month.'-'.$day; $zipcode = $_POST['zipcode']; $latitude = 0; $longitude = 0; $city = ""; $state = ""; $country = ""; $updated = strtotime("now"); if (!isLoggedInUser($_GET['un'])) { header('Location: /'.$profile['username']); } verifyName($fname); verifyName($lname); $zip_obj = verifyZipCode($zipcode); if ($zip_obj === false) { $_SESSION['error'][] = 'Invalid Postal Code or Location'; } else { $latitude = $zip_obj->latLng->lat; $longitude = $zip_obj->latLng->lng; $city = $zip_obj->adminArea5; $county = $zip_obj->adminArea4; $state = $zip_obj->adminArea3; $country = $zip_obj->adminArea1; } if (!checkdate($month,$day,$year)) { $_SESSION['error'][] = "Invalid date selected!"; } else { verifyDate($year,$month,$day); } //var_dump(isLoggedInUser($_GET['un'])); //exit(0); if (is_null($_SESSION['error'])) { $sql = "UPDATE profiles SET `fname` = '".$fname."', `lname` = '".$lname."', `profile` = '".$profile."', `gender` = '".$gender."', `ethnicity` = '".$ethnicity."', `height` = ".$height.", `weight` = ".$weight.", `birthdate` = '".$birthdate."', `city` = '".$city."', `state` = '".$state."', `country` = '".$country."', `zipcode` = '".$zipcode."', `latitude` = '".$latitude."', `longitude` = '".$longitude."', `updated` = '".$updated."' WHERE username LIKE '".$username."'"; //var_dump($sql); //exit(0); mysql_query($sql); $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "Profile updated!"; header ('Location: /'.$_SESSION['username']); } editAction(); } function saveEmailAction () { $email = $_POST['email']; $username = $_SESSION['username']; $verifycode = md5(uniqid()); //var_dump($_GET); //exit(0); if (!isLoggedInUser($_GET['un'])) { header('Location: /'.$profile['username']); } verifyEmail($username,$email); if (is_null($_SESSION['error'])) { $sql = "UPDATE profiles SET `email` = '".$email."', `emailverified` = 0, `verifycode` = '".$verifycode."' WHERE username LIKE '".$username."'"; //var_dump($sql); //exit(0); mysql_query($sql); $body = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/helpers/email_templates/cool/html/full_width.html'); $body = str_replace('__BODY__','<a href="http://dev.website.com/verifyemail/'.$verifycode.'/'.urlencode($email).'">Click here to verify your email</a> Or copy paste this in your browser http://dev.website.com/verifyemail/'.$verifycode.'',$body); //var_dump($body); // send email out: $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: [email protected]' . "\r\n"; mail($email,"Verify your new account on mywebsite.com",$body,$headers); $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "Email updated! Check your email to verify it."; header ('Location: /'.$username); } editEmailAction(); } function savePasswordAction() { $oldpassword = $_POST['oldpassword']; $password = $_POST['password']; $password2 = $_POST['password2']; $username = $_SESSION['username']; if (!isLoggedInUser($_GET['un'])) { header('Location: /'.$profile['username']); } verifyPassword($oldpassword); verifyPassword($password); if (is_null($_SESSION['error'])) { $sql = "SELECT COUNT(*) AS oldpwcount FROM profiles WHERE username LIKE '".$username."' AND password = md5('".$oldpassword."')"; $res = mysql_query($sql); $row = mysql_fetch_assoc($res); if (intval($row['oldpwcount']) < 1) { // means that the old password was NOT correctly entered. $_SESSION['error'][] = "Old password is not correct!"; } if ($password != $password2) { $_SESSION['error'][] = "New passwords do not match!"; } } if (is_null($_SESSION['error'])) { $sql = "UPDATE profiles SET `password` = md5('".$password."') WHERE username LIKE '".$username."'"; mysql_query($sql); $_SESSION['notice_count'] += 1; $_SESSION['notice'][] = "Password has been updated!"; header ('Location: /'.$_SESSION['username']); } editPasswordAction(); } ?> |
Same as before.
The End!
Summary
These are approximations.
- admin section: 430 lines of code.
- helpers: 984 lines of code.
- the rest: 855 lines of code.
- total lines of code: 2,269
- 89,365 bytes of code. Or almost 90,000 characters written out by hand.
- Correction: 87,384 bytes of code after removing all of the extra tabs in the pages. So, not even 88,000 lines of code. Converted in KB, this is less than 85.5KB of code, hand written. Let’s see any framework do that.
It seems like a lot! However, when you think of all of the other frameworks out there, our 88K size website kicks the crap out of them. Of course, our package is not a full framework with all the complexity and limitations a framework can bring. This is simply a barebone minimum for anyone who wants a starting skeleton to build a website.
At this point, you can simply build more modules, more fixtures, the potential is limitless. Do you want a shopping card website? Build the following modules:
- product
- category
- cart
- checkout
- my account
- orders history
- admin
- orders
- catelog
- products
- categories
And that’s pretty much it. The core is ready.
Want a blog site?
- posts
- single post
- admin
Of course you can add more modules, like user signups and stuff, but this is your simple blog site.
Or, you can even make a simple static page business website by making all of the pages like the about us page.
What if you wanted to make a network site where people can read each others’ posts?
- index (wall)
- credentials
- friends
- admin
- usermanager
- wall management
And you can make a nice facebook like page. The complexity should be in the code itself, not in the core.
For the future…
I might add theming to the site, and some custom made modules to help with the above mentioned samples.
Let me know if you guys liked this. Leave a comment or two.
Cheers!
Updates:
CleanPHP 0.1.0
Changelog: This version is one step up from the documented one. I merged the main.js files and passed in variables to the search functions for the base URL of the form action And with that, I close the very first fully released version.
Files changed:
- /js/main.js
- /helpers/search.php
- /helpers/header.php
- /admin/helpers/header.php
- removed - /admin/main.js