Possible duplicate of this question. You need to use a variety of built-in WordPress functions for this:
wp_insert_attachment()
set_post_thumbnail()
wp_generate_attachment_metadata()
wp_update_attachment_metadata()
wp_insert_attachment()
is probably your most important function as it returns your attachment (image) ID. set_post_thumbnail()
then takes this attachment ID and your post ID to set the image as the featured image in the post.
When I've done this in the past I also found that I had to use the metadata functions above to correctly assign the image which from memory was for removing posts from an import and their associated images. For a complete example for this see here
file_put_contents($oldfile, $image_data);
rename( $oldfile, $newfile );
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $newfile, $post_id );
if ( $set_thumb ) {
$res2= set_post_thumbnail( $post_id, $attach_id );
}
$attach_data = wp_generate_attachment_metadata( $attach_id, $newfile );
$update_attach_metadata = wp_update_attachment_metadata( $attach_id, $attach_data );