Search code examples
phpcodeigniter

Codeigniter file_put_contents: failed to open stream: Permission denied


While Uploading the image in the server I got the error in codeigniter. But it works fine in local system.

A PHP Error was encountered:

Severity: Warning

Message: file_put_contents(upload/logo/1617000545.png): failed to open stream: Permission denied

Filename: models/Logo_m.php

Line Number: 41

    list($type, $data) = explode(';', $data);
        list(, $data) = explode(',', $data);
       
        $data = base64_decode($data);
        $imageName = time().'.png';

        file_put_contents('upload/logo/'.$imageName, $data);````

Solution

  • Do you have check about your directory or permission?

    Some problem maybe cause:

    1. Directory Does not exists, you must create it first.
    2. Permissions / Script does not have enough access to write files, you must verify the application could write directory and directory is writable.

    Your code also doesn't validate the image content / metadata;

    // $data = trim(explode(',', explode(';', $data)[1])[1]);
    list($type, $data) = explode(';', $data);
    list(, $data) = explode(',', $data);
    $data = base64_decode($data);
    // determine absolute path
    $imageDirectory = __DIR__ .'/upload/logo';
    // check if string / content is an image
    if (! ($imgInfo = getimagesizefromstring($data))) {
        // do exit here because data is not a binary image string
        throw new Exception('Data is not an image');
    }
    // check if image directory exist
    if (!file_exists($imageDirectory)) {
        mkdir($imageDirectory, 755, true);
    }
    if (!is_dir($imageDirectory) || !is_writable($imageDirectory)) {
        throw new Exception('Could not save image. Directory is not writable.');
    }
    
    $extension = $imgInfo['mime'];
    // optional to filter jpeg image
    if ($extension  === 'jpeg') {
        $extension = 'jpg';
    }
    // use only time is not recommended due time is not unique, please change with random value
    $baseName = time();
    $imageName = $baseName . '.' . $extension;
    $written   = file_put_contents($imageDirectory.'/'.$imageName, $data);