ค้นหาข้อความและดึงค่าจาก Html Attribute เพื่อค้นหาไฟล์ในโฟลเดอร์
เพื่อลบไฟล์ที่ไม่เกี่ยวข้องหรือไม่มีในฐานข้อมูล จำเป็นต้องคิวรี่ค่าจากฐานข้อมูลแล้วค้นหาข้อความและดึงค่าจาก Html Attribute เพื่อค้นหาไฟล์ในโฟลเดอร์และทำการย้ายไฟล์จากโฟลเดอร์ไปยังอีกโฟลเดอร์ สามารถทำได้ดังนี้
.
Credit
https://www.itsolutionstuff.com/post/how-to-get-html-tag-attribute-value-in-phpexample.html
https://www.tutsmake.com/php-move-and-copy-file-from-one-folder-to-another/
.
<?php
$db_name = "DB_NAME";
$db_host = "127.0.0.1";
$db_user = "root";
$db_pass = "";
try {
$db_con = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_user, $db_pass);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db_con->exec("set names utf8");
} catch (PDOException $e) {
echo $e->getMessage();
}
$stmt = $db_con->prepare("SELECT * FROM news ORDER BY id DESC");
$stmt->execute();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (preg_match('/.pdf|.xls|.docx|.jpg|.JPG|.rar|.zip/i', $rows['details'])) {
$htmlEle = "<html><body>{$rows['details']}</body></html>";
$domdoc = new DOMDocument();
$domdoc->loadHTML($htmlEle);
$xpath = new DOMXpath($domdoc);
$query = "//a[@href]";
$entries = $xpath->query($query);
foreach ($entries as $p) {
// echo urldecode($p->getAttribute('href')), PHP_EOL;
$source = substr(urldecode($p->getAttribute('href')), 1);
$destination = 'files/';
if (file_exists($source)) {
// echo "file already exists.<br>";
if (rename($source, $destination . basename($source))) {
echo '<span style="color:green;">File was successfully moved</span> ', PHP_EOL;
} else {
echo '<span style="color:red;">Error moving file</span> ', PHP_EOL;
}
}
}
echo "<hr>";
}
}
.Credit
https://www.itsolutionstuff.com/post/how-to-get-html-tag-attribute-value-in-phpexample.html
https://www.tutsmake.com/php-move-and-copy-file-from-one-folder-to-another/