-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlibraryClass.php
More file actions
777 lines (625 loc) · 22.9 KB
/
libraryClass.php
File metadata and controls
777 lines (625 loc) · 22.9 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
<?php
/**-----------------------------------------------------
* This is a Php library to handle the common php task
such as database connection, connection status, insert,
delete, update, isCredentialValid, etc, get connectionError Message,
get the name of connected database
* @author Kemoy Campbell
--------------------------------------------------------*/
class Library
{
private $dbname;
private $dbusername;
private $dbpassword;
private $host;
private $errorMessage;
//create a database instance constructor
public function _construct($config)
{
$this->dbname = $config['dbname'];
$this->dbusername = $config['dbusername'];
$this->dbpassword = $config['dbpassword'];
$this->host = $config['host'];
}
/**------------------------------------------------------------
Function to connect to the database.
This function returns the connection PDO connection if the
connection was succesful connected else display failed to
connect error message.
return : if the connection is successful then the pdo connection
is return else it return false
-----------------------------------------------------------------*/
public function connect()
{
//default state fo the connection
$this->errorMessage ='Connection OK'; //temp fix as placing this in the constructor wont work
//attempt to connect
try{
$databaseConnectString = 'mysql:host='.$this->host.';dbname='.$this->dbname;
$conn = new PDO($databaseConnectString,$this->dbusername,$this->dbpassword);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;//database successful connected
}
//database failed
catch(PDOException $e)
{
$this->errorMessage = $e->getMessage();
return false;
}
}
/*-------------------------------------------------
This function is used to check successful connection
has been made. return true if successful else false
PARAMETER: $PDO $connection->takes the pdo connection
return: it return true if the connection is okay else
return false if connection is bad
--------------------------------------------------*/
public function connectionStatus($connection)
{
if($connection !=false)
{
return true;
}
else
{
return false;
}
}
/*-----------------------------------------------
This function returns the connection error
message
return the connection ERROR MESSAGE...
this is idle to use if the connection has failed
-------------------------------------------------*/
public function getConnectionErrorMessage()
{
return '<b>CONNECTION ERROR MESSAGE::</b> '.$this->errorMessage;
}
/*-------------------------------------------------------------
This function returns the name of the database currently
connected
PARAMETER: $connection->PDO connection
return: The database name is echo if the connection is connected
else an error message is echo with possible solutions
*-------------------------------------------------------------------*/
public function getNameOfConnectedDatabase($connection)
{
//checks that the connection between server has been established prior
if($this->errorMessage == "Connection OK")
{
//fetching the connected database
$stmt = $connection->query('SELECT DATABASE() FROM DUAL');
$result = $stmt->fetch();
$dup ="";//temp fix to prevent showing duplication and space being print ...happens with number and symbol but string is fine
//display the result
foreach($result as $row)
{
if($dup!=$row)
{
$dup = $row;
echo '<b>CONNECTED DATABASE:: </b>'. $row;
}
}//end of for each
}//end of if connection passed
else
{
echo 'Error connecting to database!<br/> 1.Check your config.php to ensure that you entered the correct information.<br/>';
echo 'Alternative use the method connectionStatus($connection) to see whether you are succesful connected.';
}
}
/*-----------------------------------------------
This function performs insert-like data in a database.
returns true if the insert-like function was succesful
else error mesage is output
PERIMETERS: PDO connection->takes the connection
query->takes the prepared sql query
bindings, takes the binding statements(array)
table-> the table to insert the data in
values-> the values being insert
return: true is return if the data was successful insert
else error message is echo and false is return
*/
public function insert(PDO $connection,$columns,$bindings,$tables,$values)
{
$query ='INSERT INTO '.$tables.'('.$columns.')VALUES('.$values.')';
$stmt = $connection->prepare($query);
try
{
$stmt->execute($bindings);
return true;
}
catch(PDOException $e)
{
echo '<br/>ERROR: '.$e->getMessage().'<br/>';
return false;
}
}
/*--------------------------------------------------------------------------------------------------------------
This function read/select data from database
returns the PDO stmt if the statement executed else
echo error message
PARAMETER : $connection-> takes the PDO connection
$columns-> columns of data that you want to select, can be specific columns such as foo,foo or *
$binding-> takes the bind statement array
$tables-> table to select the data from
$where-> takes specific where insturction such as 'where id =:id' or can be blank if no specific where clause ie. $where=""
return: PDO stmt if the select is successful else a false is return.. if there are errors with the syntax it will be echo
-----------------------------------------------------------------------------------------------------------------*/
public function select( PDO $connection,$columns,$bindings,$tables,$where)
{
$query = 'SELECT '.$columns.' FROM '.$tables.' '.$where.'';
//$query='SELECT * FROM admin';
$stmt = $connection->prepare($query);
try
{
//execute depends on where clause statement if null or not
if($where=='')
{
$stmt->execute();
}
else
{
$stmt->execute($bindings);
}
return $stmt;
}
catch(PDOException $e)
{
echo '<br/>ERROR: '.$e->getMessage().'<br/>';
return false;
}
}//end of select
/* This functions enable the ability to add advance query such as join, subquery, coorelated query, non-correlated query and all other advanced queries
parameters:
$query-> the sql query
$binding-> the binding paramters
Returns a PDO stmt if the statement was succeeded.
*/
public function advanceQuery($query, $binding)
{
$stmt = $connection->prepare($query);
try
{
$stmt->execute($binding);
return $stmt;
}
catch(PDOException $e)
{
echo '<br/>ERROR: '.$e->getMessage().'<br/>';
return false;
}
}
/*-----------------------------------------
This function deletes... returns the stmt if
it was succesful delete else echo error message
if there is error in the syntax or such like
PARAMETER: $binding-> takes the bind statement array
$tables-> table to delete the data from
$where-> takes specific where insturction such as '$where = id:=id'
$connection->takes the pdo connection
return: true if data is delete else false. if there are error it will be echo
*/
public function delete( PDO $connection,$bindings,$tables,$where)
{
$query = 'DELETE FROM '.$tables.' Where '.$where. ' ';
//$query ='DELETE FROM TABLE WHERE id = : some ';
$stmt = $connection->prepare($query);
try
{
$stmt->execute($bindings);
return true;
}
//failed
catch(PDOException $e)
{
echo '<br/>ERROR: '.$e->getMessage().'<br/>';
return false;
}
}//end of delete
/*----------------------------------------------------------------------------------------------------------------
This function update... returns the stmt if
it was succesful delete else echo error message
if there is error in the syntax or such like
PARAMETER: $binding-> takes the bind statement array
$tables-> table to update
$where-> takes specific where insturction such as '$where = id:=id'
$connection->takes the pdo connection
$set-> take the columns to be set such as $set ='idnum = :updateNum';
return: true if the update was succesful else false... if there is error it will be echo automatically
*-----------------------------------------------------------------------------------------------------------------*/
public function update(PDO $connection, $bindings, $table, $set,$where)
{
$query = 'UPDATE '.$table.' SET '.$set.' WHERE '.$where. ' ';
$stmt = $connection->prepare($query);
try
{
$stmt->execute($bindings);
return true;
}
//failed
catch(PDOException $e)
{
echo '<br/>ERROR: '.$e->getMessage().'<br/>';
return false;
}
}
/*---------------------------------------------------------------------------------------------------------------------------
This is a function to generate random strings
This can be number only or string only or special character or mix of all or two of the three. you decide.
PARAMETER: $length-> the total length of random strings to generate
$includeNum-> takes "yes" or "no" whether you want to include a number in the generated string
$includeSpecialChar->take "yes" or "no" whether you want to include special characters in the generate string
$includeString->take "yes" or "no" if you want to include string in the generated string.
return: random generated string;
*-------------------------------------------------------------------------------------------------------------------------------*/
public function createRandomGenerate($length,$includeSpecialChar,$includeNum,$includeString)
{
$randomGenerated='';
$char='';
//different things that can be generated
$string ='ABCDEFGHIJKLMNOPQRSTUVWXYZabdefghijklmnopqrstuvwxyz';
$num = '0123456789';
$specialCharacter = '@#$&!,.?~-_*';
//ensure that $length is numeric
if(!is_numeric($length))
{
echo '<br/> ERROR: The parameter $length must be a int.<br/> ';
}
//ensure the user do not leave specialCharacter or num blank
if($includeNum=="" || $includeSpecialChar=="" || $includeString=="")
{
echo '<br/>ERROR: The parameter $includeSpecialChar or $includeNum or $includeString cannot be blank.<br/> ';
}
else
{
//the user wish to add strings
if( strcasecmp ( $includeString , 'yes' )==0 )
{
$char.=$string;
}
//the user wish to add numbers
if( strcasecmp ( $includeNum , 'yes' )==0 )
{
$char.=$num;
}
//the user wish to add special characters
if( strcasecmp ( $includeSpecialChar , 'yes' )==0 )
{
$char.=$specialCharacter;
}
//begin the randomize code
srand((double)microtime()*1000000);
$i=1;
while($i<=$length)
{
$randNum = rand() % strlen($char);//random between the length of the $char
$temp = substr($char,$randNum,1);
//temp fix...prevent temp from adding blank
if($temp!="")
{
$randomGenerated.=$temp;
$i++;
}
}
return $randomGenerated;
}
}//end of random generated function
/*----------------------------------------------------------------------------------------
Function to genereate a secured hash password that has been hashed using crypt.
procedure: a salt key is generated using a md5 and the user name in a n time loop.
after the salt key is generated it is use in aid in hashing the password
using crypt($password,$salt)
Parameter: NUM-> NUMBER OF TIME TO loop a md5
salt->A UNIQUE SALT KEY
$username->takes the username
$password->takes the password
returns a crypt password that has been hashed in md5 then finally crypt
*--------------------------------------------------------------------------------------------*/
public function generateSecurePasswordHash($num,$salt,$username,$password)
{
//ensure that $num is a int
if(!is_numeric($num))
{
echo '<br/>Error: The parameter $num in generateSecurePasswordHash function must be an int';
}
//password is numeric
else
{
//default values
$i = 0;
$md5Hash='';
$securedHash="";
//creating a md5 hash n times
while($i < $num)
{
$md5Hash.=md5(strtolower($username));
//echo '<br/> Generating MD5 :'.$md5Hash.'<br/>';
$i++;
}//end of while
//adding the generated md5 to make a salt key
$salt = $salt.$md5Hash;
//echo '<br/> Generating salt :'.$salt.'<br/>';
//genereating a bcrypt hashed password
$securedHash = crypt($password,$salt);
$securedHash = substr($securedHash,30);
return $securedHash;
}
}//end of generating hash function
/**------------------------------------------------------------------------------------------------------------------------------
This function validate whether a login credential is
correct....
PARAMETERS: username->take the user name
password->takes the password
table->take the table that contain the user credentials
columns->takes the columns that contains the username and password
binding->binding statment array
where->takes the where statement
return a pdo stmt if the connection is validate else return false. if there are any error it will automatically echo
*---------------------------------------------------------------------------------------------------------------------------------**/
public function isCredentialValid($username,$password,$tables,$columns,$bindings,$where)
{
//ensure that the connection has been set prior
$connection = $this->connect();
//ensure that the variables exist.
if( (isset($username)) || (isset($password)) || (isset($table)) || (isset($columns)) || (isset($bindings)) || (isset($where)) )
{
//ensure that the connection has been proper configured
if($this->connectionStatus($connection) ==true)
{
//echo '<br/> connection Successful ! ';
//ensure that the requirement parameters are not blanked
if($username!="" && $password!="" && $tables!="" && $columns!="" && $bindings!="" && $where!="")
{
//echo '<br/> Passed ';
$result = $this->select($connection,$columns,$bindings,$tables,$where);
//check if result has no errors and has record
if($result!=false)
{
//has record hence return the results in form of pdo $stmt
if($result->rowCount() > 0)
{
//echo '<br/> data found!';
//it is a possible the the user will need every columns from this table so let us return all
$column ='*';
$result = $this->select($connection,$columns,$bindings,$tables,$where);
return $result;
}
//else return false as no crediential match
else
{
return false;
}//end for return false if crediential doenst match
}
}//end of if all requirement are not blanked
//output this message is there are any blank parameters
else
{
echo '<br/>Error: All parameters in the function isCredentialValid are required.<br/>';
echo '<br/>Error: The correct format is "isCredentialValid($username,$password,$tables,$columns,$bindings,$where)" ';
}
}
//the connection is not proper configured
else
{
echo '<br/> ERROR: Your server is not connected to the database! Check to ensure that you have set your config.php with the correct information.<br/>';
}
}
//echo this if the user didnt included any parameter at all ie isCredentialValid()
else
{
echo '<br/>Error: The correct format is "isCredentialValid($username,$password,$tables,$columns,$bindings,$where)" ';
}
}//end of isCredentialValid function
/*------------------------------------------------------------------------------------
This is a function to get the name of all Parameter for a function within
this class.. this can be helpful if one is not sure what parameter are
necessary for a method
return a string of all parameter of a functin
*-------------------------------------------------------------------------------------------*/
public function get_func_argNames($funcName)
{
$parameters="";
//get the file
$file = file_get_contents('libraryClass.php');
//echo "file is ".$file;
//search for the specific function
$pos = strpos($file,$funcName);
if($pos!=false)
{
$i=0;
//find the first occurance of the open brace after the function
$open = strpos($file,'(',$pos);
//loop until we get to the end of the brace
$i=$open+1;//move over from the open brace and start getting parameter names
while($file[$i]!=')')
{
$parameters.=$file[$i];
$i++;
}
return $parameters;
}
else
{
echo '<br/>ERROR: '.$funcName.' is not a function <br/>';
}
}
/*--------------------------------------------------------------
This function returns name of all available methods
------------------------------------------------------------------*/
public function getMethods()
{
echo '<b><br/>AVAILABLE METHODS :</b><br/>';
echo '=====================<br/>';
$methods = get_class_methods($this);
foreach($methods as $individual)
{
if($individual!='_construct')
{
//$individual = trim($individual);
$getparm = 'public function '.$individual;
echo '<br/>'.$individual.'('.$this->get_func_argNames($getparm).')<br/>';
//print_r($this->get_func_argNames($individual));
}
}
}
/*--------------------------------------------------------------------------------------------------
This method is use to echo the data for a variable
thus eliminate the need for multi echo when testing to see
what each variables has... all one have to do is supply the parameter with
some arguments. when invoking you may supply any number of parameters.
This eliminate the need to write a echo statement for each variables to see what data they contain
This function will echo both the variable name in the form of $somevariable and the data it possess
for example if you have a $foo='hello world'; it will echo:
"Data for $foo is : hello world"
*----------------------------------------------------------------------------------------------------*/
public function getDataOfVariables()
{
//function to get the argument names within this method
function get_func_argNames($funcName)
{
$parameters="";
//get the file
$file = file_get_contents(basename($_SERVER['PHP_SELF']));
//echo "file is ".$file;
//search for the specific function
$pos = strpos($file,$funcName);
if($pos!=false)
{
$i=0;
//find the first occurance of the open brace after the function
$open = strpos($file,'(',$pos);
//loop until we get to the end of the brace
$i=$open+1;//move over from the open brace and start getting parameter names
while($file[$i]!=')')
{
$parameters.=$file[$i];
$i++;
}
return $parameters;
}
else
{
echo '<br/>ERROR: '.$funcName.' is not a function <br/>';
}
}//end og get_function_argument name
//execute
$generatedParam = split("," , get_func_argNames('getDataOfVariables'));//get each parameters and split them based on the ','
$args = func_get_args(); //get the real value of every arguments
//echo 'Number of arguments :'. $numargs;
//loop and display the data
echo'<br/>Displaying values for getDataOfVariables('.get_func_argNames('getDataOfVariables').')';
echo'<br/>====================================================================================';
for($i=0; $i < count($generatedParam); $i++)
{
echo "<br/> Data for $generatedParam[$i] is : $args[$i]";
}
}//end of get data variable
/* if_email() function checks weather Given String is a Valid Email Address Or Not
Returns TRUE if String is valid Email
Returns False if String is not valid Email
@author argunner
http://github/argunner
*/
public function if_email($email){
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
return false;
}
else
{
return true;
}
}
/* if_contain_special_chars() checks weather Given String Contains special chars or not.
Returns true if does not contain special chars
Returns flase if contain special chars
@author argunner
http://github/argunner
*/
public function if_contain_special_chars($string){
if (!preg_match('/[^A-Za-z0-9]/', $string)) // '/[^a-z\d]/i' should also work.
{
//does not contain special chars
return true;
}
else
{
return false;
}
}
/* if_only_digit() checks weather Given String Contains Only Digits Or Not.
Returns true if contains only digits
Returns flase if contains anything other than digit.
@author argunner
http://github/argunner
*/
public function if_only_digit($string){
if(!preg_match('/[^0-9]/',$string))
{
return true;
}
else{
return false;
}
}
/* if_digit() checks weather Given String Contains A Digits Or Not.
Returns true if contains a digit
Returns flase if contains anything other than digit.
@author argunner
http://github/argunner
*/
public function if_digit($string){
if(!preg_match('/[0-9]/',$string))
{
return true;
}
else{
return false;
}
}
/* if_only_alpha() checks weather Given String Contains Only Alphabet Or Not.
Returns true if contains only alpha
Returns flase if contains anything other than alpha.
@author argunner
http://github/argunner
*/
public function if_only_alpha($string){
if(!preg_match('/[^a-z]/',$string))
{
return true;
}
else{
return false;
}
}
/* if_alpha() checks weather Given String Contains an Alphabet Or Not.
Returns true if contains only alpha
Returns flase if contains anything other than alpha.
@author argunner
http://github/argunner
*/
public function if_alpha($string){
if(!preg_match('/[a-z]/',$string))
{
return true;
}
else{
return false;
}
}
/* check_length() checks weather Given String is Under Limit or Not
Returns true if String is Under Limit
Returns flase if String Exceeds Limit.
@author argunner
http://github/argunner
*/
public function check_length($string,$limit){
if( strlen($string) <= $limit){
return true;
}
else{
return false;
}
}
}//end of library class
?>