Upload Image From URL via PHP (In a safe way)
I'm trying to make a simple code to upload an image directly from a
url.

You mean download.

How I can make it more safe?

Is there any reason why you want to retain the original file name, after applying the basename function ? This should protect against basic path traversal attempts like ../../
but you could as well rename the file altogether. If you are storing a record in a database, using an ID would be a good choice + adding the file extension (but not allow any file extension - see below).
This would be better than taking a chance and figuring out the possible pitfalls with your function. You are not controlling the file name and trusting user input is where the danger lies.
Not to mention that there may some creative attempts involving Unicode characters or whatever. Easier said than done, but I can't guarantee your code is 100% safe at this point.
The biggest problem here is that someone could supply the URL of a webshell with a .php extension, that your script will happily download to the upload folder. If that folder is under your website root, an attacker may then be able to call http://example.com/upload/shell.php to and take over your server. It's something you can test easily.
Because that's what your script does, it will download anything upon request.
At a minimum, that upload folder should not be under the website root. So the problem is not just the file name but the extension, and where that upload folder resides.
Also, there is no guarantee that the filename will be unique. You seem to be handling the scenario in some way that we don't know about.