【问题标题】:If a URL get clicked a file name has to be changed, how do i do that?如果 URL 被点击,文件名必须更改,我该怎么做?
【发布时间】:2013-08-26 03:59:06
【问题描述】:

我在 HTML 文件中有这个 sn-p。但是我希望文件名从 1unread.txt 打开到 1read.txt 时会被更改,这样它就会进入读取列表。

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

如果在php.net 上阅读过,我可以用这个来更改文件名:

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

但是当使用下载链接时,我该如何实现呢?变量$context 有什么作用?我对 PHP 有点陌生,所以不要期望我能理解太多:P

还是谢谢

【问题讨论】:

  • 我忘了提到有多个文件,所以文件命名为 $date_1unread.txt。

标签: php html file rename


【解决方案1】:

下载.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
    }
?>

用这个替换下载按钮:

echo "<a href='download.php?file=$filename'>Download {$filename}</a><br>" . "\n" ;

【讨论】:

  • 它不起作用。我没有收到任何错误。但文件不会更改名称。
  • 我在 str_replace 行忘记了)。现在改了,可以再试试吗?
  • 是的,我有错误,但已修复。但是在我修复它之后,它会运行脚本但不会做任何事情。
  • 我添加了一条调试消息。除了重命名,一切正常吗?
  • 它应该输出"RENAMED '...' to '...'".粘贴那个。
猜你喜欢
  • 1970-01-01
  • 2022-11-12
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
相关资源
最近更新 更多