Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all articles
Browse latest Browse all 8245

shazdeh on "media_handle_sideload kills the page without any errors"

$
0
0

This is a weird issue. I've made a little function to download an image from an external source and add it as an attachment. Here's the code:

function download_image_copy( $url, $desc = '' ) {
	require_once(ABSPATH . 'wp-admin/includes/file.php');
	require_once(ABSPATH . 'wp-admin/includes/media.php');

	$types = 'jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG';
	$file_array = array();

	$file_array['tmp_name'] = download_url( $url );
	if( is_wp_error( $file_array['tmp_name'] ) ) {
		@unlink( $file_array['tmp_name'] );
		return $url;
	}

	$pathparts = pathinfo( $file_array['tmp_name'] );
	$file_array['name'] = basename( $url );
	// fix file extension
	if( '' == $pathparts['extension'] || ! in_array( $pathparts['extension'], explode( '|', $types ) ) ) {
		$_file = $pathparts['dirname'] . DS . $file_array['name'];
		rename( $file_array['tmp_name'], $_file );
		$file_array['name'] = basename( $_file );
		$file_array['tmp_name'] = $_file;
	}

	$id = media_handle_sideload( $file_array, 1, $desc );
	echo 'Wow! We never reach this place!';

	if( is_wp_error( $id ) ) {
		@unlink( $file_array['tmp_name'] );
		return $url;
	}

	$src = wp_get_attachment_url( $id );
	return $src;
}

// let's try it out
echo download_image_copy( 'http://dribbble.s3.amazonaws.com/users/81899/screenshots/1170460/untitled-1.png' );

Sidenote: Sorry for pasting this code here. I can't access PasteBin.

The page stops just after calling the media_handle_sideload function, it actually never reaches that echo statement in the next line. I have enabled the debug mode but it doesn't display any errors.
That "fix file extension" block in the code was added because for me the download_url returns any file with an extension of "tmp" and so media_handle_sideload function was throwing "wrong media type" error. I have inspected the $file_array var and the path to the file and it's name are correct and exists on my filesystem.

Thanks for shedding any light on this.


Viewing all articles
Browse latest Browse all 8245

Trending Articles