Support » Plugin: WP Session Manager » Store image for session, delete on expiration

  • Resolved friendofdog

    (@friendofdog)



    I am trying to…
    – store an image in a temp folder created for the session, and
    – destroy that image, with folder, after session expires

    Here is how I’ve created and stored the image:

    
    <?php
    
    $wp_session = WP_Session::get_instance();
    
    if ( !$wp_session['image_path'] && !$wp_session['temp_dir'] ) {
    
        // create random string for temporary directory
        function random_str( $length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ) {
            $str = '';
            $max = mb_strlen($keyspace, '8bit') - 1;
            for ($i = 0; $i < $length; ++$i) {
                $str .= $keyspace[random_int(0, $max)];
            }
            return $str;
        }
    
        // create temporary directory
        $random = random_str( 12 );
        $temp_dir = PAWR_TEMP_DIR . $random . '/';
        wp_mkdir_p( $temp_dir );
    
        // create temporary image, put in directory
        $file = $some_image_in_variable;
        file_put_contents( $temp_dir . $file->name, $file->get_raw() );
        $image_path = PAWR_TEMP_PUBLIC . $random . '/' . $file->name;
    
        $wp_session = WP_Session::get_instance();
        $wp_session['temp_dir'] = $temp_dir;
        $wp_session['image_path'] = $image_path;
    
    } else {
    
        $image_path = $wp_session['image_path'];
    
    }
    
    echo '<img src="' . $image_path . '" />';
    

    This works fine, but after I need to get rid of the image and temporary folder. So I thought that this would work:

    
    <?php
    
    // unlink image, delete image and directory
    add_action( 'wp_session_cleanup', 'delete_temporary_image' );
    
    function delete_temporary_image() {
    
        unlink( $wp_session['image_path'] );
        rmdir( $wp_session['temp_dir'] );
    
    }
    

    But it doesn’t work – the folder and image remain even after session expiry. Any suggestions?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Eric Mann

    (@ericmann)

    With versions greater than 3.0, this won’t work at all as sessions are cleaned up <i>natively</i> rather than through the plugin. That being said, the ‘wp_session_cleanup’ event runs <i>after</i> sessions are deleted, therefore there’s no session data to reference to delete the image.

    Thank you for clarifying – saves me a lot of time.

    What I might do is use the wp_logout hook to delete the image and end the session, setting an idle logout time that is shorter than when the session would expire.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Store image for session, delete on expiration’ is closed to new replies.