1+ <?php
2+
3+ /* File Controller Class */
4+ class FileController {
5+
6+ function __construct () { }
7+
8+ /* Check Method Function */
9+ function fileController ($ method ) {
10+ switch ($ method ) {
11+
12+ /* POST Method */
13+ case "POST " :
14+
15+ /* Image Allowed Extension */
16+ $ allowed_extension = array ("png " , "jpg " ,"jpeg, webp " );
17+
18+ /* Get Image File Extension */
19+ $ file_extension = pathinfo ($ _FILES ["upload " ]["name " ], PATHINFO_EXTENSION );
20+
21+ /* Check Extension */
22+ if (!in_array (strtolower ($ file_extension ),$ allowed_extension )){
23+ echo json_encode (array ('status ' =>'Fail ' , 'error ' =>'Please upload png, jpg, jpeg and webp file. ' ));
24+ die ();
25+ }
26+
27+ /* Check File Size */
28+ if ($ _FILES ["upload " ]["size " ] > 1024 *1024 ){
29+ echo json_encode (array ('status ' =>'Fail ' , 'error ' =>'Please upload 1MB size file. ' ));
30+ die ();
31+ }
32+
33+ /* Upload File Path */
34+ $ url ="uploads/IMG_ " .uniqid ()."_ " .date ("GHisdmY " ).". " .$ file_extension ;
35+
36+ /* Upload File */
37+ if (move_uploaded_file ($ _FILES ['upload ' ]['tmp_name ' ], $ url )){
38+
39+ /* Check HTTPS */
40+ if (isset ($ _SERVER ['HTTPS ' ])){
41+ $ protocol = ($ _SERVER ['HTTPS ' ] && $ _SERVER ['HTTPS ' ] != "off " ) ? "https " : "http " ;
42+ }
43+ else { $ protocol = 'http ' ; }
44+
45+ /* Upload File Link */
46+ $ url = $ protocol .":// " .$ _SERVER ['SERVER_NAME ' ] ."/php-rest-api/ " .$ url ;
47+
48+ echo json_encode (array ('status ' =>'Success ' , 'message ' =>'File is successful uploaded. ' , 'file_url ' => $ url ));
49+
50+ }
51+ break ;
52+
53+ /* DELETE Method */
54+ case "DELETE " :
55+
56+ /* Recive Delete File URL */
57+ $ data = json_decode (file_get_contents ('php://input ' ), true );
58+
59+ /* Check HTTPS */
60+ if (isset ($ _SERVER ['HTTPS ' ])){
61+ $ protocol = ($ _SERVER ['HTTPS ' ] && $ _SERVER ['HTTPS ' ] != "off " ) ? "https " : "http " ;
62+ }
63+ else { $ protocol = 'http ' ; }
64+
65+ /* Remove Host Link in URL */
66+ $ url = str_replace ($ protocol .":// " .$ _SERVER ['SERVER_NAME ' ] ."/php-rest-api/ " , "" ,$ data ['upload ' ]);
67+
68+ /* Delete File */
69+ if (unlink ($ url )){
70+ echo json_encode (array ('status ' =>'Success ' , 'message ' =>'File is deleted. ' ));
71+ }
72+ break ;
73+
74+ default :
75+ echo json_encode (array ('status ' =>'Fail ' , 'error ' =>'Please use POST and DELETE Method for file. ' ));
76+
77+ }
78+ }
79+ }
80+
81+ ?>
0 commit comments