-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTame.php
1416 lines (1246 loc) · 39.2 KB
/
Tame.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
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Tamedevelopers\Support;
use Tamedevelopers\Support\Str;
use Tamedevelopers\Support\Server;
use Tamedevelopers\Support\Traits\TameTrait;
/**
* @see \Tamedevelopers\Support\Str
* @see \Tamedevelopers\Support\Server
* @see \Tamedevelopers\Support\Time
*/
class Tame {
use TameTrait;
/**
* Count
* @var int
*/
protected const COUNT = 0;
/**
* Kilobytes Value
* @var int
*/
protected const KB = 1024;
/**
* Megabytes Value
* @var int
*/
protected const MB = 1024 * self::KB;
/**
* Gegabytes Value
* @var int
*/
protected const GB = 1024 * self::MB;
/**
* Salter String
* @var string
*/
private const PBKDF2_SALT = "\x2d\xb7\x68\x1a";
/**
* Echo `json_encode` with response and message
*
* @param int $response
* @param mixed $message
* @return mixed
*/
static public function echoJson(int $response = 0, $message = null)
{
echo json_encode(['response' => $response, 'message' => $message]);
}
/**
* Check IF URL Exists
*
* @param string $url
* @return bool
*/
static public function urlExists($url)
{
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
// Execute cURL and get the HTTP status code
$httpCode = curl_exec($ch);
// Close cURL handle
curl_close($ch);
return $httpCode && preg_match('/\b200\b/', $httpCode);
}
/**
* Check IF Internet is Available
*
* @return bool
*/
static public function isInternetAvailable()
{
return self::urlExists('https://www.google.com');
}
/**
* Check if Class Exists
*
* @param string $class
* @param Closure|null $closure
* @return void
*/
static public function class_exists($class, $closure = null)
{
if(class_exists($class)){
if(self::isClosure($closure)){
$closure();
}
}
}
/**
* Check if at least one class exists
*
* @param string|array $classNames Array of class names to check
* @return bool True if at least one class exists, false otherwise
*/
static public function checkAnyClassExists(...$classNames)
{
$classNames = Str::flattenValue($classNames);
foreach ($classNames as $name) {
if (class_exists($name)) {
return true;
}
}
return false;
}
/**
* PHP Version Compare
*
* @param string $version
* @return bool
*/
static public function versionCompare($version)
{
if(version_compare(PHP_VERSION, $version, '>=')){
return true;
}
return false;
}
/**
* Check if headers have been sent.
* This function checks if headers have been sent and outputs information about where headers were sent.
* If headers are sent, it outputs the file and location where the headers were sent and terminates the script.
*/
static public function HeadersSent()
{
$file = null;
$location = null;
if (headers_sent($file, $location)) {
// Headers have been sent, output the file and location
echo "Headers sent in file: {$file} <br/> Location: {$location} <br/>";
die('Script terminated after detecting headers sent.');
}
}
/**
* include if file exist
*
* @param string $path
* - [base path will be automatically added]
*
* @return void
*/
static public function include($path)
{
$fullPath = self::getBasePath($path);
if(self::exists($fullPath)){
include $fullPath;
}
}
/**
* include once if file exist
*
* @param string $path
* - [base path will be automatically added]
*
* @return void
*/
static public function includeOnce($path)
{
$fullPath = self::getBasePath($path);
if(self::exists($fullPath)){
include_once $fullPath;
}
}
/**
* require if file exist
*
* @param string $path
* - [base path will be automatically added]
*
* @return void
*/
static public function require($path)
{
$fullPath = self::getBasePath($path);
if(self::exists($fullPath)){
require $fullPath;
}
}
/**
* require_once if file exist
*
* @param string $path
* - [base path will be automatically added]
*
* @return void
*/
static public function requireOnce($path)
{
$fullPath = self::getBasePath($path);
if(self::exists($fullPath)){
require_once $fullPath;
}
}
/**
* Convert Bytes to Units
*
* @param float|int $bytes
* @param bool $format
* @param string|null $gb
* @param string|null $mb
* @param string|null $kb
*
* @return string
*/
static public function byteToUnit($bytes = 0, $format = true, $gb = 'GB', $mb = 'MB', $kb = 'KB')
{
$bytes = (int) $bytes;
if ($bytes >= 1073741824){
$bytes = round(($bytes / 1073741824)) . $gb;
} elseif ($bytes >= 1048576){
$bytes = round(($bytes / 1048576)) . $mb;
} elseif ($bytes >= 1024){
$bytes = round(($bytes / 1024)) . $kb;
}
return $format ? $bytes : Str::lower($bytes);
}
/**
* Convert Megabytes to bytes
*
* @param string|int|float $size
* @return int
*/
static public function sizeToBytes($size = '1mb')
{
$size = Str::lower(str_replace(' ', '', (string) $size));
// Match the size and unit from the input string
if (preg_match('/^(\d+(\.\d+)?)([kmg]b?)?$/', $size, $matches)) {
$value = (float) $matches[1];
$unit = isset($matches[3]) ? $matches[3] : '';
switch ($unit) {
case 'kb':
return (int) ($value * self::KB);
case 'mb':
return (int) ($value * self::MB);
case 'gb':
return (int) ($value * self::GB);
default:
// If no unit specified, default to megabytes
return (int) ($value * self::MB);
}
}
// Invalid input
$size = (int) $size;
// check if input is greter than 1kb, else default to 1KB
return $size > self::KB ? $size : $size * self::KB;
}
/**
* Get file modification time
*
* @param string|null $path
* - [full path to file is required]
*
* @return int|bool
*/
static public function fileTime($path = null)
{
return self::getFiletime($path);
}
/**
* Count the numbers between $index and $amount (inclusive) that are divisible by $index.
*
* @param int $index The divisor.
* @param int $amount The range end.
* @return int
* - The count of divisible numbers.
*/
static public function countDivisibleNumbers($index = 100, $amount = 0)
{
if ($index <= 0 || $amount < $index) {
return 0;
}
// Calculate the count of divisible numbers
return floor($amount / $index);
}
/**
* Calculate the result of raising a base to an exponent.
*
* @param float|int $base The base number.
* @param float|int $exponent The exponent to raise the base to.
* @return float|int
* - The result of the exponentiation.
*/
static public function calculateExponent($base = 0, $exponent = 0)
{
return pow($base, $exponent);
}
/**
* Getting weight calculation
*
* @param mixed $length
* - float|int
*
* @param mixed $width
* - float|int
*
* @param mixed $height
* - float|int
*
* @param bool $format
* - [optional] Default is `true` and round using provided or default decimal of `0.5`
* if set to false, it return converted value without rounding
*
* @param int|float|string $decimal
* - [optional] Default is `0.5` value to round to if $format is `true`
*
* @return int
*/
static public function calculateVolumeWeight($length = 0, $width = 0, $height = 0, ?bool $format = true, $decimal = 0.5)
{
$value = ((float) $length * (float) $width * (float) $height) / 5000;
return $format ?
self::roundToDecimal($value, $decimal)
: $value;
}
/**
* Getting weight calculation
*
* @param mixed $length
* - float|int
*
* @param mixed $width
* - float|int
*
* @param mixed $height
* - float|int
*
* @param bool $format
* - [optional] Default is `true` and round using provided or default decimal of `0.1`
* if set to false, it return converted value without rounding
*
* @param int|float|string $decimal
* - [optional] Default is `0.1` value to round to if $format is `true`
*
* @return int
*/
static public function calculateCubicMeterWeight($length = 0, $width = 0, $height = 0, ?bool $format = true, $decimal = 0.1)
{
$value = ((float) $length * (float) $width * (float) $height) / 1000000;
return $format ?
self::roundToDecimal($value, $decimal)
: $value;
}
/**
* Getting actual weight length
*
* @param mixed $length
* - float|int
*
* @param mixed $width
* - float|int
*
* @param mixed $height
* - float|int
*
* @param mixed $weight
* - float|int
*
* @param bool $format
* - [optional] Default is `true` and round using provided or default decimal of `0.5`
* if set to false, it return converted value without rounding
*
* @param int|float|string $decimal
* - [optional] Default is `0.5` value to round to if $format is `true`
*
* @return int
*/
static public function getBetweenBoxLengthAndWeightInKg($length = 0, $width = 0, $height = 0, $weight = 0, ?bool $format = true, $decimal = 0.5)
{
$weight = (float) $weight;
$dimensional_weight = self::calculateVolumeWeight($length, $width, $height, $format, $decimal);
if($dimensional_weight > $weight){
return $dimensional_weight;
}
return self::roundToDecimal($weight, $decimal);
}
/**
* Getting actual weight length
*
* @param mixed $length
* - float|int
*
* @param mixed $width
* - float|int
*
* @param mixed $height
* - float|int
*
* @param mixed $weight
* - float|int
*
* @param bool $format
* - [optional] Default is `true` and round using provided or default decimal of `0.1`
* if set to false, it return converted value without rounding
*
* @param int|float|string $decimal
* - [optional] Default is `0.1` value to round to if $format is `true`
*
* @return int
*/
static public function getBetweenBoxLengthAndWeightInCMB($length = 0, $width = 0, $height = 0, $weight = 0, ?bool $format = true, $decimal = 0.1)
{
$weight = (float) $weight;
$dimensional_weight = self::calculateCubicMeterWeight($length, $width, $height, $format, $decimal);
if($dimensional_weight > $weight){
return $dimensional_weight;
}
return self::roundToDecimal($weight, $decimal);
}
/**
* Getting actual weight between Volume/Dimensional weight and Weight in `kg`
*
* @param mixed $dimensional_weight
* - float|int
*
* @param mixed $actual_weight
* - float|int
*
* @return int
*/
static public function getBetweenDimensionalWeightAndWeightInKg(mixed $dimensional_weight = 0, mixed $actual_weight = 0)
{
$actual_weight = (float) $actual_weight;
$dimensional_weight = (float) $dimensional_weight;
if($dimensional_weight > $actual_weight){
return $dimensional_weight;
}
return $actual_weight;
}
/**
* Getting actual weight between Volume/Dimensional weight and Weight in `CBM`
*
* @param mixed $dimensional_weight
* - float|int
*
* @param mixed $actual_weight
* - float|int
*
* @return int
*/
static public function getBetweenDimensionalWeightAndWeightInCBM(mixed $dimensional_weight = 0, mixed $actual_weight = 0)
{
return self::getBetweenDimensionalWeightAndWeightInKg($dimensional_weight, $actual_weight);
}
/**
* Round to decimal point
*
* @param mixed $value
* - float|int
*
* @param mixed $decimal
* - float|int|string
*
* @return int
*/
static public function roundToDecimal(mixed $value = 0, mixed $decimal = 0.5)
{
$decimal = (float) $decimal;
if($decimal == self::COUNT) $decimal = 0.1;
if($value == self::COUNT) return $value;
// Perform the rounding
$result = ceil($value / $decimal) * $decimal;
// return round($value / $decimal, 1, PHP_ROUND_HALF_UP) * $decimal;
return round($result, 1);
}
/**
* Set Checkbox Value
*
* @param mixed $status
* @param bool $reverse_order
* @return array
*/
static public function setCheckbox($status = null, ?bool $reverse_order = false)
{
$order = ['on' => 1, 'off' => 0];
if($reverse_order){
$order = ['on' => 0, 'off' => 1];
}
if($status != '0' && $status != '1'){
return ['status' => null, 'value' => null];
}
if($status == '1'){
return ['status' => "checked='checked'", 'value' => $order['on']];
}
return ['status' => null, 'value' => $order['off']];
}
/**
* Convert Kilograms to Grams
*
* @param float|int $weight
* @return int
*/
static public function kgToGrams(float|int $weight = 0)
{
return $weight == 0 ? 0 : round(($weight * 1000) + 1, 2);
}
/**
* Convert Grams to Kilograms
*
* @param float|int $weight
* @return int
*/
static public function gramsToKg(float|int $weight = 0)
{
return $weight == 0 || null ? 0 : round((($weight - 1) / 1000), 2);
}
/**
* Calculation Percentage between numbers
*
* @param float|int $total
* @param float|int $newNumber
* @return int
*/
static public function calPercentageBetweenNumbers(float|int $total = 0, float|int $newNumber = 0)
{
// default
$decreaseValue = self::COUNT;
if($total > $newNumber){
$decreaseValue = ($newNumber / $total) * 100;
} else{
if($total != self::COUNT && $newNumber != self::COUNT){
$decreaseValue = ($total / $newNumber) * 100;
} elseif($newNumber != self::COUNT){
$decreaseValue = ($newNumber * 100) / $newNumber;
}
}
return $decreaseValue;
}
/**
* Check if array has duplicate value
*
* @param array $data
* @return bool
* - true|false
*/
static public function isArrayDuplicate(?array $data = [])
{
return Str::arrayDuplicate($data);
}
/**
* Check if all values of array is same
*
* @param array $data
* @return bool
* - true|false
*/
static public function isArraySame(?array $data = [])
{
return Str::arraySame($data);
}
/**
* For sorting array
*
* @param array $data
* @param string $type
* - [rsort|asort|ksort|arsort|krsort|sort]
*
* @return array
*/
static public function sortArray(?array &$data = [], ?string $type = 'sort')
{
// Validate that $data is an array
if (!is_array($data)) {
return [];
}
// Perform sorting based on the specified type
switch ($type) {
case 'rsort':
rsort($data); // Sort arrays in descending order
break;
case 'asort':
asort($data); // Sort associative arrays in ascending order, according to the value
break;
case 'ksort':
ksort($data); // Sort associative arrays in ascending order, according to the key
break;
case 'arsort':
arsort($data); // Sort associative arrays in descending order, according to the value
break;
case 'krsort':
krsort($data); // Sort associative arrays in descending order, according to the value
break;
default:
sort($data); // Sort arrays in ascending order
break;
}
return $data;
}
/**
* For sorting muti-dimentional array
*
* @param array $data
* @param string|null $key
* @param string $type
* - [asc|desc|snum]
*
* @return array
*/
static public function sortMultipleArray(?array &$data = [], $key = null, ?string $type = 'asc')
{
// Check if $data is an array and not empty
if (!is_array($data) || empty($data)) {
return [];
}
// Check if $key is provided
// If $key is not provided, return without sorting
if (is_null($key)) {
return $data;
}
// Extract values of the specified key from each sub-array
$id = array_column($data, $key);
// Ensure $id and $data have the same size before sorting
if (count($id) !== count($data)) {
return;
}
switch ($type) {
case 'desc':
array_multisort($id, SORT_DESC, $data); //sort associative arrays in descending order
break;
case 'snum':
array_multisort($id, SORT_NUMERIC, $data); //sort associative arrays in numeric order
break;
default:
array_multisort($id, SORT_ASC, $data); //sort arrays in ascending order
break;
}
return $data;
}
/**
* Clean phone string
*
* @param string|null $phone
*
* @param bool $allow --- Default is true
* - [optional] to allow int format `+` (before number)
*
* @return string
*/
static public function cleanPhoneNumber($phone = null, ?bool $allow = true)
{
$phone = Str::trim($phone);
$phone = str_replace([' ', '-'], '', $phone);
$phone = str_replace(['(', ')'], '', $phone);
if(Str::contains('+', $phone)){
$phone = str_replace('+', '', $phone);
}
if($allow){
$phone = "+{$phone}";
}
return $phone;
}
/**
* Remove special characters while allowing all languages.
*
* @param string|null $string
* @return string
* - The cleaned string or null if the input is empty.
*/
static public function removeSpecialChars($string = null)
{
return self::cleanTagsForURL($string);
}
/**
* Clean tags for use in URLs, considering multiple language modules.
*
* @param string|null $string The input string to clean.
* @return string The cleaned string.
*/
static public function cleanTagsForURL($string = null)
{
// Remove unwanted characters from the string
$string = preg_replace('/[^\p{L}\p{N}\s]/u', '', Str::trim($string));
return Str::trim($string);
}
/**
* Hash String
*
* @param string|null $string
* @param int $length
* @param string $type
* @param int $interation
* @return void
*/
static public function stringHash($string = null, $length = 100, $type = 'sha256', $interation = 100)
{
return hash_pbkdf2($type, mt_rand() . $string, self::PBKDF2_SALT, $interation, $length);
}
/**
* Shorten String to Given Limit
* @link https://codeflarelimited.com/blog/php-shorten-string-with-three-dots/
*
* @param mixed $string
* @param mixed $limit
* @param mixed $replacer
* [optional]
*
* @return string
*/
static public function shortenString($string = null, $limit = 50, $replacer = '...')
{
// clean string before begin
$string = strip_tags(Str::trim($string));
$string = str_replace("、", '', $string);
$string = Str::trim(str_replace(PHP_EOL, ' ', $string));
if(mb_strlen($string) > $limit) {
return mb_strcut($string, 0, (int) $limit) . $replacer;
}
return $string;
}
/**
* Decode entity html strings
*
* @param string|null $string
* @return string
*/
static public function html($string = null)
{
return html_entity_decode(Str::trim($string), ENT_HTML5, 'UTF-8');
}
/**
* Convert string to clean text without html tags
*
* @param string|null $string
*
* @return string
* - strip all tags from string content
*/
static public function text($string = null)
{
return strip_tags(Str::trim($string));
}
/**
* Filter sanitize string
*
* @param string|null $string
* @return string
*/
static public function filter_input($string = null)
{
return htmlspecialchars(Str::trim($string), ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Format number to nearest thousand
* @link https://code.recuweb.com/2018/php-format-numbers-to-nearest-thousands/
*
* @param float|int $number
* @return void
*/
static public function formatNumberToNearestThousand(float|int $number = 0)
{
if( $number >= 1000 ) {
$x = round($number);
$x_number_format = number_format($x);
$x_array = explode(',', $x_number_format);
//[t(trillion) - p(quadrillion) - e(quintillion) - z(sextillion) - y(septillion)]
$x_parts = array('k', 'm', 'b', 't', 'p', 'e', 'z', 'y');
$x_count_parts = count($x_array) - 1;
$x_display = $x;
$x_display = $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : '');
// if amount in array
if(in_array($x_count_parts - 1, array_keys($x_parts))){
$x_display .= $x_parts[$x_count_parts - 1];
}
return $x_display;
}
return $number;
}
/**
* File exist and not a directory
*
* @param string|null $path
* - [full path to file]
*
* @return bool
*/
static public function exists($path = null)
{
return !is_dir($path) && file_exists($path);
}
/**
* Unlink File from Server
*
* @param string $pathToFile
* - [full path to file is required]
*
* @param string|null $fileName
* - [optional] file name. <avatar.png>
*
* @return void
*/
static public function unlink(string $pathToFile, $fileName = null)
{
$fullPath = self::stringReplacer($pathToFile);
if(self::exists($fullPath)){
if(basename($fullPath) != basename((string) $fileName)){
@unlink($fullPath);
}
}
}
/**
* Convert json data to array|object
*
* @param string $path
* - [full path to destination]
*
* @param bool $format
* - [optional] `true` will convert to an array
*
* @return array|object|null
*/
static public function convertJsonData($path, $format = true)
{
if(self::exists($path)){
return json_decode(file_get_contents($path), $format);
}
}
/**
* Save Data to Path as a Json Object
*
* @param string $destination
* - [full path to destination]
*
* @param mixed $data
* @param bool $type
* - Saveas[JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE]
*
* @return bool
*/
static public function saveDataAsJsonObject(string $destination, mixed $data, ?bool $type = true)
{
// Choose the JSON encoding format
$format = $type ? JSON_PRETTY_PRINT : JSON_UNESCAPED_UNICODE;
// check or convert data to an array
if(!is_array(!$data)){
$data = Server::toArray($data);
}
// try to read destination
$fopen = fopen($destination, "w");
// must be a type of resource
if(is_resource($fopen)){
fwrite($fopen, json_encode($data, $format));
fclose($fopen);
return true;
}
return false;
}
/**
* Save File From Url
*
* @param string $url
* - [url path] <https://google.com/file.pdf>
*
* @param string $destination
* - [full path to destination]
*
* @return string|null
*/
static public function saveFileFromURL($url, $destination)
{
// Check if the destination directory exists, if not, create it
$directory = dirname($destination);
if (!is_dir($directory)) {
mkdir($directory, 0755, true);
}
// Try to open the file and save its contents
$fileContents = @file_get_contents($url);
if ($fileContents === false) {
// Handle error, e.g., log it
error_log("Failed to fetch contents from $url");
return null;
}
// Try to write the contents to the destination file
$writeResult = @file_put_contents($destination, $fileContents);
if ($writeResult === false) {
// Handle error, e.g., log it
error_log("Failed to write contents to $destination");
return null;
}
// Extract the file name from the URL and return it
$fileName = basename($destination);
return $fileName;
}
/**
* Read PDF TO Browser