Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Buscador

Estas en el tema de Buscador en el foro de PHP en Foros del Web. Buenas noches : Tengo una página de música muy simple, es de archivos .mid. Tiene un buscador Real Time Full Text Search, que funciona bien. ...
  #1 (permalink)  
Antiguo 20/02/2013, 19:47
Avatar de horizon  
Fecha de Ingreso: septiembre-2012
Mensajes: 9
Antigüedad: 11 años, 6 meses
Puntos: 0
Buscador

Buenas noches:

Tengo una página de música muy simple, es de archivos .mid. Tiene un buscador Real Time Full Text Search, que funciona bien.

Quisiera que en vez de mostrar las paginas .htm, me muestre solo los archivos de música .mid.

Espero que puedan ayudarme, les dejo un link de pruebas,
http://testingbusca.p.ht

Desde ya, muchas gracias

Código PHP:
  <?php
/* Easy Real Time Full Text Search © 2012 Christer Svensson

---------------------------------------------- Instructions -------------------------------------------------------------------------------------------

 If the name of this file not is easy.php then rename it to easy.php

 Upload it to the directory (folder) on your homepage server that you want to search through.

 The PHP-script in this file performs a real time full text search of every htm, html, asp,
 and php file in the directory (folder) and all subdirectories (subfolders). The search is
 not case sensitive.

 The text displayed in the browser window is searched. For that reason, in the html code, all
 text in tags are omitted and also text between the tag and the end tag for head, script, noscript
 and iframe.

 You may translate the text (string values) in this file to your native language without the
 author's permission. If you do so, please send a copy to [email protected] and it
 will be published on the homepage of this script.

 You may also use another CSS style and you may include the script as a natural part at pages at
 your site.

*/

// You may translate the string values here under to your native languages. 

$buttonvalue "Search";
$search_at "Search on";
$search_result "gave this result";
$pages "Number of pages with hits";
$to_small "At least two characters is required";
$recursive true;  // Change to false if no searching should be done in subdirectories.

//---------------------------- Do not change anything below this line -------------------------------------------------------------------------------

$html = <<<HTML
<p><br /></p>
<form name="form" action="">
<input type="text" name="search" size="30" /> 
<input type="button" value="$buttonvalue" 
 onclick='window.location.assign(document.URL.substring(0,document.URL.indexOf("?")) + "?search=" + document.form.search.value.replace(/ /g,"%20"))' />
</form>
<!-- Please do not remove or change this link to the application's site. Others might like it too. -->
<br />
HTML;

echo 
$html;

function 
textpart($body$search) {
// Displays the text after the title
  
$length 30;
  
$text substr($bodymax(stripos($body,$search) - $length0), strripos($body,$search) - stripos($body,$search) + strlen($search) + $length);
  if (
strripos($text" ") < strripos($text,$search)) {
    
$text $text " ";
  }
  if (
stripos($text" ") != strripos($text" ")) {
    
$text substr($textstripos($text" "), strripos($text" ") - stripos($text" "));
  }
  
$temp $text;
  
$stop substr($textstrripos($text$search) + strlen($search));
  if (
strlen($stop) > $length) {
    
$stop substr($textstrripos($text$search) + strlen($search), $length);
    
$stop substr($stop0strripos($stop" "));
  }
  
$text "... ";
  while (
stripos($temp,$search)) {
    
$temp substr_replace($temp"<b>"stripos($temp$search), 0);
    
$temp substr_replace($temp"</b>"stripos($temp$search) + strlen($search), 0);
    
$text $text substr($temp0stripos($temp"</b>") + 4);
    
$temp substr($tempstripos($temp"</b>") + 4);
    if(
stripos($temp$search) > ($length)) {
       
$text $text substr($temp0$length);
       
$text substr($text0strripos($text" ")) . " ... ";
       
$temp substr($tempstripos($temp$search) - $length);
       
$temp substr($tempstripos($temp" "));
    }
  }
  
$text $text $stop " ... ";
  echo 
$text
  return;
}

function 
compress($string$first$last) {
// Removes everything in $string from $first to $last including $first and $last
  
while(stripos($string,$first) && stripos($string,$last)) {
    
$string substr_replace($string""stripos($string,$first), stripos($string,$last) - stripos($string,$first) + strlen($last));
  }
  return 
$string;  
}

