There may come a time when there is a file in your uploads folder with no matching attachment post in the database. As unlikely as this is, it could happen, and when it does, it’s not clear how the upload mechanisms work.
I came across a similar problem myself, here’s my code:
View the code on Gist.
This is derived from the code that runs after wp_handle_upload is fired with some modifications.
If afterwards you want to attach the file to a post, simply modify the $parent_id variable. To set an image as the featured image of said parent post, you can do the following at the end:
update_post_meta($parent_id, '_thumbnail_id', $id);
It might seem tempting to use this to add arbitrary files from outside the uploads directory using this mechanism, but I would avoid it. There are real benefits to having all modifiable content centralised in the File system.
I’ll post more on the subject in the coming months, until then here’s a list of useful functions to know: