将PHP中的base64文件内容解码

4

我有一个脚本,可以获取文件内容并使用base64进行编码。这个脚本运行良好:

<?php
$targetPath="D:/timekeeping/logs/94-20160908.dat";
$data = base64_encode(file_get_contents($targetPath));
$file = fopen($targetPath, 'w');
fwrite($file, $data);
fclose($file);
echo "file contents has been encoded";
?>

现在,我想把内容解码回原始值。我尝试了以下方法:
<?php
$targetPath="D:/timekeeping/logs/94-20160908.dat";
$data = base64_decode(file_get_contents($targetPath));
$file = fopen($targetPath, 'w');
fwrite($file, $data);
fclose($file);
echo "file contents has been decoded";
?>

但是不起作用。

两者都写在同一页上吗? - Noman
什么不起作用?请展示给我们输入和输出的例子,并解释实际得到的结果与您期望的结果之间的差异。 - Martin Nyolt
不,它们不在同一脚本上。 - Joey
2个回答

3
这解决了我的问题。这两个函数一起使用会出现问题,所以我将file_get_contents和base64_decode分开使用。
    <?php
    $targetPath="D:/timekeeping/logs/94-20160908.dat";
    $data = file_get_contents($targetPath);
    $content= base64_decode($data);
    $file = fopen($targetPath, 'w');    
    fwrite($file, $content);
    fclose($file);
    echo "done";
?>

如果一个工作,另一个也会工作,这不可能是问题。 - cske

0

你没有提供“不起作用”的细节,我假设你因为输入和输出是同一个文件而进行了双重编码或双重解码,请考虑。

<?php

$in = 'teszt';
$enc = base64_encode($in);
echo $enc,"\n";
$enc2 = base64_encode($enc);
echo $enc2,"\n";
$enc3 = base64_encode($enc2);
echo $enc3,"\n";

查看双重编码会发生什么

试试这个

<?php
$sourcePath="D:/timekeeping/logs/94-20160908.dec.dat";
$targetPath="D:/timekeeping/logs/94-20160908.enc.dat";
if (!file_exsits($sourcePath) || !file_readable($sourcePath) ) {
    die('missing source');
} 
$source = file_get_contents($sourcePath);
if (empty($source) ) {
    die('source file is empty');
}
$data = base64_encode($source);
$file = fopen($targetPath, 'w');
fwrite($file, $data);
fclose($file);
echo "file contents has been encoded";
?>

<?php
$sourcePath="D:/timekeeping/logs/94-20160908.enc.dat";
$targetPath="D:/timekeeping/logs/94-20160908.dec.dat";
if (!file_exsits($sourcePath) || !file_readable($sourcePath) ) {
    die('missing source');
} 
$source = file_get_contents($sourcePath);
if (empty($source) ) {
    die('source file is empty');
}
$data = base64_decode($source);
$file = fopen($targetPath, 'w');
fwrite($file, $data);
fclose($file);
echo "file contents has been decoded";
?>

我的第二个脚本在解码部分无法工作,返回的文件大小为0KB。 - Joey
当被调用时,"D:/timekeeping/logs/94-20160908.enc.dat"是否存在?我将添加检查来回答。 - cske

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接