2016-09-08 77 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