I am making a search engine that searches through a file, and every time it outputs the results, every other code in the page doesn't work.
search.php:
<form action="" method="GET" name="">
<table>
<tr>
<td><input type="text" name="q" value="<?php echo isset($_GET['q']) ? $_GET['q'] : ''; ?>" placeholder="" /></td>
<td><input type="submit" name="" value="search" /></td>
</tr>
</table>
</form>
<body>
<?php
include("results.php");
?>
</body>
results.php:
<?php
$file = 'test.txt';
$searchfor = $_GET['q'];
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if (preg_match_all($pattern, $contents, $matches))
{
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else
{
echo "No matches found";
}
and then when it goes through results.php, it outputs this on my localhost site, not my code editor:
<form action="" method="GET" name="">
<table>
<tr>
<td><input type="text" name="q" value="dawn" placeholder="" /></td>
<td><input type="submit" name="" value="search" /></td>
</tr>
</table>
</form>
<body>
Found matches:
dawn
</body>
Does anybody know what's causing this output?
I've tried googling a lot, but I can't find anything.
CodePudding user response:
You need to change header()
one another in files. Change files like that.
Content of search.php
<?php
header('Content-Type: text/html');
?>
<form action="" method="GET" name="">
<table>
<tr>
<td><input type="text" name="q" value="<?php echo isset($_GET['q']) ? $_GET['q'] : ''; ?>" placeholder="" /></td>
<td><input type="submit" name="" value="search" /></td>
</tr>
</table>
</form>
<body>
<?php
include("results.php");
?>
</body>
Content of results.php
<?php
$file = 'test.txt';
$searchfor = $_GET['q'];
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if (preg_match_all($pattern, $contents, $matches))
{
echo "Found matches:\n";
echo htmlspecialchars(implode("\n", $matches[0]));
}
else
{
echo "No matches found";
}