See media_handle_sideload
in Codex:
$url = "http://s.wordpress.org/style/images/wp3-logo.png";
$tmp = download_url( $url );
$post_id = 1;
$desc = "The WordPress Logo";
// Set variables for storage
// fix file filename for query strings
preg_match(\'/[^\\?]+\\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/\', $file, $matches);
$file_array[\'name\'] = basename($matches[0]);
$file_array[\'tmp_name\'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array[\'tmp_name\']);
$file_array[\'tmp_name\'] = \'\';
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $post_id, $desc );
// If error storing permanently, unlink
if ( is_wp_error($id) ) {
@unlink($file_array[\'tmp_name\']);
return $id;
}
$src = wp_get_attachment_url( $id );