Solved

Looking for a certain type of searching script  -Please HELP!

Posted on 1998-12-03
7
263 Views
Last Modified: 2010-08-05
Hello All,

I am looking for a script which can search thru text files and display the results on a web page. The text files will be in a format like:

Kings Quest 2 Level 6 Password ------ 49387xdg44w

Police Quest 5 Level 16 Password ------ 9946zxdgg44w

Kings Quest 2 Level 3 Password ------ 34687xdg44w

Etc...

So I want the results that if I searched for- 'Kings Quest' to come up on the next page as:

Search Results (2 Matches):

Kings Quest 2 Level 6 Password ------ 49387xdg44w

Kings Quest 2 Level 3 Password ------ 34687xdg44w

If anyone knows of one, please let me know.

Thanks a lot
0
Comment
Question by:CMD
7 Comments
 
LVL 1

Expert Comment

by:flivauda
ID: 1206719
$stringtofind = "king";

open (FILE, "datafile.txt");
while ($ln = <FILE>)
{
  if ($ln =~ /$stringtofind/i)
  {
     print "Found: $ln";
  }
}
close (FILE);
0
 

Author Comment

by:CMD
ID: 1206720
What am I supposed to do with that?
0
 
LVL 8

Expert Comment

by:shlomoy
ID: 1206721
tell me more so I can help you:

1) do you know how to make HTML forms to interface your search script with the user's query?
2) are you working on a unix or NT server?
3) are you allowed to run CGI scripts on your server?

answer those questions - and the answer will be good.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

Author Comment

by:CMD
ID: 1206722
I want a normal search script which instead of searching thru html files, to search thru text files.

I have an nt server

I do have a cgi bin

I have Perl 5

Thanks heaps
0
 
LVL 8

Accepted Solution

by:
shlomoy earned 50 total points
ID: 1206723
OK! let's give you an answer now.

on the HTML from which you want to search you need to add the following form (so you could have a place to punch in the query). just add the following lines to the HTML:

<form action="http://www.mysite.net/cgi-bin/findPass.cgi" method=POST>
<B><U> Search my DataBase: </U></B><BR>
<input type=text name="query" value="">        
<input type=submit value="Submit query">
</form>

now make sure you put the full and correct url for the location of the CGI which will do the actual search. If your site is "http://www.mysite.net" and your CGI-BIN is just under your PUBLIC_HTML and if your script is called findPass.cgi then the path I wrote is correct - otherwise change it according to your settings.

Next we need to write findPass. I assume that the search will be conducted over a text file named "passwords".

now, let's write the script:

#!/usr/bin/perl
# linkAdd.cgi
require 'cgi-lib.pl'                        # I'm using an external perl library called "cgi-lib"
&ReadParse(*input);                  #      I pasted it further ahead with instructions what to
$Query=$input{'query'};              #      do with it.
$LOCK_SH=1;
$LOCK_UN=8;
print "Content-Type: text/html\r\n\r\n";
open (FILE, "passwords");            # put full pathname for passwords file!!!
flock(FILE,$LOCK_SH);      
$count=0;
while ($line = <FILE>)
{
   if ($line =~ /$stringtofind/i)
   {
      $count++;
      print "Found: $line";
   }
}
flock(FILE,$LOCK_UN);
close (FILE);
print "<HTML><HEAD><TITLE>Search Results</TITLE></HEAD>\n";
print "<body>\n";


