优化12代码 只写php段1 PHP代码中添加新网址部分的判断条件应该是!in_array$newUrl $urls而不是!in_array$newUrl $url。2 PHP代码中删除网址、锁定网址、解锁网址部分的循环变量应该是$selected而不是$_POSTurls。!DOCTYPE htmlhtmlhead title网址收藏夹title meta charset=UTF-8 link
优化后的PHP代码:
<?php
// 读取已保存的网址
$url_file = 'urls.txt';
if (file_exists($url_file)) {
$urls = file($url_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
} else {
$urls = array();
}
// 添加新网址
if (isset($_POST['action']) && $_POST['action'] === 'add' && isset($_POST['url'])) {
$newUrl = $_POST['url'];
if (!in_array($newUrl, $urls)) {
if (filter_var($newUrl, FILTER_VALIDATE_URL)) {
$urls[] = $newUrl;
file_put_contents($url_file, implode("\n", $urls));
echo 'success';
} else {
echo 'invalid url';
}
} else {
echo 'url already exists';
}
}
// 删除网址
if (isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['urls'])) {
$selected = $_POST['urls'];
foreach ($selected as $index) {
if (array_key_exists($index, $urls)) {
unset($urls[$index]);
}
}
file_put_contents($url_file, implode("\n", $urls));
echo 'success';
}
// 锁定网址
if (isset($_POST['action']) && $_POST['action'] === 'lock' && isset($_POST['urls'])) {
$selected = $_POST['urls'];
foreach ($selected as $index) {
if (array_key_exists($index, $urls)) {
$lockedUrl = 'locked:' . $urls[$index];
if (!in_array($lockedUrl, $urls)) {
$urls[$index] = $lockedUrl;
}
}
}
file_put_contents($url_file, implode("\n", $urls));
echo 'success';
}
// 解锁网址
if (isset($_POST['action']) && $_POST['action'] === 'unlock' && isset($_POST['urls'])) {
$selected = $_POST['urls'];
foreach ($selected as $index) {
if (array_key_exists($index, $urls)) {
$unlockedUrl = str_replace('locked:', '', $urls[$index]);
if (!in_array($unlockedUrl, $urls)) {
$urls[$index] = $unlockedUrl;
}
}
}
file_put_contents($url_file, implode("\n", $urls));
echo 'success';
}
?>
原文地址: https://www.cveoy.top/t/topic/bmSD 著作权归作者所有。请勿转载和采集!