1

I am using put_contents() function to put images on the server, works fine on localhost, though on server, the user group when the file are downloaded to server is "nginx nobody" and that is causing the images to return 404 error and not to be viewed, how can I make the file be downloaded with the default WordPress owner/group

    global $wp_filesystem;
    // Initialize the WP filesystem.
    if (empty($wp_filesystem)) {
        require_once (ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }       
$wp_filesystem->put_contents($save_file_to, $file_to_save, 0644)
0

I got it fixed, using this function request_filesystem_credentials(), it seems to initialize things and gets the proper credentials.

Found it in an example in this article: An Introduction to the WordPress Filesystem API.

My code:

# get credentials
function connect_fs()
{
  global $wp_filesystem;

  if( false === ($credentials = request_filesystem_credentials('')) ) 
  {
    return false;
  }

  //check if credentials are correct or not.
  if(!WP_Filesystem($credentials)) 
  { 
    request_filesystem_credentials('');
    return false;
  }

  return true;
}

function donload_images($image_title, $image_url)
{
  global $wp_filesystem;

    #path to save to
    $files_path = ABSPATH . '/image';   
    $save_file_to = $files_path .'/'. $image_title;

    #check if requested file is on server
    $file_exists = file_exists($save_file_to);

    if(connect_fs()){
            // Get file
        if(!$file_exists)
        {     
            #Download file info
            $file_to_save = file_get_contents($image_url);

                //success
            if($wp_filesystem->put_contents($save_file_to, $file_to_save, FS_CHMOD_FILE)){
            }
            else //Fail
            {
            }

            return $file_to_save;
        }
        else //File exists
        {
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.