2

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
3
  • 2
    This has nothing to do with writing the string. The issue simply is that your fopen() fails and returns false instead of a resource handler. Since you do not do any error checking or handling at all in your code you try to use a file handler with value false which won't work and leads to the error message. As always: read the documentation of the functions you use if you encounter issues! Commented Jul 17, 2015 at 13:19
  • call getcwd to check whether you are really in the include folder Commented Jul 17, 2015 at 14:26
  • Possible duplicate of Write binary file in PHP Commented May 16, 2019 at 3:21

1 Answer 1

1

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");
}
Sign up to request clarification or add additional context in comments.

3 Comments

He has to check for permissions also : 'ls -la' in the image's directory and 'chown -R www-data .' if php doesn't have the execution and reading permission
@Answers_Seeker and this is true for all the folders in the path: the http servers process requires permission to enter those. Oh, and the use is not necessarily www-data. Also changing the owner is not the only option for this. Often it is much more elegant to change group writing access.
@akascha: It adds the owner it doesn't change it. You are right about www-data but it's the standard

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.