[ Поиск ] - [ Пользователи ] - [ Календарь ]
Полная Версия: Поиск по сайту. Не добавляется в базу mysql проиндексированное
M-I-X-E-R
bc.gif Народ помоге решить проблему.
Есть поиск на сайте http://www.thirteen.ru/ , есть скрипт индексации сайта (см.код). Скрипт делает:
1.Создаёт структуру сайта и кладёт в файл struct.txt
2. Индексирует а потом
3. Вносит в базу "tmp" в ней поля (id, link, text, title)

Но на практике совсем другое. Структуру создаёт а вот индексировать и внести в базу не хочет. В чём проблема и помогите дописать код.

Если внести руками в базу что либо руками, то при поиске по сайту естественно выдётся. Поиск на сайте ищет по полю text.


Код
<?
#include("$DOCUMENT_ROOT/manage/inc/auth.php");
include("$DOCUMENT_ROOT/manage/inc/connection.php");
#include("$DOCUMENT_ROOT/manage/inc/class.php");
#include("$DOCUMENT_ROOT/manage/inc/functions.php");

$title = "Поиск — Переиндексация";
$table = "tmp";
$fileStruct = "tmp/struct.txt";
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>

<? include "inc_head.php"; ?>

<tr>
    <td colspan="2" bgcolor="#cc0000">
        <div class="z1" style="color: #ffffff; margin-left: 10px; margin-top: 5px; margin-bottom: 5px;">
        <b>Переиндексация</b>
        </div>
    </td>
</tr>
<tr>
    <td colspan="2" bgcolor="#fd7f0f"><img src="/pics/clear.gif" width=1 height=5 border=0 alt=""><br></td>
</tr>
    <tr>
        <td bgcolor="#eeeeee" width="20%" valign="top">
            <? include "inc_nav.php"; ?>
        </td>
        <td bgcolor="#ffffff" valign="top">
            <br>
            <div class="t1" style="margin-left: 20px; margin-right: 20px;">

            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                    <td width="100%">
                        <div class="t1">
                        
                        <?
                        if(!isset($step)) $step = 0;
                        
                        if($step == 0)
                        {
                            echo "1. <a href=\"$PHP_SELF?step=1\" class=\"t1\">Построение структуры сервера</a><br>";
                            echo "2. Переиндексация страниц<br>";
                        }
            
                        if($step == 1)
                        {
                            echo "1. Построение структуры сервера - OK<br>";
                            echo "2. <a href=\"$PHP_SELF?step=2\" class=\"t1\">Переиндексация страниц</a><br>";
                            
                            // строим структуру
                            $index_page = "index.php";
                            $server = $_SERVER['SERVER_NAME'];
                            
                            $url = "http://".$server."/".$index_page;    
                            
                            $already = array(); $global = array();
                
                            getlinks($url);
                            
                            for($i=0; $i<count($global); $i++) getlinks($global[$i]);
                            for($i=0; $i<count($global); $i++) getlinks($global[$i]);
                            
                            $f = fopen($fileStruct, "w");
                            for($i=0; $i<count($global); $i++)
                            {
                                fwrite($f,$global[$i]."\n");
                                //echo $global[$i]."<br>";
                            }
                            fclose($f);
                        }
            
                        if($step == 2)
                        {
                            echo "1. Построение структуры сервера - OK<br>";
                            echo "2. Переиндексация страниц - OK<br>";
                            
                            save();
                        }
                        ?>
            
                        <br><br>
                        </div>        
                    
                    </td>
                </tr>
            </table>
            
            </div>
            <br>
        </td>
    </tr>

<? include "inc_end.php"; ?>

</body>
</html>

<?
///////////////////////////////////////////////////////////////////////
function save()
{
    global $table, $fileStruct;
    
    if(!file_exists($fileStruct)) die("Структура не найдена");
    
    $result = file($fileStruct);
    mysql_query("DELETE FROM $table");

    for($i=0;$i<count($result);$i++)
    {
        $result[$i] = chop($result[$i]);                            // пробел в конце уберем
        $ext = preg_replace("/.*\.(\w*).*/","\\1",$result[$i]);     // возьмем расширение файла
        
        if($ext == "php" || $ext == "html" || $ext == "html" || $ext == "shtml")
        {
            // вытащим заголовок
            $f = @fopen($result[$i], "r");
            if($f)
            {    
                while(!feof($f))
                {
                    $str = fgets($f, 256);
                    if(ereg("title",$str))
                    {
                        $title = ereg_replace("<title>(.*)</title>","\\1",$str);
                        break;
                    }
                }
                fclose($f);
            }

            // контент
            $f = @fopen(chop($result[$i]),"r");
            if($f)
            {    
                echo "<br><strong>$result[$i] сохранен</strong>";
                
                $text = "";
                while(!feof($f))
                {
                    $str = chop(fgetss($f,1024));
                    if(!empty($str)) $text .= $str;
                }
                fclose($f);
                $text = ereg_replace("\"","&quot;",$text);
                $text = ereg_replace("'","&quot;",$text);
                mysql_query("INSERT INTO $table(link, text, title) VALUES('$result[$i]', '$text', '$title')");
            }
            //else echo "<br><strong>".($i+1)." $result[$i]</strong> <font color=#FF0000>не найден</font>";
        }
        else echo "<br><strong>$result[$i]</strong> <font color=#FF0000>формат не поддерживается</font>";
    }
}

