Wordpress - Programmatically get images by URL and save in uploads folder
There's actually a great function that will do all three of those things for you:
media_sideload_image( $url, $post_id, $description );
The first argument is the remote url of the image you want to download. The second argument is the post id of the post to which you want to attach the image. The third argument is optional, but will be a description if included.
I'd suggest finding a way to throttle the downloads so that you don't keep timing out, such as limiting the number of images it pulls in per load and setting the importer to refresh itself between downloads, or using AJAX to do them one at a time asynchronously.
John's answer is correct re: using media_sideload_image
, just note that you may need to require these scripts before if you aren't doing this within the context of WP Admin:
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
See https://codex.wordpress.org/Function_Reference/media_sideload_image#Notes