前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >简易 PHP 网址缩短

简易 PHP 网址缩短

作者头像
Dabenshi
发布2023-10-10 08:08:02
2450
发布2023-10-10 08:08:02
举报
文章被收录于专栏:Dabenshi

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

复制代码

代码语言: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('/', '', $u); // 替换短链接中的斜杠字符
    }

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

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

数据库配置

复制代码

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

    $conn = mysqli_connect($host, $user, $pass, $db);
    if(!$conn){
        echo "Database connection error".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(' ', '', $og_url);
    $hidden_url = mysqli_real_escape_string($conn, $_POST['hidden_url']);

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

URL控制

复制代码

代码语言:javascript
复制
<?php
    include "config.php";
    $full_url = mysqli_real_escape_string($conn, $_POST['full_url']);
    if(!empty($full_url) && 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}', '{$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 = "https://dabenshi.cn/"; 
                shortenURL.value = domain + data;
                copyIcon.onclick = ()=>{
                    shortenURL.select();
                    document.execCommand("copy");
                }

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

                    let xhr2 = new XMLHttpRequest();
                    xhr2.open("POST", "php/save-url.php", true);
                    xhr2.onload = ()=>{
                        if(xhr2.readyState == 4 && xhr2.status == 200){
                            let data = xhr2.response;
                            if(data == "success"){
                                location.reload();
                            }else{
                                infoBox.classList.add("error");
                                infoBox.innerText = data;
                            }
                        }
                    }
                    let shorten_url1 = shortenURL.value;
                    let hidden_url = data;
                    xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr2.send("shorten_url="+shorten_url1+"&hidden_url="+hidden_url);
                }
            }else{
                alert(data);
            }
        }
    }
    let formData = new FormData(form);
    xhr.send(formData);
}轮廓:输入有效的长网址并进行缩短,出现一个弹出框,其中包含一个短网址和一个保存按钮(编辑或保存短网址)单击保存按钮后,页面重新加载,并显示创建的短网址、源网址等信息。

复制代码
<?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('/', '', $u); // 替换短链接中的斜杠字符
    }

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

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

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

    $conn = mysqli_connect($host, $user, $pass, $db);
    if(!$conn){
        echo "Database connection error".mysqli_connect_error();
    }
?>
创建"urlshortener"数据库,"url"表。包含四个字段:id、shorten_url、full_url和clicks。

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

复制代码
<?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: ../");
    }
?>
自定义短网址

复制代码
<?php
    include "config.php";
    $og_url = mysqli_real_escape_string($conn, $_POST['shorten_url']);
    $shorten_url = str_replace(' ', '', $og_url);
    $hidden_url = mysqli_real_escape_string($conn, $_POST['hidden_url']);

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

复制代码
<?php
    include "config.php";
    $full_url = mysqli_real_escape_string($conn, $_POST['full_url']);
    if(!empty($full_url) && 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}', '{$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

复制代码
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 = "https://dabenshi.cn/"; 
                shortenURL.value = domain + data;
                copyIcon.onclick = ()=>{
                    shortenURL.select();
                    document.execCommand("copy");
                }

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

                    let xhr2 = new XMLHttpRequest();
                    xhr2.open("POST", "php/save-url.php", true);
                    xhr2.onload = ()=>{
                        if(xhr2.readyState == 4 && xhr2.status == 200){
                            let data = xhr2.response;
                            if(data == "success"){
                                location.reload();
                            }else{
                                infoBox.classList.add("error");
                                infoBox.innerText = data;
                            }
                        }
                    }
                    let shorten_url1 = shortenURL.value;
                    let hidden_url = data;
                    xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr2.send("shorten_url="+shorten_url1+"&hidden_url="+hidden_url);
                }
            }else{
                alert(data);
            }
        }
    }
    let formData = new FormData(form);
    xhr.send(formData);
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023/10/08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档