· 8 years ago · Jun 19, 2018, 06:38 PM
1<?php
2
3/**
4 * @param $required_fields_array, an array containing the list of all required fields
5 * @return array, containing all errors
6 */
7function check_empty_fields($required_fields_array){
8 //initialize an array to store error messages
9 $form_errors = array();
10
11 //loop through the required fields array and populate the form error array
12 foreach($required_fields_array as $name_of_field){
13 if(!isset($_POST[$name_of_field]) || $_POST[$name_of_field] == NULL){
14 $form_errors[] = $name_of_field . " Is A Required Field";
15 }
16 }
17
18 return $form_errors;
19}
20
21/**
22 * @param $fields_to_check_length, an array containing the name of fields
23 * for which we want to check min required length e.g. array('username' => 4, 'email' => 12)
24 * @return array, containing all errors
25 */
26function check_min_length($fields_to_check_length){
27 //initialize an array to store error messages
28 $form_errors = array();
29
30 foreach($fields_to_check_length as $name_of_field => $minimum_length_required){
31 if(strlen(trim($_POST[$name_of_field])) < $minimum_length_required){
32 $form_errors[] = $name_of_field . " Is Too Short, Must Be {$minimum_length_required} Characters Long";
33 }
34 }
35 return $form_errors;
36}
37
38/**
39 * @param $data, store a key/value pair array where key is the name of the form control
40 * in this case 'email' and value is the input entered by the user
41 * @return array, containing email error
42 */
43function check_email($data){
44 //initialize an array to store error messages
45 $form_errors = array();
46 $key = 'email';
47 //check if the key email exists in data array
48 if(array_key_exists($key, $data)){
49
50 //check if email has a value
51 if($_POST[$key] != null){
52
53 //remove all illegal characters from email
54 $key = filter_var($key, FILTER_SANITIZE_EMAIL);
55
56 //check if input is a valid email address
57 if(filter_var($_POST[$key], FILTER_VALIDATE_EMAIL) === false){
58 $form_errors[] = $key . " Is Not A Valid Email Address";
59 }
60 }
61 }
62 return $form_errors;
63}
64
65/**
66 * @param $form_errors_array, the array holding all
67 * errors which we want to loop through
68 * @return string, list containing all error messages
69 */
70function show_errors($form_errors_array){
71 $errors = "<p><ul style='color: red;'>";
72
73 //loop through error array and display all items in a list
74 foreach($form_errors_array as $the_error){
75 $errors .= "<li> {$the_error} </li>";
76 }
77 $errors .= "</ul></p>";
78
79 return $errors;
80}
81
82function flashMessage($message, $passOrFail = "Fail"){
83 if($passOrFail === "Pass"){
84 $data = "<div class='alert alert-success'>{$message}</p>";
85 }else {
86 $data = "<div class='alert alert-danger'>{$message}</p>";
87 }
88 return $data;
89}
90
91function redirectTo($page){
92 header("location: {$page}.php");
93}
94
95function checkDuplicateEntries($table, $column_name, $value, $db){
96 try{
97 $sqlQuery ="SELECT * FROM .$table. WHERE .$column_name.=:$column_name";
98 $statement = $db->prepare($sqlQuery);
99 $statement->execute(array(':$column_name' => $value));
100 if($row = $statement->fetch()){
101 return true;
102 }
103 return false;
104 }catch (PDOException $ex){
105 //handle exception
106 }
107}
108
109/**
110 * @param $user_id
111 */
112function rememberMe($user_id){
113 $encryptCookieData = base64_encode("JaRteF5i8y0dntstemYODEC{$user_id}");
114 //cookie will expire in 30 days
115 setcookie("rememberUserCookie", $encryptCookieData, time()+60*60*24*100, "/");
116}
117
118/**
119 * check if the cookie used is same with the encrypted cookie
120 * @param $db, database connection link
121 * @return bool, true if the user cookie is valid
122 */
123function isCookieValid($db){
124 $isValid = false;
125
126 if(isset($_COOKIE['rememberUserCookie'])){
127
128 /**
129 * Decode cookies and extract user ID
130 */
131 $decryptCookieData = base64_decode($_COOKIE['rememberUserCookie']);
132 $user_id = explode("JaRteF5i8y0dntstemYODEC", $decryptCookieData);
133 $user_ID = $user_id[1];
134
135 /**
136 * check if id retrieved from the cookie exist in the database
137 **/
138 $sqlQuery = "SELECT * FROM users WHERE id = :id";
139 $statement = $db->prepare($sqlQuery);
140 $statement->execute(array(':id' => $user_ID));
141
142 if($row = $statement->fetch()){
143 $id = $row['id'];
144 $username = $row['username'];
145
146 /**
147 * create the user session variable
148 */
149 $_SESSION['id'] = $id;
150 $_SESSION['username'] = $username;
151 $isValid = true;
152 }else{
153 /**
154 * cookie ID is invalid destroy session and logout user
155 */
156 $isValid = false;
157 $this->signout();
158 }
159 }
160 return $isValid;
161}
162function signout(){
163 unset($_SESSION['username']);
164 unset($_SESSION['id']);
165
166 if(isset($_COOKIE['rememberUserCookie'])){
167 unset($_COOKIE['rememberUserCookie']);
168 setcookie('rememberUserCookie', null, -1, '/');
169 }
170 session_destroy();
171 session_regenerate_id(true);
172 redirectTo('index');
173}
174
175function guard(){
176 $isValid = true;
177 $inactive = 60 * 2; //2mins
178 $fingerprint = md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
179 if((isset($_SESSION['fingerprint']) && $_SESSION['fingerprint'] != $fingerprint)){
180 $isValid = false;
181 signout();
182 }else if((isset($_SESSION['last_inactive']) && (time() - $_SESSION['last_inactive']) > $inactive) && $_SESSION['username']){
183 $isValid = false;
184 signout();
185 }else{
186 $_SESSION['last_inactive'] = time();
187 }
188 return $isValid;
189}
190
191function isValidImage($file)
192{
193 $form_errors = array();
194
195 $part = explode(".", $file);
196 $extension = end($part);
197 switch (strtolower($extension)) {
198 case 'jpg':
199 case 'gif':
200 case 'bmp':
201 case 'png':
202
203 return $form_errors;
204 }
205 $form_errors[] = $extension . "is not a valid image extension";
206 return $form_errors;
207}
208
209function uploadAvatar($username){
210 if($_FILES['avatar']['tmp_name']){
211
212 //File in the temp location
213 $temp_file = $_FILES['avatar']['tmp_name'];
214 $ext = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
215 $filename = $username.md5(microtime()).".{$ext}";
216
217 $path = "uploads/{$filename}"; //uploads/demo.jpg
218 move_uploaded_file($temp_file, $path);
219
220 return $path;
221 }
222
223 return false;
224}
225
226
227function _token(){
228 $randomToken = base64_encode(openssl_random_pseudo_bytes(32));
229 // $randomToken = md5(uniqid(rand(), true));
230 return $_SESSION['token'] = $randomToken;
231}
232
233function validate_token($requestToken){
234 if(isset($_SESSION['token']) && $requestToken === $_SESSION['token']){
235 unset($_SESSION['token']);
236 return true;
237 }
238 return false;
239}
240
241function prepLogin($id, $username, $remember){
242 $_SESSION['id'] = $id;
243 $_SESSION['username'] = $username;
244
245 $fingerprint = md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
246 $_SESSION['last_active'] = time();
247 $_SESSION['fingerprint'] = $fingerprint;
248
249 if ($remember === "yes") {
250 rememberMe($id);
251 }
252
253 // call sweet alert
254 echo $welcome = "<script type=\"text/javascript\">
255 swal({
256 title: \"Welcome $username\",
257 text: \"You're being logged in\",
258 type: 'success',
259 timer: 6000,
260 showConfirmButton: false });
261
262 setTimeout(function() {
263 window.location.href = 'index.php';
264 }, 5000);
265 </script>";
266}