doushan5245 2013-08-23 07:19
浏览 31
已采纳

如果点击了URL,则必须更改文件名,我该怎么做?

I have this snippet in a HTML file. But I want that a file name gets changed if its opened from 1unread.txt to 1read.txt so it will get in the list of read.

<h2>Unread</h2>
<?php 
foreach (glob("*1unread.txt") as $filename) {
    echo "<a href='$filename'>Download {$filename}</a><br>" . "
" ;
}
?>
<h2>Read</h2>
<?php 
foreach (glob("*1read.txt") as $filename) {
    echo "<a href='$filename'>Download {$filename}</a><br>" . "
" ;
}
?>

If have read on php.net that I can change a file name with this:

bool rename ( string $oldname , string $newname [, resource $context ] )

but how do I make this happen when the download linked is used? And what does the variable $context do? I am kinda new to PHP so don't expect much from me to understand :P

Thanks anyway

  • 写回答

1条回答 默认 最新

  • douyun7285 2013-08-23 07:34
    关注

    download.php:

    <?php
        //Only offer file to download which are having "unread" or "read" in their filename.
        if(!strstr($_GET['file'], 'unread') || !strstr($_GET['file'], 'read']))
            die('Invalid file.');
    
        //Make sure the file exists.
        if(!file_exists($_GET['file']))
            die('File not found.');
    
        echo file_get_contents($_GET['file']);
    
        if(strstr($_GET['file'], 'unread')) {
            //rename 1unread.txt to 1read.txt
            $newFileName = str_replace('unread', 'read', $_GET['file']);
            rename($_GET['file'], $newFileName);
            echo sprintf("RENAMED '%s' TO '%s'!", $_GET['file'], $newFileName); //Debug
        } else {
            //rename 1read.txt to 1unread.txt
            $newFileName = str_replace('read', 'unread', $_GET['file']);
            rename($_GET['file'], $newFileName);
            echo sprintf("RENAMED '%s' TO '%s'!", $_GET['file'], $newFileName); //Debug
        }
    ?>
    

    Replace the download button with this:

    echo "<a href='download.php?file=$filename'>Download {$filename}</a><br>" . "
    " ;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题