Save image to server from a URL

2019-03-02 12:16发布

问题:

I've built a mini-content management system with CKEditor. The user has the ability to paste an image URL from another website. Is there a way to to get all image URLs when the user submits the content, save all these images to the server, and replace another server's URL with URL of my server?

For example, the user wrote something like this:

<img src="somews.com/img1.jpg"/>Lorem Ipsum is simply dummy text of the printing and typesetting industry. ...

During the submit process PHP would save the image from somews.com/img1.jpg to the server, converts its URL to myserver.com/photos/img1.jpg and replaces <img src="somews.com/img1.jpg"/> with .. Is that possible?

回答1:

If you have PHP5 and the HTTP stream wrapper enabled on your server, it's incredibly simple to copy it to a local file:

copy('http://somedomain.com/file.jpeg', '/tmp/file.jpeg');

This will take care of any pipelining etc. that's needed. If you need to provide some HTTP parameters there is a third 'stream context' parameter you can provide.