Joey
Joey

Reputation: 509

PHP Decode base64 file contents

I have a script that gets the contents of a file and encodes it using base64. This script works fine:

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

Now, I want to decode the contents back to its original value. I tried:

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

But does not work.

Upvotes: 4

Views: 26224

Answers (2)

cske
cske

Reputation: 2243

You did not provide the details of "not work" i assume you double encode or double decode becouse of the input & output are the same file, consider

<?php

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

to see what happens on double encode

try this

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

Upvotes: 0

Joey
Joey

Reputation: 509

This fixed my problem. The two function does not go well together so I separated the file_get_contents from 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";
?>

Upvotes: 3

Related Questions