简易 PHP 网址缩短

轮廓:输入有效的长网址并进行缩短,出现一个弹出框,其中包含一个短网址和一个保存按钮(编辑或保存短网址)单击保存按钮后,页面重新加载,并显示创建的短网址、源网址等信息。

代码语言:javascript
复制
<?php 
  include "php/config.php"; // 包含配置文件,连接到数据库

$new_url = ""; // 初始化变量

// 判断是否存在GET请求
if(isset($_GET)){
foreach(_GET as key=>$val){
u = mysqli_real_escape_string(conn, $key); // 获取短链接参数并进行转义处理,防止SQL注入攻击
new_url = str_replace(&#39;/&#39;, &#39;&#39;, u); // 替换短链接中的斜杠字符
}

// 查询数据库中对应的长网址
$sql = mysqli_query($conn, &#34;SELECT full_url FROM url WHERE shorten_url = &#39;{$new_url}&#39;&#34;);

// 如果存在查询结果
if(mysqli_num_rows($sql) &gt; 0){
  $sql2 = mysqli_query($conn, &#34;UPDATE url SET clicks = clicks + 1 WHERE shorten_url = &#39;{$new_url}&#39;&#34;); // 更新点击次数
  if($sql2){
    $full_url = mysqli_fetch_assoc($sql);
    header(&#34;Location:&#34;.$full_url[&#39;full_url&#39;]); // 跳转到原始URL
  }
}

}
?>

数据库配置

代码语言:javascript
复制
<?php
$domain = "https://dabenshi.cn/"; //例如: dabenshi.cn/
$host = "localhost";
$user = ""; //数据库用户名
$pass = ""; //数据库密码
$db = ""; //数据库名

$conn = mysqli_connect($host, $user, $pass, $db);
if(!$conn){
    echo &#34;Database connection error&#34;.mysqli_connect_error();
}

?>

创建"urlshortener"数据库,"url"表。包含四个字段:idshorten_urlfull_urlclicks

id字段是一个自增的整数类型,作为主键使用。shorten_url字段是一个长度为200的非空字符串,用于保存缩短后的URL。full_url字段是一个长度为1000的非空字符串,用于保存完整的URL。clicks字段是一个整数类型,用于记录URL的点击次数。

数据删除

代码语言:javascript
复制
<?php
include "config.php";
if(isset($_GET['id'])){
delete_id = mysqli_real_escape_string(conn, $_GET['id']);
sql = mysqli_query(conn, "DELETE FROM url WHERE shorten_url = '{$delete_id}'");
if($sql){
header("Location: ../");
}else{
header("Location: ../");
}
}elseif(isset($_GET['delete'])){
sql3 = mysqli_query(conn, "DELETE FROM url");
if($sql3){
header("Location: ../");
}else{
header("Location: ../");
}
}else{
header("Location: ../");
}
?>

自定义短网址

代码语言:javascript
复制
<?php
include "config.php";
og_url = mysqli_real_escape_string(conn, $_POST['shorten_url']);
shorten_url = str_replace(&#39; &#39;, &#39;&#39;, og_url);
hidden_url = mysqli_real_escape_string(conn, $_POST['hidden_url']);

if(!empty($shorten_url)){
    if(preg_match(&#34;/\//i&#34;, $shorten_url)){
        $explodeURL = explode(&#39;/&#39;, $shorten_url);
        $shortURL = end($explodeURL);
        if($shortURL != &#34;&#34;){
            $sql = mysqli_query($conn, &#34;SELECT shorten_url FROM url WHERE shorten_url = &#39;{$shortURL}&#39; &amp;&amp; shorten_url != &#39;{$hidden_url}&#39;&#34;);
            if(mysqli_num_rows($sql) == 0){
                $sql2 = mysqli_query($conn, &#34;UPDATE url SET shorten_url = &#39;{$shortURL}&#39; WHERE shorten_url = &#39;{$hidden_url}&#39;&#34;);
                if($sql2){
                    echo &#34;success&#34;;
                }else{
                    echo &#34;错误 - 无法更新链接!&#34;;
                }
            }else{
                echo &#34;你输入的短网址已存在。请输入另一个!&#34;;
            }
        }else{
            echo &#34;必需 - 你必须输入短网址!&#34;;
        }
    }else{
        echo &#34;无效网址 - 你无法编辑域名!&#34;;
    }
}else{
    echo &#34;错误 - 你必须输入短网址!&#34;;
}

?>

URL控制

代码语言:javascript
复制
<?php
include "config.php";
full_url = mysqli_real_escape_string(conn, $_POST['full_url']);
if(!empty(full_url) &amp;&amp; filter_var(full_url, FILTER_VALIDATE_URL)){
$ran_url = substr(md5(microtime()), rand(0, 26), 5);
sql = mysqli_query(conn, "SELECT * FROM url WHERE shorten_url = '{$ran_url}'");
if(mysqli_num_rows($sql) > 0){
echo "出了点问题. 请重新缩短!";
}else{
sql2 = mysqli_query(conn, "INSERT INTO url (full_url, shorten_url, clicks)
VALUES ('{full_url}&#39;, &#39;{ran_url}', '0')");
if($sql2){
sql3 = mysqli_query(conn, "SELECT shorten_url FROM url WHERE shorten_url = '{$ran_url}'");
if(mysqli_num_rows($sql3) > 0){
shorten_url = mysqli_fetch_assoc(sql3);
echo $shorten_url['shorten_url'];
}
}
}
}else{
echo "$full_url - 这不是有效的网址!";
}
?>

JаvaScript

代码语言:javascript
复制
const form = document.querySelector(".wrapper form"),
fullURL = form.querySelector("input"),
shortenBtn = form.querySelector("form button"),
blurEffect = document.querySelector(".blur-effect"),
popupBox = document.querySelector(".popup-box"),
infoBox = popupBox.querySelector(".info-box"),
form2 = popupBox.querySelector("form"),
shortenURL = popupBox.querySelector("form .shorten-url"),
copyIcon = popupBox.querySelector("form .copy-icon"),
saveBtn = popupBox.querySelector("button");

form.onsubmit = (e)=>{
e.preventDefault();
}

shortenBtn.onclick = ()=>{
let xhr = new XMLHttpRequest();
xhr.open("POST", "php/url-controll.php", true);
xhr.onload = ()=>{
if(xhr.readyState == 4 && xhr.status == 200){
let data = xhr.response;
if(data.length <= 5){
blurEffect.style.display = "block";
popupBox.classList.add("show");

            //网址填写到这里. 例如: dabenshi.cn/
            let domain = &#34;https://dabenshi.cn/&#34;; 
            shortenURL.value = domain + data;
            copyIcon.onclick = ()=&gt;{
                shortenURL.select();
                document.execCommand(&#34;copy&#34;);
            }

            saveBtn.onclick = ()=&gt;{
                form2.onsubmit = (e)=&gt;{
                    e.preventDefault();
                }

                let xhr2 = new XMLHttpRequest();
                xhr2.open(&#34;POST&#34;, &#34;php/save-url.php&#34;, true);
                xhr2.onload = ()=&gt;{
                    if(xhr2.readyState == 4 &amp;&amp; xhr2.status == 200){
                        let data = xhr2.response;
                        if(data == &#34;success&#34;){
                            location.reload();
                        }else{
                            infoBox.classList.add(&#34;error&#34;);
                            infoBox.innerText = data;
                        }
                    }
                }
                let shorten_url1 = shortenURL.value;
                let hidden_url = data;
                xhr2.setRequestHeader(&#34;Content-type&#34;, &#34;application/x-www-form-urlencoded&#34;);
                xhr2.send(&#34;shorten_url=&#34;+shorten_url1+&#34;&amp;hidden_url=&#34;+hidden_url);
            }
        }else{
            alert(data);
        }
    }
}
let formData = new FormData(form);
xhr.send(formData);

}