Lay Leangsros
Lay Leangsros

Reputation: 9296

PHP : write binary string to file

I had encoded image to binary ($binaryImage) in a string. Now I want to save it in file in server.Here is the code, but I got the result: fwrite() expects parameter 1 to be resource, boolean given... . Is the code wrong?

            $binary=base64_decode($binaryImage);
            header('Content-Type: bitmap; charset=utf-8');

            $file = fopen('../uploadedImages/'.$filename, 'wb');
            // Create File
            fwrite($file, $binary);
            fclose($file);

(EDIT) I also tried :

            if($file===false){
                echo "Failed to file";
            }            
            // Create File
            if(fwrite($file, $binary)===false){
                echo "Failed to write";
            }

get this message:

fopen(../uploadedImages/FB_IMG_1437004428570.jpg): failed to open stream: No such file or directory in <b>/home/u505221043/public_html/welcom/include/db_functions.php

My php code is in "include" directory. And "uploadedImage" is 777 mode.

->include
   ->function.php
->uploadedImages

Upvotes: 2

Views: 7352

Answers (1)

Jason McCreary
Jason McCreary

Reputation: 72971

file() returns a boolean when it fails to open a file.

This could be for several reasons such as an incorrect path or permissions.

I recommend adding a guard clause, at least to debug this issues:

$file = fopen('../uploadedImages/' . $filename, 'wb');
if ($file === false) {
    exit("Failed to file");
}

Upvotes: 1

Related Questions