1 | <?php
|
---|
2 | /*
|
---|
3 | * Project: NodeMap2.0
|
---|
4 | * File: FileHandler.class.php
|
---|
5 | * Purpose: Checking and reading node files from the server
|
---|
6 | */
|
---|
7 |
|
---|
8 | class FileHandler {
|
---|
9 | private $filename;
|
---|
10 | private $handle;
|
---|
11 |
|
---|
12 | /*
|
---|
13 | * Function: __construct (constructor)
|
---|
14 | * Description: Handling with a node file
|
---|
15 | * Parameters: string $filename, string $mode
|
---|
16 | * Returns: true is we've succesfully opened the file, otherwise false
|
---|
17 | */
|
---|
18 | public function __construct($filename, $mode) {
|
---|
19 | $this->filename = $filename;
|
---|
20 |
|
---|
21 | try {
|
---|
22 | trigger_log(SYSLOG_DEBUG, 'Opening the file "' . $this->filename . '"', __FILE__, __LINE__);
|
---|
23 | $this->handle = fopen($this->filename, $mode);
|
---|
24 | } catch (Exception $err) {
|
---|
25 | trigger_log(SYSLOG_ERR, 'Reading from file "' . $this->filename . '" failed', __FILE__, __LINE__);
|
---|
26 | return false;
|
---|
27 | }
|
---|
28 |
|
---|
29 | return true;
|
---|
30 | }
|
---|
31 |
|
---|
32 | /*
|
---|
33 | * Function: read
|
---|
34 | * Description: Try to read the file we've opened in the constructor
|
---|
35 | * Parameters: -
|
---|
36 | * Returns: The content of the file if we can read from the file, otherwise false
|
---|
37 | */
|
---|
38 | public function read() {
|
---|
39 | $file = '';
|
---|
40 |
|
---|
41 | try {
|
---|
42 | trigger_log(SYSLOG_DEBUG, 'Reading from file "' . $this->filename . '"', __FILE__, __LINE__);
|
---|
43 | $file = stream_get_contents($this->handle);
|
---|
44 | } catch (Exception $err) {
|
---|
45 | trigger_log(SYSLOG_ERR, 'Reading from file "' . $this->filename . '" failed', __FILE__, __LINE__);
|
---|
46 | return false;
|
---|
47 | }
|
---|
48 |
|
---|
49 | return $file;
|
---|
50 | }
|
---|
51 |
|
---|
52 | /*
|
---|
53 | * Function: write
|
---|
54 | * Description: Try to write to the file we've opened in the constructor
|
---|
55 | * Parameters: string $data
|
---|
56 | * Returns: true if we can write to the file, otherwise false
|
---|
57 | */
|
---|
58 | public function write($data) {
|
---|
59 | trigger_log(SYSLOG_DEBUG, 'Writing file "' . $this->filename . '"', __FILE__, __LINE__);
|
---|
60 |
|
---|
61 | try {
|
---|
62 |
|
---|
63 |
|
---|
64 | fwrite($this->handle, $data);
|
---|
65 |
|
---|
66 |
|
---|
67 | } catch (Exception $err) {
|
---|
68 | trigger_log(SYSLOG_ERR, 'Couldn\'t write to file "' . $this->filename . '"', __FILE__, __LINE__);
|
---|
69 | return false;
|
---|
70 | }
|
---|
71 |
|
---|
72 | return true;
|
---|
73 | }
|
---|
74 |
|
---|
75 | public function __destruct() {
|
---|
76 | trigger_log(SYSLOG_DEBUG, 'Closing file "' . $this->filename . '"', __FILE__, __LINE__);
|
---|
77 | fclose($this->handle);
|
---|
78 | }
|
---|
79 | }
|
---|