PHP function: Determine whether the remote file has an instance code

Source: Internet
Author: User
Tags file url

This article introduces PHP functions-how to determine whether a remote file exists in the instance code

  1. <? Php
  2. /*
  3. Function: remote_file_exists
  4. Function: determines whether a remote file exists.
  5. Parameter: $ url_file-Remote File URL
  6. Return: If yes, true is returned. If not, false is returned for other reasons.
  7. */
  8. Function remote_file_exists ($ url_file ){
  9. // Check input
  10. $ Url_file = trim ($ url_file );
  11. If (empty ($ url_file) {return false ;}
  12. $ Url_arr = parse_url ($ url_file );
  13. If (! Is_array ($ url_arr) | empty ($ url_arr) {return false ;}
  14. // Obtain request data
  15. $ Host = $ url_arr [host];
  16. $ Path = $ url_arr [path]. "? ". $ Url_arr [query];
  17. $ Port = isset ($ url_arr [port])? $ Url_arr [port]: "80 ";
  18. // Connect to the server
  19. $ Fp = fsockopen ($ host, $ port, $ err_no, $ err_str, 30 );
  20. If (! $ Fp) {return false ;}
  21. // Construct the request protocol
  22. $ Request_str = "GET". $ path. "HTTP/1.1 ";
  23. $ Request_str. = "Host:". $ host ."";
  24. $ Request_str. = "Connection: Close ";
  25. // Send the request
  26. Fwrite ($ fp, $ request_str );
  27. $ First_header = fgets ($ fp, 1024 );
  28. Fclose ($ fp );
  29. // Determine whether a file exists
  30. If (trim ($ first_header) = "") {return false ;}
  31. If (! Preg_match ("/200/", $ first_header )){
  32. Return false;
  33. }
  34. Return true;
  35. }
  36. // Test code
  37. $ Str_url = http://www.ite5e.com/newsinfo.php? Nid = 1493;
  38. $ Exits = remote_file_exists ($ str_url );
  39. Echo $ exists? "Exists": "Not exists ";
  40. ?>

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.