How to save an image from a URL in PHP? Function doesn't work with some images
Hello everyone. I'm a beginner in PHP and encountered a problem when saving images from external URLs. I'm writing a simple parser for downloading user avatars.\n\nI have this code:\n\n```php\n$url = 'https://example.com/avatar.jpg';\n$image = file_get_contents($url);\nfile_put_contents('avatars/user1.jpg', $image);\n```\n\nIt works with some sites, but not with others – it returns an empty file or an error. I've tried different approaches:\n\n1. Used `copy($url, $local_path)` – also doesn't always work.\n2. Tried via CURL, but that's even more confusing.\n3. Some images are saved as corrupted (can't be opened).\n\nI suspect the issue is that the server might be blocking direct requests or requires User-Agent headers. I've also noticed that if the URL contains Cyrillic characters or p
No answers yet.
Log in to leave an answer