xeryas_inc.php:
<?php
class Posts {
public function last_file_about_name() : array {
$file_list = (scandir("../forumpasja_informatyki/"));
$arr = [];
// probably max aX, it: 9999999
foreach($file_list as $file) {
if(preg_match('@a[1-9][0-9]{1,6}.txt@', ($file))) {
$arr[] = $file;
}
}
//sort($arr, SORT_NATURAL); // what better?
return ($arr);
}
public function max_count($array1) {
return max(array_filter($array1, function($x) {
return ((int)substr($x, 1, strlen($x)-5));
}));
}
public function save_to_file(...$args) : bool {
$order_number = ($this->max_count($this->last_file_about_name()));
//$order_number = end($order_number);
var_dump($order_number);
$ex = explode(".txt", $order_number);
$order_number = ((int)substr($ex[0], 1)) + 1;
$order_number = "a".$order_number.".txt";
if($order_number === false) {
$order_number = "a1.txt";
}
if(!file_exists( $order_number )) {
$handler = fopen($order_number, "w+");
foreach($args as $arg) {
fwrite($handler, $arg . "\r\n");
}
return true;
} else {
$order_number++;
return false;
}
}
public function read_file() : array {
$txt = [];
foreach($this->last_file_about_name() as $content) {
$txt[] = file($content);
}
return $txt;
}
public function delete_file($file_name) : bool {
if(file_exists($file_name) && unlink($file_name)) {
return true;
} else {
return false;
}
}
}
// To nie jest kod "produkcyjny", tylko bardziej poglądowy.
?>
xeryas.php:
<body style="background: darkolivegreen;">
<form method="post" action="">
<input type="text" name="topic" />
<textarea name="topic_description">Description here...</textarea>
<input type="text" name="author" />
<input type="submit" name="save" />
</form>
<form method="post" action="">
<input type="text" name="file_delete" />
<input type="submit" name="delete" />
</form>
<?php
include_once("xeryas_inc.php");
$posts = new Posts();
if(!empty($_POST['topic']) && !empty($_POST['topic_description']) && !empty($_POST['author']) && isset($_POST['save'])) {
var_dump($posts->save_to_file($_POST['topic'], $_POST['topic_description'], $_POST['author']));
}
if(!empty($_POST['file_delete']) && isset($_POST['delete'])) {
var_dump($posts->delete_file($_POST['file_delete']));
}
?>
</body>
xeryas2.php:
<body style="background: darkolivegreen;">
<?php
include_once("xeryas_inc.php");
$posts = new Posts();
for($i=0;$i<count($posts->read_file());$i++) {
echo "<p><a href=\"?link={$i}\">".trim($posts->read_file()[$i][0])."</a>";
if(isset($_GET['link']) && $_GET['link'] == $i) {
echo trim($posts->read_file()[$i][1]);
}
echo "<span style='color: lightgreen;'>".trim($posts->read_file()[$i][2])."</span></p>";
}
?>
</body>
Podkreślam, nie jest to kod raczej produkcyjny, trzeba by trochę go poprawić, aby w miarę jako tako wyglądał.
Na tę chwilę nie wiem, czemu skrypt dokleja białe znaki. Żeby to zlikwidować musiałem użyć funkcji trim().