超链接与浏览器的实际位置不匹配? PHP用于以编程方式编写标签,但获取嵌套链接结构

发布于 2025-01-16 20:43:29 字数 4665 浏览 1 评论 0原文

目前,我正在尝试使用 PHP 制作一个简单的博客系统。我的网站设置为所有路由都转到 index.php。它非常脆弱,需要修复,但是现在它

<?php
    include("config.php");
    $requestedPage = $_GET['page'] ?? 'home';
    if ($requestedPage === 'index'){
        $requestedPage = 'home';
        }
    $requestedPage = basename($requestedPage).".php"; 
    if (!file_exists($requestedPage)){
        http_response_code(404);
        $requestedPage = '404.php';
    }
?>
//HTML header info
<?php 
include("header.php");
include($requestedPage); 
include("footer.php");
?>

远非安全,但它加载了我现在需要的页面。如果我们转到我的博客页面,它总共有 3 个文件:blog.phpblog_functions.phpblog_templateblog.php 只是一些 HTML,其中我包含了其他两个提到的文件,这是实际博客的大部分内容。我确定问题不在 blog.php 中,但这里只是为了以防万一。

<?php include("includes/blog_functions.php");?>

//Some HTML
<section id="blog">
    <div class="blog-sidebar">
        <h3>Our recent posts</h3>
        <?php initPosts();?>
    </div>


<div class="blog-post">
<?php 
include("templates/blog_template.php");?>
</div>
</section>

下一个文件是 blog_functions.php

<?php 
function sortRecentPosts($POST_DIR){
    $DIR = './blog_posts';
    $folders = array_slice(scandir($DIR), 2);
    usort($folders, function($a, $b) use ($POST_DIR) {
        //The array is just sending the file names, attach a path in this function 
        if(file_exists($POST_DIR.$a) && file_exists($POST_DIR.$b)){
            return filemtime($POST_DIR.$b) - filemtime($POST_DIR.$a);
        }
    });  
    return $folders;
}

function displayRecentPosts($folderArray, $POST_DIR){
    if(is_array($folderArray)){
        for($i=0; $i<3; $i++){
            echo "<h2><a href="."blog/".$folderArray[$i].">".$folderArray[$i]."</a></h2> \n";;
            echo date("d M, Y", filemtime($POST_DIR.$folderArray[$i]));
            echo "<img class=\"blog-post-header-img\"src=\"/".$POST_DIR.$folderArray[$i]."/header.jpg\" alt=\"Header image of blog post\">";
        }  
    }
    else{
        throw new Exception('function did not recieve an array');
    }
}

function initPosts(){
    //POST_DIR controls the entire scripts working directory to find the blog posts.
    $POST_DIR = './blog_posts/';
    displayRecentPosts(sortRecentPosts($POST_DIR), $POST_DIR);
}

我认为这就是问题所在。在 displayRecentPosts($a, $b) 中,有一行回显了一些 HTML。它所呼应的其中一行是带有指向实际博客文章的 href 的标签。正如您所看到的,我以硬编码的 blog/ 开始字符串,然后是实际的帖子(基于单击的帖子)。虽然没有加载博客文章(例如只是导航到博客页面), 网址将如下所示。 my-website.com/blog。例如,现在让我们单击图片中的链接之一。

图片博客侧边栏是什么样子

这将加载一篇博客文章,然后将 URL 更改为 my-website.com/blog/Test-Post2。但是,如果我随后尝试以相同的方式导航到另一篇博客文章,它现在将开始嵌套 url,导致 404。

嵌套链接结构的图片

由于某种原因,一旦加载博客文章,一个脚本正在抓取并复制带有 blog/ 前缀的链接并再次应用。但是,如果我检查该标签,它没有嵌套前缀。看起来应该如此。

标签看起来不错

我不知道是什么原因造成的,也不知道它来自哪里。我已经在 index.phpblog_functions.phpblog_template.php 上运行了调试器。它们看起来都很好并且按预期工作。

这是blog_template.php。它仅呈现所给出的帖子,没有什么花哨的。

<?php   
    $DIR = "./blog_posts";
    $folders = array_slice(scandir($DIR), 2);
    if(isset($_GET['blogPost'])){
        $blogPost = $_GET['blogPost'];
        $i = 0;
        foreach ($folders as $arr){
            if($arr == $blogPost){
                chdir($DIR."/".$blogPost); 
                include(getcwd().'\\'.$blogPost.".html");
                chdir(__DIR__);
            }else{
                echo "NO MATCH ";
            }
            $i++;
        }
    }else{
        $blogPost = "";
        echo "FILE NAME IS NULL";
    }
?>

我不怀疑问题出在这个文件上,因为它只呈现所选页面并随后停止。

最后,我认为错误可能出现在 .htaccess 中,但是我从未听说过或使用 RewriteModule 遇到过这样的问题,所以如果是它导致的,这对我来说是第一次。

