【问题标题】:How do I edit a certain part of a file through php?如何通过php编辑文件的某个部分?
【发布时间】:2015-01-24 04:27:24
【问题描述】:

我想在文件下载之前编辑文件的某些部分。我想通过 php 来做,但我可以使用 javascript 或 flash。我会怎么做?

这是我尝试过的方法,但它替换了整行并且也不会恢复到原来的状态

<?php
$file = 'folder/file.ext';

if($_POST['filename'] != null)
{
$exclude = "text"; 
 $lines = file($file); 
 $out = $_POST['filename']; 
 foreach ($lines as $line) { 
  if (strstr($line, $exclude) == "") { 
   $out .= $line; 
  } 
 } 
 $f = fopen($file, "w"); 
 fwrite($f, $out); 
 fclose($f); 
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="text.php"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
    $exclude = $_POST['filename']; 
    $lines = file($file); 
    $out = "text"; 
    foreach ($lines as $line) { 
        if (strstr($line, $exclude) == "") { 
        $out .= $line; 
    } 
    } 
 $f = fopen($file, "w"); 
 fwrite($f, $out); 
 fclose($f); 
}

}
?>

【问题讨论】:

  • 你在 Flash 上迷失了我:P
  • 如何确定要编辑的具体行?
  • 我让它在每一行搜索 $exclude 设置的内容
  • 您的问题得到解答了吗?

标签: php html file editing


【解决方案1】:

为此,您想了解一些事情。第一个是mod_rewrite,它允许“URL 重写”。你可以用这个做什么,你可以做到,当用户尝试访问“http://example.com/files/file-123.txt”时,他们会得到“http://example.com/download.php?file=file-123.txt”。他们不会知道他们正在使用 PHP 脚本,但他们知道。

使用它,在 download.php 上,您可以执行类似的操作

$file = $_GET['file'];
if (file_exists($file)) 
{
    //Put your headers here
    $contents = file_get_contents($pathToFile);

    //Do your replacements in $contents here, but don't write to the file
    echo $contents;
}

这样您只修改发送给用户的文件,而不是服务器本身上的文件。

请记住,这不会花费您需要修复的任何安全问题。当您进行文件访问时,其中有很多,例如确保 $_GET['file'] 是他们实际允许访问的文件,而不是说“/etc/sudoers”。

但我认为这是您想要采取的方法,是吗?

【讨论】:

    【解决方案2】:

    我认为你必须下载文件,然后修改并保存。

    要读取文件的特定部分,请使用fgets($file, position) 如果您想将内容放在特定位置,请尝试fseek() 如果你想添加file_put_content($file, $content, FILE_APPEND);

    【讨论】:

    • 所以我可以制作一个临时文件,编辑它,下载它,然后删除吗?如果是这样,我如何将内容复制到临时文件中?
    • 上传的文件是临时文件。 $FILE['tmp'] 我记得。如果需要,您也可以创建自己的:php.net/manual/en/function.tmpfile.php
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2018-04-25
    • 1970-01-01
    相关资源
    最近更新 更多