OK -
(*) make sure perl path is like the one on your machine (the 1st line of the script)
(*) make sure you wrote the full pathname to the passwords file (use absolute path)
(*) make sure that the directory wihch passwords resides on has read write and execute     permissions! and that the permissions apply for EVERYONE
(*) make sure that passwords file has read permissions.
(*) make sure findPass.cgi (which we've just made) has execute permissions for     EVERYONE.

note: it's important to set permission for everyone and not just for you because your CGI will be launched form your web-site by anonimus users - so the have to have permissions to run your CGI.

now paste the following into a new filename called cgi-lib.pl and make sure you put it along with findPass.cgi at the cgi-lib directory.

-----------------------------------------------------------------------------------------
#!/usr/bin/perl -- -*- C -*-
# Perl Routines to Manipulate CGI input
# S.E.Brenner@bioc.cam.ac.uk
# $Header: /home/ncvs/www/en/cgi/cgi-lib.pl,v 1.2 1996/10/06 20:16:38 jfieber Ex
p $
#
# Copyright 1994 Steven E. Brenner
# Unpublished work.
# Permission granted to use and modify this library so long as the
# copyright above is maintained, modifications are documented, and
# credit is given for any use of the library.
#
# Thanks are due to many people for reporting bugs and suggestions
# especially Meng Weng Wong, Maki Watanabe, Bo Frese Rasmussen,
# Andrew Dalke, Mark-Jason Dominus and Dave Dittrich.
# For more information, see:
#     http://www.bio.cam.ac.uk/web/form.html
#     http://www.seas.upenn.edu/~mengwong/forms/
# Minimalist http form and script (http://www.bio.cam.ac.uk/web/minimal.cgi):
#
# require "cgi-lib.pl";
# if (&ReadParse(*input)) {
#    print &PrintHeader, &PrintVariables(%input);
# } else {
#   print &PrintHeader,'<form><input type="submit">Data: <input name="myfield">'
;
#}
# ReadParse
# Reads in GET or POST data, converts it to unescaped text, and puts
# one key=value in each member of the list "@in"
# Also creates key/value pairs in %in, using '\0' to separate multiple
# selections
# Returns TRUE if there was input, FALSE if there was no input
# UNDEF may be used in the future to indicate some failure.
# Now that cgi scripts can be put in the normal file space, it is useful
# to combine both the form and the script in one place.  If no parameters
# are given (i.e., ReadParse returns FALSE), then a form could be output.
# If a variable-glob parameter (e.g., *cgi_input) is passed to ReadParse,
# information is stored there, rather than in $in, @in, and %in.
#
# $Id: cgi-lib.pl,v 1.2 1996/10/06 20:16:38 jfieber Exp $
#
 
sub ReadParse {
  local (*in) = @_ if @_;
  local ($i, $key, $val);
  # Read in text
  if (&MethGet) {
    $in = $ENV{'QUERY_STRING'};
  } elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
    read(STDIN,$in,$ENV{'CONTENT_LENGTH'});
  }
  @in = split(/&/,$in);
  foreach $i (0 .. $#in) {
    # Convert plus's to spaces
    $in[$i] =~ s/\+/ /g;
    # Split into key and value.
    ($key, $val) = split(/=/,$in[$i],2); # splits on the first =.
    # Convert %XX from hex numbers to alphanumeric
    $key =~ s/%(..)/pack("c",hex($1))/ge;
    $key =~ tr/[^A-Za-z0-9\-\_\$\+\=\~\.\,]//;          # allow only safe chars
    $val =~ s/%(..)/pack("c",hex($1))/ge;
    $val =~ tr/[^A-Za-z0-9\-\_\$\+\=\~\.\,]//;          # allow only safe chars
    # Associate key and value
    $in{$key} .= "\0" if (defined($in{$key})); # \0 is the multiple separator
    $in{$key} .= $val;
  }
  return length($in);
}
# PrintHeader
# Returns the magic line which tells WWW that we're an HTML document
sub PrintHeader {
  return "Content-type: text/html\n\n";
}
# MethGet
# Return true if this cgi call was using the GET request, false otherwise
sub MethGet {
  return ($ENV{'REQUEST_METHOD'} eq "GET");
}
# MyURL
# Returns a URL to the script
sub MyURL  {
  return  'http://' . $ENV{'SERVER_NAME'} .  $ENV{'SCRIPT_NAME'};
}
# CgiError
# Prints out an error message which containes appropriate headers,
# markup, etcetera.
# Parameters:
#  If no parameters, gives a generic error message
#  Otherwise, the first parameter will be the title and the rest will
#  be given as different paragraphs of the body
sub CgiError {
  local (@msg) = @_;
  local ($i,$name);
  if (!@msg) {
    $name = &MyURL;
    @msg = ("Error: script $name encountered fatal error");
  };
  print &PrintHeader;
  print "<html><head><title>$msg[0]</title></head>\n";
  print "<body><h1>$msg[0]</h1>\n";
  foreach $i (1 .. $#msg) {
    print "<p>$msg[$i]</p>\n";
  }
  print "</body></html>\n";
}
# PrintVariables
# Nicely formats variables in an associative array passed as a parameter
# And returns the HTML string.
sub PrintVariables {
  local (%in) = @_;
  local ($old, $out, $output);
  $old = $*;  $* =1;
  $output .=  "<DL COMPACT>";
  foreach $key (sort keys(%in)) {
    foreach (split("\0", $in{$key})) {
      ($out = $_) =~ s/\n/<BR>/g;
      $output .=  "<DT><B>$key</B><DD><I>$out</I><BR>";
    }
  }
  $output .=  "</DL>";
  $* = $old;
  return $output;
}
1;
-----------------------------------------------------------------------------------------

(*) adjust perl's location on the 1st line of the library script to your perl location.
(*) set cgi-lib.pl 's permissions for read/execute for everyone.

And now - unless you made a mistake following my orders and unless I forgot something  - this is it!!

in case something isn't clear or if you don't know how to do a certain step - tell me - I'll guide you through it.

You might need to use the winNT version of cgi-lib.pl (I gave you the Unix version) - you can download the windows NT version from www.perl.org (from CPAN).

Good Luck!!
0
 
LVL 84

Expert Comment

by:ozo
ID: 1206724
     
0
 

Author Comment

by:CMD
ID: 1206725
is there a way of searching several txt files?
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question