///////////////////////////////////////////////////////////////////////
function getlinks($file)
{
    global $global, $server, $index_page, $already;
    
    $res = array();
    
    $type = ereg_replace(".*\.(.*)","\\1",$file);    // вырезаем тип файла все после .
    $type = ereg_replace("\?.*","",$type);            // если идут параметры после ? - вырежем
    
    // выбираем только нужный тип
    if($type == "php" or $type == "html" or $type == "htm" or $type == "shtml" or $type == "shtm")
    {
        if(!in_array($file,$already))            // если данный файл уже анализировали        
        {
            array_push($already,$file);
            
            $str = @implode ('', file ($file));
            
            preg_match_all("!<a.*?href=\"?'?([^ \"'>]+)\"?'?.*?>(.*?)!is",$str,$ok);
            
            for ($i=0; $i<count($ok[1]); $i++)
            {
                $s = $ok[1][$i];
                $s = ereg_replace("^(/.*)","http://".$server."\\1",$s);    // ссылки типа /cat/index.php -> http://сервер/cat/index.php
                $s = ereg_replace("(.*)/$","\\1/".$index_page,$s);
                
                //echo $s."<br>";
                
                if(!ereg("javascript",$s)                                  // исключаем: javascipt
                and !ereg("#",$s)                                             // #
                and !ereg("mailto",$s)                                    // mailto
                and ereg($server,$s)                                // чужой сервер
                and !ereg(".*".$server."$",$s))                  // сервер типа http://$SERVER_NAME - стартовая страница
                array_push($res,$s);
                
                $tmp = explode(".",$s);
                if(count($tmp) == 2)
                {
                    $tmp[1] = ereg_replace("\?.*","",$tmp[1]);            // если идут параметры после ? - вырежем
                    if($tmp[1] == "php" or $tmp[1] == "html" or $tmp[1] == "shtml" or $tmp[1] == "htm" or $tmp[1] == "shtm")
                    {
                        $s2 = ereg_replace("(.*/).*","\\1".$s,$file);
                        array_push($res,$s2);
                    }
                }
            }
        }
        //else  echo "<b>уже анализирован: $file</b><br>";
    }
    //else echo "<b>анализ: $file ($type) - формат не тот</b><br>";
    
    $x = count($res);
    // удаляем дубликаты
    $res = array_unique($res);
    // делаем слияние непустых элементов
    for($i=0; $i<$x; $i++) if(!empty($res[$i]) and !in_array($res[$i],$global)) array_push($global, $res[$i]);
    sort($global);
}
?>




Спустя 17 часов, 36 минут, 54 секунды (31.10.2007 - 11:55) md5 написал(а):
Цитата
$ext == "html" || $ext == "html"

круто

простите, но код впадлу читать

Спустя 2 года, 25 дней, 15 часов, 34 минуты, 19 секунд (27.11.2009 - 03:29) Гость_Александр написал(а):
У меня похожая проблема хочу занести даные в базу но почемуто в базу даные не попадяют вот сокращёная версия кода
Первая страница
<h1>Задайте свой вопрос </h1>
<form name="true" method="post" action="otvet.php">
<p>
<label>Введите имя<br>
<input type="text" name="autor" id="autor">
</label>
</p>
<p>
<label>Введите майл<br>
<input type="text" name="mail" id="mail">
</label>
</p>
<p>
<label>Введите Вопрос<br>
<textarea name="text" id="text" cols="45" rows="5"></textarea>
</label>
</p>
<label>
<input type="submit" name="submit" id="submit" value="Отправи">
</label>

</form>
Вторая
<?
include("blok/bd.php");
if (isset($_POST['autor'])){$autor = $_POST['autor']; if ($autor == ''){unset($autor);}}
if (isset($_POST['mail'])){$mail = $_POST['mail'] ; if ($mail == ''){unset($mail);}}
if (isset($_POST['text'])){$text = $_POST['text'] ; if ($text == ''){unset($text);}}
?>

.....

<?php

if (isset($autor) && isset($text) && isset($mail))
{
$result = mysql_query("INSERT INTO vopros (autor,text,mail) VALUES ('$autor','$text','$mail')");

if ($result=='true'){echo "<p>Ваш вопрос отправлен</p>";}
else {echo "<p>Ваш вопрос не отправлен</p>";}
}
else
{
echo "<p>вы ввели не всю информацию</p>";
}
?>


<? include("10.php"); ?>
помогите плз если не трудно намишите на майл: "alexandr@1dvcu.ru"
Зарание спасибо

Спустя 1 день, 17 часов, 18 минут, 54 секунды (28.11.2009 - 20:48) Ka4_0k написал(а):
оформляйте листинг читабельно, если хотите чтобы вам помогли. Для начала хотя бы используйте BB [html], [php]
Быстрый ответ:

 Графические смайлики |  Показывать подпись
Здесь расположена полная версия этой страницы.
Invision Power Board © 2001-2024 Invision Power Services, Inc.