im new in php programming and ive a problem recently. I have 1 html page with a Search Box and a php script using for grep in a specific file on local host. This is what i want, when a user type string of char and click on enter that send a POST to modify my php var $contents_list, and grep all filename where the string is found.
<?php
$contents_list = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir = new RecursiveDirectoryIterator($path);
$compteur = 0;
foreach(new RecursiveIteratorIterator($dir) as $filename => $file) {
$fd = fopen($file,'r');
if($fd) {
while(!feof($fd)) {
$line = fgets($fd);
foreach($contents_list as $content) {
if(strpos($line, $content) != false) {
$compteur+=1;
echo "\n".$compteur. " : " . $filename. " : \n"."\n=========================================================================\n";
}
}
}
}
fclose($fd);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="page2.php" method="post">
<INPUT TYPE = "TEXT" VALUE ="search" name="search">
</form>
</body>
And when i go to my html page and type text in searchbar, that redirect me to my php script "localhost/test.php" and i have 500 internal error.
So I want:
To see result of the php script on the same html page, but i dont know how to do that :/
And if the previous filename return was same like previous result, dont print it, to avoid double result.
I hope its clear and youve understand what i want to do, so thanks for the people who want to help me <3
My recommendations:
Combine the code into the single index.php file for simplicity
Separate logic for search and output to achieve clean separation of duties
Add helper text such as nothing found or enter text
index.php content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<form action="index.php" method="post">
<input type="text" placeholder="search" name="search">
</form>
<?php
// Check if the form was submitted.
if (isset($_POST['search']) && (strlen($_POST['search'])) > 0) {
$search_line = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir_content = new RecursiveDirectoryIterator($path);
// Array to store results.
$results = [];
// Iterate through directories and files.
foreach (new RecursiveIteratorIterator($dir_content) as $filename => $file) {
$fd = fopen($file, 'r');
if ($fd) {
while (!feof($fd)) {
$file_line = fgets($fd);
if (strpos($file_line, $search_line) !== FALSE) {
$results[] = $filename;
}
}
fclose($fd);
}
}
// Output result.
echo "<pre>";
if ($results) {
foreach ($results as $index => $result) {
echo ($index + 1) . " :: $result\n";
}
}
else {
echo "Nothing found!";
}
echo "</pre>";
}
else {
// When nothing to search.
echo "<pre>Enter something to search.</pre>";
}
?>
</body>
</html>
Related
I have forms.
On the forms should be adding files to the Files folder. (It works, but there is a problem) when I only add a file, it is not added, this error appears instead:
Warning:Cannot modify header information -headers already sent by (output started at Q:\home\rat\www\pr5\files.php:1) in Q:\home\rat\www\pr5\files.php on line 10
The file of the file in the Files folder (it does not work: constantly writes that the file exists, even if there is no such file)
The image of the added files (it works too)
Deleting files (it does not work completely, the files are not deleted), this error appears:
Warning: unlink(files/Удалить) [function.unlink]: No such file or directory in Q:\home\rat\www\pr5\files.php on line 61
What is the problem with the paths of me? I can not understand. I did everything on the textbook, but does not work ...
files.php
<?
class Files {
public $files;
function __construct() {
$this->files = scandir("files/");
}
function redirect($url) {
header('Location: '.$url);
}
function counter() {
$filename = "count.txt";
if(file_exists($filename)) {
$h = fopen($filename, "r+");
$Content = fread($h, filesize($filename));
fclose($h);
$text = $Content + 1;
} else {
$text = 1;
}
$h = fopen($filename, "w");
if(fwrite($h, $text)) {
echo "Вы $text-й посетитель сайта =)";
} else {
echo "Что-то не работает на сайте! =(";
echo "Надо напрячь прогера!";
}
fclose($h);
echo "<hr>";
}
function upload() {
if($_FILES['myfile']) {
$uploaddir = 'files/';
$destination = $uploaddir.$_FILES['myfile']['name'];
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $destination)) {
$this->redirect('/pr5');
} else {
return "error <br>";
}
}
}
function search() {
if($_POST['searchname']) {
$folder = "files/";
$file = $searchname;
$file = $folder.$file;
if(file_exists($file)) {
print "Файл существует";
} else {
print "Файл не существует";
}
}
}
function delete() {
if($_POST['delete']) {
unlink("files/".$_POST['delete']);
$this->redirect('/pr5');
}
}
}
?>
index.php
<?
include "files.php";
$f = new Files;
if($_FILES['myfile']) {
$f->upload();
}
if($_POST['delete']) {
$f->delete();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>pr5</title>
</head>
<body>
<?
$f->counter();
?>
<form enctype = "multipart/form-data" method = "post">
<input type = "hidden" name = "MAX_FILE_SIZE" value = "30000" />
<input type = "file" name = "myfile" /><br>
<input type = "submit" value = "Отправить" />
</form>
<hr>
<form enctype = "multipart/form-data" method = "post">
<input type = "text" name = "searchname" /><br>
<input type = "submit" value = "Найти" />
</form>
<?
if($_POST['searchname']) {
$f->search();
}
?>
<hr>
<?
if(count($f->files) > 2) {
?>
<form method = "POST">
<table>
<tr>
<th>Имя</th>
<th>Удалить</th>
</tr>
<?
foreach($f->files as $s) {
?>
<?
if($s != '.' and $s != '..') {
?>
<tr>
<td> <?
echo $s;
?> </td>
<td>
<button type = "submit" name = "delete" value = "<? echo $s; ?>">Удалить</button>
</td>
</tr>
<?
}
?>
<?
}
?>
</table>
</form>
<?
}
?>
</body>
</html>
Okay, let's check this error more closely.
Warning: Cannot modify header information -headers already sent
PHP cannot modify headers - so the point where it realizes something's amiss is when it calls the header() function - because
output started at Q:\home\rat\www\pr5\files.php:1)
So, in that file, at row 1, there is something output. Something that's not PHP.
What appears to be line 1 is just
<?
which should have been perfectly copacetic (well, actually you'd better take the habit of using long tags, so, "<?php", since that's the established standard).
I am therefore betting something that in that line, unless there is an empty line before it of course, there is something you cannot see. My money is on a BOM: three invisible bytes that tell the operating system that file is coded in UTF8 with specific characteristics.
Usually, your editor should have an option to create files without a Byte Order Mark.
I have a PHP code that read text file and allow the user to make a search on a word and its work perfectly.
the files content is in arabic
Where the user make a search and the system will display the requested string with the line number where it exist.
What i want now is to make the system read multiple text files and when the user request a word the system will display the name of files where he found the user request.
is this possible and how long this process will take if i have 100 files ?
code:
<?php
$myFile = "arabic text.txt";
$myFileLink = fopen($myFile, 'r');
$line = 1;
if(isset($_POST["search"]))
{
$search =$_POST['name'];
while(!feof($myFileLink))
{
$myFileContents = fgets($myFileLink);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches))
{
foreach($matches[1] as $match)
{
echo "Found $match on Line $line";
}
}
++$line;
}
}
fclose($myFileLink);
//echo $myFileContents;
?>
<html>
<head>
</head>
<meta http-equiv="Content-Language" content="ar-sa">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<body>
<form action="index.php" method="post">
<p>enter your string <input type ="text" id = "idName" name="name" /></p>
<p><input type ="Submit" name ="search" value= "Search" /></p>
</form>
</body>
</html>
So you have to put your currently working code into a function, with the function returning the content you want.
function readFile($fileName)
{
// ...your code
return $yourMessage;
}
$fileNames = array("file1.txt", "file2.txt");
$result = array();
foreach($fileNames as $name)
{
$message = readFile($name);
$result[$name] = $message;
}
You can now iterate over the $result and print it in your own desired way.
To get all files into one array you can use scandir('/mydir/').
$files = scandir('/mydir/here/');
foreach($files as $file) {
if (strpos($file, '.txt')) {
//dosomething
}
}
I am working on a page that allows the user to "upload" multiple files at once (they are stored locally in folders relative to their type).
My problem is that when I try to pass $upFile1 and $fileInfo1 to writeResults() to update $fileInfo1 with information about $upFile1, the echoed result is empty.
I did some research and this appears to be a scoping issue, but I'm not sure about the best way to get around this having just started learning PHP last month.
Any help would be greatly appreciated.
foo.html
<!DOCTYPE HTML>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form method="post" action="foo.php" enctype="multipart/form-data">
<p>
<b>File 1:</b><br>
<input type="file" name="upFile1"><br/>
<br/>
<b>File 2:</b><br>
<input type="file" name="upFile2"><br/>
<br/>
</p>
<p>
<input type="submit" name="submit" value="Upload Files">
</p>
</form>
</body>
</html>
foo.php
<?php
$upFile1 = $_FILES['upFile1'];
$upFile2 = $_FILES['upFile2'];
$fileInfo1 = "";
$fileInfo2 = "";
// Check if directories exist before uploading files to them
if (!file_exists('./files/images')) mkdir('./files/images', 0777, true);
if (!file_exists('./files/text')) mkdir('./files/text', 0777, true);
// Copies the file from the source input to its corresponding folder
function copyTo($source) {
if (($source['type'] == 'image/jpg') || ($source['type'] == 'image/png')) {
#copy($source['tmp_name'], "./files/images/".$source['name']);
}
if ($source['type'] == 'text/plain') {
#copy($source['tmp_name'], "./files/text/".$source['name']);
}
}
// Outputs file data for input file to destination
function writeResults($source, $destination) {
$destination .= "You sent: ";
$destination .= $source['name'];
$destination .= ", a ";
$destination .= $source['size'];
$destination .= "byte file with a mime type of ";
$destination .= $source['type'];
$destination .= ".";
// echoing $destination outputs the correct information, however
// $fileInfo1 and $fileInfo2 aren't affected at all.
}
// Check if both of the file uploads are not empty
if ((!empty($upFile1['name'])) || (!empty($upFile2['name']))) {
// Check if the first file upload is not empty
if (!empty($upFile1['name'])) {
copyTo($upFile1);
writeResults($upFile1, $fileInfo1);
}
// Check if the second file upload is not empty
if (!empty($upFile2['name'])) {
copyTo($upFile2);
writeResults($upFile2, $fileInfo2);
}
} else {
die("No input files specified.");
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<p>
<!-- This is empty -->
<?php echo "$fileInfo1"; ?>
</p>
<p>
<!-- This is empty -->
<?php echo "$fileInfo2"; ?>
</p>
</body>
</html>
you are passing the values of $fileInfo1 and $fileInfo2 but they are empty. After that there is no relation between the $destination value and the fileininfo values.
Change your function to return the $destination value.
Change your writeResults command to $fileInfo1 = writeResults($upFile1);
Use the & sign to pass variables by reference
function addOne(&$x) {
$x = $x+1;
}
$a = 1;
addOne($a);
echo $a;//2
function writeResults($source, &$destination) {
$destination .= "You sent: ";
$destination .= $source['name'];
$destination .= ", a ";
$destination .= $source['size'];
$destination .= "byte file with a mime type of ";
$destination .= $source['type'];
$destination .= ".";
// echoing $destination outputs the correct information, however
// $fileInfo1 and $fileInfo2 aren't affected at all.
}
Adding & in front of $destination will pass the variable by reference, instead of by value. So modifications made in the function will apply to the variable passed, instead of a copy inside the function.
I have the following code that opens a non-txt file and runs through it so it can read the file line by line, i want to create a textbox (using html probably) so i can put my readed text into that but i have no idea how to do it
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h2>testing</h2>
<?php
$currentFile = "pathtest.RET";
$fp = fopen($currentFile , 'r');
if (!$fp)
{
echo '<p> FILE NOT FOUND </p>';
exit;
}
else
{
echo '<p><strong> Arquivo:</strong> ['. $currentFile. '] </p>';
}
$numLinha = 0;
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
}
fclose($fp);
$numLinha = $numLinha -1;
echo '<hr>linhas processadas: ' . $numLinha;
?>
</body>
</html>
i need the textbox area to be in a form so i can define the cols and rows, or there is an way to do it in php ? is there any way to send the readed content to another .php so i can edit the php to an html interface style freely ?
Try echoing the lines between a textarea:
echo "<textarea>";
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
};
echo "</textarea>";
You may use \n in order to break lines on the textarea:
echo $linha . "\n";
I need some help with some php scripting. I wrote a script that parses an xml and reports the error lines in a txt file.
Code is something like this.
<?php
function print_array($aArray)
{
echo '<pre>';
print_r($aArray);
echo '</pre>';
}
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'utf-8');
$xml = file_get_contents('file.xml');
$doc->loadXML($xml);
$errors = libxml_get_errors();
print_array($errors);
$lines = file('file.xml');
$output = fopen('errors.txt', 'w');
$distinctErrors = array();
foreach ($errors as $error)
{
if (!array_key_exists($error->line, $distinctErrors))
{
$distinctErrors[$error->line] = $error->message;
fwrite($output, "Error on line #{$error->line} {$lines[$error->line-1]}\n");
}
}
fclose($output);
?>
The print array is only to see the errors, its only optional.
Now my employer found a piece of code on the net
<?php
// test if the form has been submitted
if(isset($_POST['SubmitCheck'])) {
// The form has been submited
// Check the values!
$directory = $_POST['Path'];
if ( ! is_dir($directory)) {
exit('Invalid diretory path');
}
else
{
echo "The dir is: $directory". '<br />';
chdir($directory);
foreach (glob("*.xml") as $filename) {
echo $filename."<br />";
}
}
}
else {
// The form has not been posted
// Show the form
?>
<form id="Form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Path: <input type="text" name="Path"><br>
<input type="hidden" name="SubmitCheck" value="sent">
<input type="Submit" name="Form1_Submit" value="Path">
</form>
<?php
}
?>
That basically finds all xmls in a given directory and told me to combine the 2 scripts.
That i give the input directory, and the script should run on all xmls in that directory and give reports in txt files.
And i don't know how to do that, i'm a beginner in PHP took me about 2-3 days to write the simplest script. Can someone help me with this problem?
Thanks
Make a function aout of your code and replace all 'file.xml' to a parameter e.g. $filename.
In the second script where the "echo $filename" is located, call your function.