Store image for session, delete on expiration
-
I am trying to…
– store an image in a temp folder created for the session, and
– destroy that image, with folder, after session expiresHere 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)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘Store image for session, delete on expiration’ is closed to new replies.