How to save image from URL using PHP

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to save image from URL using PHP

You have an image in a URL, something like “http://www.yourhowto.net/wp-content/uploads/2012/09/mysql-java-jdbc1.jpg“, and you want to save that image in your computer, but you want to obtain that directly from PHP. You can use 2 methods for this, one is using CURL and one using fopen directly.

First method

To use this method, CURL extension needs to be installed in your php environment, normally, all hosters would have this enabled. Create a php file with the bellow script and you are done.

Second method

To use this method, you have to set allow_url_fopen to on. The allow_url_fopen directive is disabled by default. You should be aware of the security implications of enabling the allow_url_fopen directive. PHP scripts that can access remote files are potentially vulnerable to arbitrary code injection.

When the allow_url_fopen directive is enabled, you can write scripts that open remote files as if they are local files. To enable this functionality, use a text editor to modify the allow_url_fopen directive in the php.ini file as follows:

To disable this functionality, modify the allow_url_fopen directive in the php.ini file as follows:

So, with this activated, you can use the following snippet.

Do however keep in mind, this must only be used for your own purpose only, I don’t really recommend using these on a production environment due to the security risks involved.

If you have further questions, please comment bellow.

Request an article ←