实际上,这对我来说是第一次,我从未见过标签显示的内容与浏览器实际发送给我的内容不同,所以我完全不知道这个错误来自哪里。

为了清楚起见,这里是 .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z0-9]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9-]+)$ index.php?page=$1&blogPost=$2

Currently, I'm trying to make a simple blogging system using PHP. My website set up so all routing goes to index.php. It is extremely flimsy, and needs to be fixed up, however here it is right now

<?php
    include("config.php");
    $requestedPage = $_GET['page'] ?? 'home';
    if ($requestedPage === 'index'){
        $requestedPage = 'home';
        }
    $requestedPage = basename($requestedPage).".php"; 
    if (!file_exists($requestedPage)){
        http_response_code(404);
        $requestedPage = '404.php';
    }
?>
//HTML header info
<?php 
include("header.php");
include($requestedPage); 
include("footer.php");
?>

Far from secure, but it loads page's which is all I need right now. If we head over to my blog page, it has 3 files in total, blog.php, blog_functions.php, and blog_template.
blog.php is simply some HTML where I include the other two mentioned files, which is the bulk of the actual blog. I'm certain the issue isn't in blog.php, but here it is just to in case.

<?php include("includes/blog_functions.php");?>

//Some HTML
<section id="blog">
    <div class="blog-sidebar">
        <h3>Our recent posts</h3>
        <?php initPosts();?>
    </div>


<div class="blog-post">
<?php 
include("templates/blog_template.php");?>
</div>
</section>

This next file is blog_functions.php

<?php 
function sortRecentPosts($POST_DIR){
    $DIR = './blog_posts';
    $folders = array_slice(scandir($DIR), 2);
    usort($folders, function($a, $b) use ($POST_DIR) {
        //The array is just sending the file names, attach a path in this function 
        if(file_exists($POST_DIR.$a) && file_exists($POST_DIR.$b)){
            return filemtime($POST_DIR.$b) - filemtime($POST_DIR.$a);
        }
    });  
    return $folders;
}

function displayRecentPosts($folderArray, $POST_DIR){
    if(is_array($folderArray)){
        for($i=0; $i<3; $i++){
            echo "<h2><a href="."blog/".$folderArray[$i].">".$folderArray[$i]."</a></h2> \n";;
            echo date("d M, Y", filemtime($POST_DIR.$folderArray[$i]));
            echo "<img class=\"blog-post-header-img\"src=\"/".$POST_DIR.$folderArray[$i]."/header.jpg\" alt=\"Header image of blog post\">";
        }  
    }
    else{
        throw new Exception('function did not recieve an array');
    }
}

function initPosts(){
    //POST_DIR controls the entire scripts working directory to find the blog posts.
    $POST_DIR = './blog_posts/';
    displayRecentPosts(sortRecentPosts($POST_DIR), $POST_DIR);
}

This is where I believe the problem to be. In displayRecentPosts($a, $b) there is a line where it echos out some HTML. One of the lines it echos is the tag with a href to the actual blog post. As you can see, I start the string with with a hard coded blog/, followed up by the actual post, based on which post is clicked. While not having a blog post loaded, (for example just navigating to the blog page),
the url will look like this. my-website.com/blog. Now for example, let's now click on one of those links in the picture.

Picture of what the blog sidebar looks like

This will load a blog post, which will then change the URL to my-website.com/blog/Test-Post2. However, if I then try to navigate to another blog post in the same manner, it now will begin nesting the url, causing a 404.

Picture of nested link structure

For some reason, once a blog post is loaded, one scripts is grabbing and copying the link with the blog/ prefix and applying again. However, if I inspect the tag, it doesn't have the nested prefix. It looks like it should.

The  tag looks proper

I have no idea what's causing this, or where it's coming from. I've ran through with a debugger on index.php, blog_functions.php, and blog_template.php. They all look fine and work as expected.

Here is blog_template.php. It only renders a post that it's given, nothing fancy.

<?php   
    $DIR = "./blog_posts";
    $folders = array_slice(scandir($DIR), 2);
    if(isset($_GET['blogPost'])){
        $blogPost = $_GET['blogPost'];
        $i = 0;
        foreach ($folders as $arr){
            if($arr == $blogPost){
                chdir($DIR."/".$blogPost); 
                include(getcwd().'\\'.$blogPost.".html");
                chdir(__DIR__);
            }else{
                echo "NO MATCH ";
            }
            $i++;
        }
    }else{
        $blogPost = "";
        echo "FILE NAME IS NULL";
    }
?>

I don't suspect the issue to be here this file, as it only renders out the chosen page and stops afterwards.

Finally, I suppose the error could be in .htaccess, however I've never heard of or had an issue like this using RewriteModule, so if it is causing it, this is a first for me.

Actually, this is a first in general for me, I've never seen an tag show something different than where the browser is actually going to send me, so I'm at a complete loss as to where this bug is coming from.

Here is .htaccess for clarity.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z0-9]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9-]+)$ index.php?page=$1&blogPost=$2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文