2016-09-08 36 views
0

我有一个脚本获取文件的内容并使用base64对其进行编码。此脚本工作正常:PHP解码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

这两个都写在同一页? – Noman

+0

什么不行?向我们展示示例输入和输出,并解释您实际获得的内容与您的期望之间的差异。 –

+0

不,他们不在同一个脚本上。 – Joey

回答

0

你没有提供的“不行”我想你双重编码或双解码becouse输入&输出相同的文件都是细节,考虑

<?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"; 
?> 
+0

我的第二个脚本不起作用。在解码部分。它返回0kb的文件 – Joey

+0

'“D:/timekeeping/logs/94-20160908.enc.dat”'调用时是否存在? ,如果一个人正常工作,我会添加支票来回答 – cske

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"; 
?> 
+0

,另外这个也不会是问题 – cske