nlozovan

Untitled

Apr 13th, 2021
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.70 KB | None | 0 0
  1. /**
  2.      * Save a base64 jpeg image on the server in Media library.
  3.      */
  4.     function save_image($base64_image_string, $output_file_name_without_extension) {
  5.       global $wp_filesystem;
  6.       // Initialize the WP filesystem, no more using 'file-put-contents' function
  7.       if (empty($wp_filesystem)) {
  8.         require_once (ABSPATH . '/wp-admin/includes/file.php');
  9.         WP_Filesystem();
  10.       }
  11.       // get uploads dir
  12.       $upload_dir = wp_upload_dir();
  13.       $upload_basedir = $upload_dir['basedir'];
  14.       $upload_baseurl = $upload_dir['baseurl'];
  15.       $screens_dir = $upload_basedir . '/flo_forms_screens/'; // custom folder where the screen shots will be kept
  16.       // if folder that will hold the screens does not exist yet, create it
  17.       if(!$wp_filesystem->is_dir($screens_dir)) {
  18.         $wp_filesystem->mkdir($screens_dir);
  19.       }
  20.       // folder exists, push image to it
  21.       $file = false;
  22.       if($wp_filesystem->is_dir($screens_dir)) {
  23.         $img             = str_replace( 'data:image/jpeg;base64,', '', $base64_image_string );
  24.         $img             = str_replace( ' ', '+', $img );
  25.         $decoded         = base64_decode( $img );
  26.         $hashed_filename = md5( $output_file_name_without_extension . microtime() ) . '_' . $output_file_name_without_extension;
  27.         $filePath = $screens_dir . $hashed_filename . ".jpeg";
  28.         $fileCallback = $wp_filesystem->put_contents(
  29.           $filePath,
  30.           $decoded,
  31.           FS_CHMOD_FILE // predefined mode settings for WP files
  32.         );
  33.         $publicFilePath = str_replace($upload_basedir, $upload_baseurl, $filePath);
  34.         if($fileCallback) $file = $publicFilePath;
  35.       }
  36.       return $file;
  37.     }
Add Comment
Please, Sign In to add comment