我有一个脚本可以获取文件的内容并使用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";
?>
但是不起作用。
答案 0 :(得分:0)
您没有提供&#34;不工作&#34;的详细信息。我假设您进行双重编码或双重解码,因为输入&amp;输出是同一个文件,考虑
<?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";
?>
答案 1 :(得分:0)
这解决了我的问题。这两个函数不能很好地结合在一起所以我将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";
?>