The WordPress codex states that “The file MUST be on the uploads directory”. I’ve added a line to move the uploaded file into the uploads directory and changed the guid path.
if( isset( $_POST['submit'] ) ) {
$filename = $_FILES['file']['name'];
$wp_filetype = wp_check_filetype( basename($filename), null );
$wp_upload_dir = wp_upload_dir();
// Move the uploaded file into the WordPress uploads directory
move_uploaded_file( $_FILES['file']['tmp_name'], $wp_upload_dir['path'] . "https://wordpress.stackexchange.com/" . $filename );
$attachment = array(
'guid' => $wp_upload_dir['url'] . "https://wordpress.stackexchange.com/" . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$filename = $wp_upload_dir['path'] . "https://wordpress.stackexchange.com/" . $filename;
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}