Using file_get_contents with Gravity Forms uploads folder to create images in the media library returning false


I am using Gravity forms which is uploading media and recreating the image into the relevant media folder over https.

However, on my server, this doesn’t appear to be reading the Gravity File folder, or the contents of the image correctly. The files are being created however with no data from the image. (I have included my full upload code below. I found an article that "file_get_contents" had issues in regards to SSLs locally, and this appears to be working locally as intended.

Thoughts / guidance appreciated

(Note, Prefix is just an additional parameter, and obviously $imgArr is an array of image URLs that i am passing from the Gravity Form by form of


name is from another variable from the Gravity form as an entity also.

Thankyou in advance.

function createImage($prefix, $imgArr, $name){

    $i = 1;
    //Sorting out the URLs prior to creation
    foreach($imgArr as $url) {

            $finalUrl = str_replace('""', '',$url);
            $newName = $name . $prefix . '-'. $i;


            $upload_dir = wp_upload_dir();
            $image_data = file_get_contents($finalUrl, false, stream_context_create($arrContextOptions));

            //Strip out the old filename and replace with the befores name
            $slash = strrpos($finalUrl, '/', 0);
            $fileName = array_pop(str_split($finalUrl, $slash));
            $fileExt =  array_pop(explode('.', $fileName));
            $newFileName = $newName . '.' . $fileExt;

                $file = $upload_dir['path'] . '/' . $newFileName;
                $file = $upload_dir['basedir'] . '/' . $newFileName;
            file_put_contents($file, $image_data);

            $wp_filetype = wp_check_filetype($newFileName, null);
                $upload_id = array(
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title'=> sanitize_file_name($newFileName),
                    'post_content'   => '',
                    'post_status'    => 'inherit'

            $attach_id = wp_insert_attachment( $upload_id, $file, $post_ID);

            if (!is_wp_error($attach_id)) {
                require_once( ABSPATH . 'wp-admin/includes/image.php' );
                $attachment_data = wp_generate_attachment_metadata( $attach_id,  $file );
                wp_update_attachment_metadata( $attach_id,  $attachment_data );
                set_post_thumbnail( $post_ID, $attachment_data );

            //Return the uploaded image ID, so to use to update the ACF field

Kirsty Marks 2 months 0 Answers 6 views 0

Leave an answer