简体   繁体   中英

PHP 5.3.x - How do I turn the server path into its domain name, and a clickable URL?

I'm a newbie...sorry...I'll admit that I've cobbled this script together from several sources, but I'm trying to learn. :-) Thanks for any help offered!!

$directory = new \RecursiveDirectoryIterator(__DIR__, \FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new \RecursiveCallbackFilterIterator($directory, function ($current, $key, $iterator) {
  if ($current->getFilename() === '.') {
    return FALSE;
  } 
if ($current->isDir()) {
   return $current->getFilename() !== 'css';
}
  else {
    // Only consume files of interest.
    return strpos($current->getFilename(), 'story.html') === 0;
  }
});
$iterator = new \RecursiveIteratorIterator($filter);
$files = array();
foreach ($iterator as $info) {
  $files[] = $info->getPathname();
}
?>

Then down in my HTML is where I run into problems, in the 2nd echo statement...

<?php
  echo '<ul>';
  foreach ($files as $item){
  echo '<li><a href="' thedomain.com/directory/subdirectory/story.html '">http://<domain.com/directory/subdirectory/story.html></a></li>';
  echo '</ul>';
};
?>

The purpose of my script is to "crawl" a directory looking for a specific file name in sub-directories. Then, when it finds this file, to create a human-readable, clickable URL from the server path. Up to now, my HTML gets one of these two server paths as my list item:

http://thedomain.com/var/www/vhosts/thedomain.com/httpdocs/directory/subdirectory/story.html 

or

file:///C:/Bitnami/wampstack-5.5.30-0/apache2/htdocs/directory/subdirectory/story.html 

...depending on where I'm running my .php page.

I feel like I need to "strip away" part of these paths... to get down to /subdirectory/story.html ... If I could do that, then I think I can add the rest into my echo statements. Everything I've found for stripping strings has been from the trailing end of the path, not the leading end. (dirname($item)) takes away the filename, and (basename($item)) takes away the subdirectory and the filename ... the bits I want!!

Try this function

function strip($url){
    $info = parse_url($url);
    $slash = (explode('/',$info['path']));
    $sub = $slash[count($slash)-2];
    $file = basename($url)==$sub ? "" : basename($url);
    return "/".$sub."/".$file;
}

calling it by

echo strip('file:///C:/Bitnami/wampstack-5.5.30-0/apache2/htdocs/directory/subdirectory/story.html');

will result in

/subdirectory/story.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM