PHP cross-domain upload images

Source: Internet
Author: User

Because to upload all uploaded images to a separate picture server above, JS upload there is a cross-domain problem, find this online, through the PHP curl, the picture is sent to another server to save, and return the picture Path!


There are some problems with this approach:
1, upload large pictures, such as 2M, you need to upload the image first to the server, and then to the image server, the middle needs 4M transmission, increase the upload time!
2, from the server to the picture server because there is no save, the transfer is using temporary files, taking into account the picture format restrictions, the image has been renamed, after the transfer of the image to delete, encountered some unknown problem is likely to cause the picture deletion failure, increase the server storage space!


The code is as follows:

[HTML]View PlainCopy 
  1. Public function upload ($files = ') {
  2. if ("files = = =") {
  3. $files = $_files;
  4. }
  5. if (empty ($files)) {
  6. $this->error = ' no uploaded files!  ‘;
  7. return false;
  8. }
  9. $ext = pathinfo (strip_tags ($files [' file '] [' name ']), pathinfo_extension);
  10. $new_name = dirname ($files [' file '] [' tmp_name ']). ' /'. Date ("Ymdhis"). Rand (0,99). ".".  $ext;
  11. Rename ($files [' file '] [' tmp_name '], $new _name);
  12. $fields [' img '] = ' @ '. $new _name;
  13. Initialize Curl
  14. $ch = Curl_init ();
  15. curl_setopt ($ch, Curlopt_url, $this->url);
  16. curl_setopt ($ch, Curlopt_post, 1);
  17. curl_setopt ($ch, Curlopt_postfields, $fields);
  18. curl_setopt ($ch, Curlopt_returntransfer, TRUE);
  19. Run Curl
  20. $R = curl_exec ($ch);
  21. Curl_close ($ch);
  22. @unlink ($new _name);
  23. if ($r) {
  24. Return Json_decode ($r, true);
  25. }else{
  26. $this->error = "Request Failed";
  27. return false;
  28. }
  29. }

PHP cross-domain upload images

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.