Your going about this the wrong way.
Your opening the same file each time in append mode,
and appending the data to the file.
You want to open a file in write mode so it will create a new file each time.
Here is an example that will validate the URL before it creates the file.
If it doesn't validate, it won't create a file.
This will validate most common URL's but not all.
I am sure someone else can come up with a better regex.
Example: