Home >Backend Development >PHP Tutorial >Relative path to network absolute path (supports second-level domain name) ./a.jpg => http://www.w.com/a.jpg

Relative path to network absolute path (supports second-level domain name) ./a.jpg => http://www.w.com/a.jpg

WBOY
WBOYOriginal
2016-07-25 08:48:581538browse
Yesterday, when I was writing about using Thunder to download, I found that the ./a.jpg file converted to Thunder was not the network address, so I wrote a method to convert it. I am currently at the basic level of PHP, so I would like to ask for help if I have any deficiencies.
It will automatically determine the current domain name and main domain name. The following is the form:
./a.jpg => http://about.w.com/a.jpg;
../a.jpg => http:// www.w.com/a.jpg
  1. /**
  2. * Convert relative path to network absolute path
  3. * @param string $file
  4. * @return string
  5. */
  6. function dirToHttpUrl($file) {
  7. //Determine whether the file exists
  8. if (!file_exists($file)) {
  9. return false;
  10. }
  11. //Domain name
  12. $nowUrl = dirname('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); //Current domain name
  13. $tempUrl = explode('.', $_SERVER['HTTP_HOST' ]);
  14. $dirUrl = 'http://www.'.$tempUrl[1].'.'.$tempUrl[2].'/'; //Main domain name
  15. //Level statistics of file paths
  16. $tempFile = explode('../', $file);
  17. $tempNum = array_count_values($tempFile);
  18. if (array_key_exists('', $tempNum)) {
  19. $fileNum = $tempNum[''];
  20. $fileEnd = end($tempFile);
  21. } else {
  22. $fileNum = 0;
  23. $fileEnd = '/'.substr($tempFile[0], 2);
  24. }
  25. //Domain name level statistics
  26. $ tempWeb = explode('/', $nowUrl);
  27. $tempWeb = array_slice($tempWeb, 3);
  28. $webNum = count($tempWeb);
  29. //Domain name corresponding to the file
  30. if ($fileNum > $ webNum) {
  31. $nowUrl = $dirUrl;
  32. }
  33. //Return
  34. return $nowUrl.$fileEnd;
  35. }
  36. //dirToHttpUrl('./1.jpg');
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn