WordPress PHP custom function is causing 500 Internal Server Error Connection Timeout

This function is completely unnecessary, and can be replaced with the official WP function called media_sideload_image:

media_sideload_image( string $file, int $post_id, string $desc = null, string $return = ‘html’ )

for example:

$new_image_id = media_sideload_image(
    "https://example.com/image.png",
    $post_id,
    "Toms great picture",
    'ID'
);

https://developer.wordpress.org/reference/functions/media_sideload_image/

Don’t forget to check the result, if this fails it will return a WP_Error object, and you must handle it. The error object contains the message telling you what went wrong, and it’s why your original code failed mysteriously ( it never checked for errors so if one happened it didn’t say anything ).

If you want to use this outside WP Admin, you’ll need to include one or two files before using it. Read the official documentation for how to do that