function 
directoryToArray($directory$recursive) {
// This function by XoloX was downloaded from http://snippets.dzone.com/user/XoloX
  
$array_items = array();
  if (
$handle opendir($directory)) {
    while (
false !== ($file readdir($handle))) {
      if (
$file != "." && $file != "..") {
        if (
is_dir($directory"/" $file)) {
          if(
$recursive) {
            
$array_items array_merge($array_itemsdirectoryToArray($directory"/" $file$recursive));
          }
        } else {
          
$file $directory "/" $file;
          
$array_items[] = preg_replace("/\/\//si""/"$file);
        }
      }
    }
    
closedir($handle);
  }
  return 
$array_items;
}

function 
filewalk($file$search$counter$webpath) {
// Selects and treats files with the extension .htm and .html and .asp and .php
  
if (strtolower(substr($filestripos($file".htm"))) == ".htm"
      
|| strtolower(substr($filestripos($file".html"))) == ".html"
      
|| strtolower(substr($filestripos($file".asp"))) == ".asp"
      
|| strtolower(substr($filestripos($file".php"))) == ".php") {
    
$all file_get_contents($file);
    
$body substr($allstripos($all,"<body"),stripos($all,"</body>") - stripos($all,"<body"));
    
$body preg_replace('/<br \/>/i'' '$body);
    
$body preg_replace('/<br>/i'' '$body);
    
$body compress($body,"<noscript","</noscript>");
    
$body compress($body,"<script","</script>");
    
$body compress($body,"<iframe","</iframe>");
    
$body compress($body,"<noframe","</noframe>");
    
$body strip_tags($body);
    
$body html_entity_decode($bodyENT_QUOTES);
    
$body preg_replace('/\s+/'' '$body);
    
// Scans and displays the results
    
if (stripos($body$search)) {
      
$title substr($allstripos($all,"<title>") + 7,stripos($all,"</title>") - stripos($all,"<title>") - 7);
      
$title html_entity_decode($titleENT_QUOTES);
      
$title preg_replace('/\s+/'' '$title); 
      echo 
'<p><a href="' $file '">' $title '</a></br>';
      echo 
'<span id="webpath">' $webpath substr($filestripos($file"/")) . '</span><br />';
      echo 
textpart($body$search) . '</p>';
      
$counter $counter 1;
    }
  }
  return 
$counter;
}

// Reads the search text from the page's URL
$url $_SERVER['HTTPS'] == 'on' 'https://' 'http://';
$url .= $_SERVER['SERVER_PORT'] != '80' $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"] : $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

if (
stripos($url,"?search=")) $search $_GET['search'];

$webpath dirname($url);

// Starts searching
if (strlen($search) < && trim($search) <> "") {
  echo 
'<p>' $to_small '!</p>';
  
$search "";
}

if (
trim($search) <> "") {
  echo 
"<p>" $search_at " '<b>" $search "</b>' " $search_result ".</p>";
  
$counter 0;
  
// Path to the folder containing this file
  
$curdir getcwd();
  
// Opens the folder and read its contents
  
if ($dir opendir($curdir)) {
    
$files directoryToArray("./"$recursive);
    foreach (
$files as $file) {
      
$counter filewalk($file$search$counter$webpath);
    }
    
closedir($dir);
  }
  echo 
"<p>" $pages ": " $counter "</p>";
}
?>

Última edición por horizon; 20/02/2013 a las 19:54
  #2 (permalink)  
Antiguo 20/02/2013, 19:57
marcofbb
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Buscador

Podes hacer un condicional (IF) que haga cualquiera de esta forma
- Si el nombre del archivo contiene .mid agregarlo al array
- Si no contiene el nombre del archivo el texto .html agregarlo al array
- Con filetype, si el archivo es HTML no agregarlo al array
- Con filetype, si el archivo es MID agregarlo al array

PD: Consejo para la próxima, no publicar todo el código, sino solo la parte que en verdad sirve como dato para responder a la pregunta realizada

Saludos
  #3 (permalink)  
Antiguo 23/02/2013, 15:43
Avatar de horizon  
Fecha de Ingreso: septiembre-2012
Mensajes: 9
Antigüedad: 11 años, 6 meses
Puntos: 0
Respuesta: Buscador

Buenas tardes:

Muchas gracias por responder marcofbb.

Cita:
Podes hacer un condicional (IF) que haga cualquiera de esta forma
- Si el nombre del archivo contiene .mid agregarlo al array
- Si no contiene el nombre del archivo el texto .html agregarlo al array
- Con filetype, si el archivo es HTML no agregarlo al array
- Con filetype, si el archivo es MID agregarlo al array
Desculpen responder recien ahora, estaba buscando información pq no se del tema, encontre esto.

