Can't perform simple array search from array - php

I have a program that is failing because it's not finding the $post in the search of the array, so it's continuing to add each time. I have used the other suggested method of using a foreach loop, with strpos, such as:
if (strpos($data, $posts) !== false), and this will work find the $post, but it will also find the rest and run against everything in the data/array. hence why I would just like it to search the array, if it's not there add it, if it is, just say it's there or checking in... I've spent 3 days using in_array, array_search, etc, now I'm asking for help...
<html>
<body>
<?php
$post = $_POST['name'];
$data = file("data.txt");
if (in_array($post, $data)) {
echo "$post is checking in...";
}
else {
echo "Adding to $data...";
$data = fopen("data.txt", "a+");
fwrite($data, $post.PHP_EOL);
fclose($data);
}
$data = file("data.txt");
foreach ($data as $d) {
echo $d;
}
?>
</body>
</html>
tclient.html
<html>
<body>
<form action="test4.php" method="POST">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
data.txt
Names
John
Doe

The value in $post probably doesn't have a new line at the end. You can specify not to include new lines when you use file().
file("data.txt", FILE_IGNORE_NEW_LINES);

Related

using php how to read multiple TEXT files and display the file name?

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
}
}

HTML using a PHP script

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>

PHP - Write selected checkboxes to a text file

What I want to do is write a bunch of songs that a user selects from a checkbox list to a text file. The songs are listed in a text file, which is then opened and has its values stored into an array, and that array is used to make the checkbox list. This is what I have so far.
<html>
<h1>Welcome to Zmzon. Select songs below to add to your library.</h1>
<?php
var_dump($_POST);
/*Write song selections to myLibrary.txt file.*/
if(isset($_POST['songList'])){
$addSongs = $_POST['songList'];
$handle = fopen('myLibrary.txt', 'a');
foreach($addSongs as $song){
fwrite($handle, $song."\n");
}
fclose($handle);
}
?>
<form action="zmzon.php" method="POST">
<?php
/*Add contents of zmzonSongs.txt to array.*/
$songList = explode("\n", file_get_contents('zmzonSongs.txt'));
foreach($songList as $songs){
echo "<br/><input type='checkbox' name='songList[]' value='$songs' />$songs<br>";
}
?>
<input type="submit">
</form>
To zTunes
</html>
I've looked around everywhere and I'm still struggling with this.
Do the following in the zmzon.php file
<?php
if(isset($_POST['songList'])){
$listOfSongs = $_POST['songList'];
$fp = fopen('myLibrary.txt', 'w');
foreach ($listOfSongs as $song) {
fwrite($fp, $song.'\n');
}
fclose($fp);
}
?>
The above process is used to receive the song list and store it in file 'myLibrary.txt'.
you can include the above part in your existing zmzon.php file

my script is not reading *.txt file

I have a form which takes two values. One takes a .txt file, the file at which some links are hard coded and a text field which takes a url. When I press submit it takes that url and checks on every link that is on *.txt file. Hope you understand what I am saying if not then please comment I will clarify it. Now I have problems. My code does not work until the file at which links are, is not at my server. I don't how to handle this problem. I have done my search, I also try mysql but that is not ok for me. My script is this:
Enter your file :<input type="file" name="ufile" />
Enter your site name :<input type="text" name="utext" />
<input type="submit" value="Check" />
Now, my php script is this:
$needle = $_POST['utext'];
$file = $_FILES['ufile'];
$new = file($file, FILE_IGNORE_EMPTY_LINES | FILE_SKIP_EMPTY_LINES);
$new = array_map('trim', $new);
echo 'Total entries are: '.count($new).'<br />';
$found = array();
$notfound = array();
foreach ($new as $check) {
echo "<table border='1'><tr>";
echo "<td>Processing</td> <td>", $check,"</td></tr>";
$a = file_get_contents($check);
if (strpos($a, $needle)) {
echo "<td><font color='green'>Found:</font></td>";
$found[] = $check;
} else {
echo "<td><font color='red'>Not Found</font></td>";
$notfound[] = $check;
}
echo "</tr></table>";
}
echo "Matches ".count($found)."<br />";
echo "Not Matched ".count($notfound);
Is there any reason you never read the documentation about how PHP handles uploads in first place? That would make clear that $_FILES['ufile'] is array, so your code cannot work. If you really want to continue writing code without understanding it first, then replace:
$file = $_FILES['ufile'];
with
$file = $_FILES['ufile']['tmp_name'];

Merge 2 php scripts

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.

Categories