Código PHP:
// add to array $arquivos
while($fn readdir($mydir)) {
if (
is_dir($fn))
continue;
if (
$fn == $exclude[.htm])
continue;
$arq basename ($fn,".mid");
$arquivos[] = $arq;

- Seria esto lo que tengo que colocar?
Donde iria? me pueden ayudar a armar el codigo

Gracias p su tiempo !
  #4 (permalink)  
Antiguo 03/03/2013, 16:16
Avatar de horizon  
Fecha de Ingreso: septiembre-2012
Mensajes: 9
Antigüedad: 11 años, 6 meses
Puntos: 0
Respuesta: Buscador

Buenas noches:

Queria agradecer p su ayuda y p su tiempo. Sinceramente no consegui hacer las modificaciones que me sugirieron, pq mis conocimientos son básicos.
Encontre un buscador, este es el código:

Código PHP:
Ver original
  1. <?php
  2.  
  3. $url = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
  4. $url .= $_SERVER['SERVER_PORT'] != '80' ? $_SERVER["SERVER_NAME"] .
  5.  
  6. ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"] : $_SERVER
  7.  
  8. ['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  9. $urlPath = explode("php/", $url);
  10. $dir = 'files/'; //define your folder to search, for default is files
  11. $files = scandir("../" . $dir); //if the folder "files" isn't in raiz
  12.  
  13. please change "../"
  14. $ele = array();
  15. $total = count((array) $files);
  16.  
  17. function file_get_contents_curl($url) {
  18.     $ch = curl_init();
  19.     curl_setopt($ch, CURLOPT_HEADER, 0);
  20.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  21.     curl_setopt($ch, CURLOPT_URL, $url);
  22.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  23.  
  24.     $data = curl_exec($ch);
  25.     curl_close($ch);
  26.  
  27.     return $data;
  28. }
  29.  
  30. foreach ($files as $key => $value) {
  31.     $html = file_get_contents_curl($urlPath[0] . $dir . $value);
  32.     $doc = new DOMDocument();
  33.     @$doc->loadHTML($html);
  34.     $nodes = $doc->getElementsByTagName('title');
  35.  
  36.     $title = $nodes->item(0)->nodeValue;
  37.  
  38.     $metas = $doc->getElementsByTagName('meta');
  39.  
  40.     for ($i = 0; $i < $metas->length; $i++) {
  41.         $meta = $metas->item($i);
  42.         if ($meta->getAttribute('name') == 'description')
  43.             $description = $meta->getAttribute('content');
  44.         if ($meta->getAttribute('name') == 'keywords')
  45.             $keywords = $meta->getAttribute('content');
  46.     }
  47.     $t = substr(strrchr($value, '.'), 1);
  48.     if ($t) {
  49.         $file = $urlPath[0] . $dir . $value;
  50.         if (strtolower(substr($file, stripos($file, ".htm"))) ==
  51.  
  52. ".htm" || strtolower(substr($file, stripos($file, ".html"))) ==
  53.  
  54. ".html" || strtolower(substr($file, stripos($file, ".asp"))) ==
  55.  
  56. ".asp" || strtolower(substr($file, stripos($file, ".php"))) ==
  57.  
  58. ".php") {
  59.             $obj = array(
  60.                 "title" => $title,
  61.                 "link" => $file,
  62.                 "description" => $keywords
  63.             );
  64.             array_push($ele, $obj);
  65.         } else {
  66.             $obj = array(
  67.                 "title" => $value,
  68.                 "link" => $file,
  69.                 "description" => "image"
  70.             );
  71.             array_push($ele, $obj);
  72.         }
  73.     }
  74.  
  75.     if ($total - 1 === $key) {
  76.         print json_encode($ele);
  77.     }
  78. }
  79. ?>


El buscador, realiza la busqueda en los archivos que se encuentran en la carpeta files.
El problema surge cuando agrego carpetas en la carpeta files ejemplo:

files/Ac_Dc
files/Aerosmith
files/Black_Sabbath

Quisiera saber como modificar la ruta, para que busque en la carpeta files y en todas las carpetas que voy agregando en ella.

Desde ya muchas gracias por su tiempo y por su ayuda. Disculpen insistir, pero realmente necesito que funcione, buenas noches p tds.

Etiquetas: buscador, html, select
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 19:14.