I have this script to search file into a directory.
Works well when i perform search with exactly term, example: "my file.doc", "sales order 1234.pdf"
Can anyone help me to modify to search word into filename, example: "file" ou "Sales"
TKS
Cris.
<?php
if($_POST['search']) {
$word = $_POST['file'];
$dir = './';
$list = new RecursiveDirectoryIterator($dir);
$recursive = new RecursiveIteratorIterator($list);
$num = 0; //
foreach($recursive as $obj){
//echo $obj->getFilename().'<br />';
if($obj->getFilename()=="$word"){
echo $obj->getPathname().'<br/>';
$num++;
}
}
echo "found(s) $num file(s).";
}
?>
<form action="" method="POST">
search files. <input type="text" name="file" value="">
<input type="submit" name="search">
</form>
<?php
if($_POST['search']) {
$word = $_POST['file'];
$dir = './';
$list = new RecursiveDirectoryIterator($dir);
$recursive = new RecursiveIteratorIterator($list);
$num = 0; //
foreach($recursive as $obj){
//echo $obj->getFilename().'<br />';
if( strpos( $obj->getFilename(), "$word" ) === true ){
echo $obj->getPathname().'<br/>';
$num++;
}
}
echo "found(s) $num file(s).";
}
?>
<form action="" method="POST">
search files. <input type="text" name="file" value="">
<input type="submit" name="search">
</form>
You can use the strpos function or the strstr function on your filename.
Test if the function returns something different than false to know your filename contains your chain.
You can use PHP's substr_count to count the occurrences of a string in another, but since you need one or more you can check like this:
if( substr_count( $obj->getFilename(), $word ) ){
echo $obj->getPathname().'<br/>';
$num++;
}
edit: for case-insensitive comparison:
if( substr_count( strtolower($obj->getFilename()), strtolower($word) ) {
// ...
}
Related
There seems to be some issue with the code where the result is skipped with one line.
For example, if I write: 642641
the result should be: "642641","testgatan 1"
but instead, it's showing: "762755","testgatan 2"
How can I fix so it actually get the input submitted?
I got a link for you to see what I mean: http://snaland.com/herestheidnummer/test.html
Here's the csv:
ID,Gata
"642641","testgatan 1"
"762755","testgatan 2"
"346468","testgatan 3"
"114564","testgatan 4"
"758925","testgatan 5"
I used the php code from Find if a value exist in a CSV file with PHP by Fred -ii-
And modified it like this:
<?php
$search = $_GET['subject'];
$lines = file('http://snaland.com/herestheidnummer/anlaggningsnmr.csv');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (stripos($line, $search) !== FALSE);
}
if($line_number){
echo "Found result: " .$line;
}
else{
echo "Can't find result: " .$search;
}
?>
Html form:
<form name="form" action="http://snaland.com/herestheidnummer/verifiera.php" method="get">
<input type="text" name="subject" id="subject" value="000000">
<input type="submit" value="Submit">
</form>
Your problem is the condition in the while loop. The assignment to key and list get executed before the check of !$line_number. It should work ff you swap both conditions like this
while (!$line_number and list($key, $line) = each($lines) ) {
$line_number = (stripos($line, $search) !== FALSE);
}
Each advances the array cursor, so when you finde the result, the next value is already loaded. More here http://php.net/manual/en/function.each.php.
A simpler solution is to replace your loop with:
for($i = 0; $i<count($lines);$i++){
if(stripos($lines[$i], $search) !== false){
$line = $lines[$i];
break;
}
}
And on the if:
if($line){
echo "Found result: " .$line;
}
I created a script for saving a form submission as a .txt file that uses the user's first name as the file name. To keep it simple I created a test file in HTML to show what I'm trying to achieve.
<form action="sender.php" method="post">
<input type="text" id="f_name" name="First_Name" />
<input type="text" id="demo_1" name="Demo_01" />
<input type="text" id="demo_2" name="Demo_02" />
<input type="text" id="demo_3" name="Demo_03" />
<input type="text" id="demo_4" name="Demo_04" />
<input type="text" id="demo_5" name="Demo_05" />
<input type="text" id="demo_6" name="Demo_06" />
<input type="submit" value="submit" />
</form>
So far the script I have for processing the form in PHP is this
<?php ini_set('display_errors','on'); ?><?php
$data= "";
foreach ($_POST as $key => $value) {
$data.= str_replace("_"," ",$key)."\n\n ". $value."\n\n\n\n"; preg_replace("/[^ 0-9a-zA-Z]/", "_", $value);
}
$fileName= fopen("Submissions/".$_POST['First_Name'],'w');
fwrite($fileName, $data);
fclose($fileName);
?>
What I want to do is add some code to make it increment the file name so in the event of me getting multiple submissions from people with the same first name it won't over write them. Do say I have a submission from somebody named Bob, and two more Bobs happens to fill out the questionnaire, I want it to save as
Bob.txt
Bob_02.txt
Bob_03.txt
This means I need something that will be able to ignore the "_02" at the end to identify the "Bob" at the beginning so it doesn't go
Bob.txt
Bob_02.txt
Bob_02_02.txt
I came up with this in an attempt to do just that but got errors on both of the "file_exists" opperators
if (file_exists($fileName)){
$num="00";
$fileNameUpd= count(substr.$_POST['First_Name'].$num++);
fopen("Submissions/".$fileNameUpd,'w');
fwrite($fileNameUpd, $data);
fclose($fileNameUpd);
}
else if (!file_exists($fileName)){
fwrite($fileName, $data);
fclose($fileName);
};
the way I added it in is like this
<?php ini_set('display_errors','on'); ?><?php
$data= "";
foreach ($_POST as $key => $value) {
$data.= str_replace("_"," ",$key)."\n\n ". $value."\n\n\n\n"; preg_replace("/[^ 0-9a-zA-Z]/", "_", $value);
}
$fileName= fopen("Submissions/".$_POST['First_Name'],'w');
if (file_exists($fileName)){
$num="00";
$fileNameUpd= count(substr.$_POST['First_Name'].$num++);
fopen("Submissions/".$fileNameUpd,'w');
fwrite($fileNameUpd, $data);
fclose($fileNameUpd);
}
else if (!file_exists($fileName)){
fwrite($fileName, $data);
fclose($fileName);
};
?>
How can I get this to achieve what I need it to do?
Check the file name and loop till dynamic file name not exists. Each time append a counter variable with the file name.
<?php
$name = "Submissions/".$_POST['First_Name'].".txt";
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("Submissions/".$actual_name.".".$extension))
{
$actual_name = (string)$original_name."_".$i;
$name = $actual_name.".".$extension;
$i++;
}
file_put_contents("Submissions/".$name, $data);
?>
You can run while loop to check if the file already exists. As others have pointed out, first name is not a good unique identifier so perhaps you could consider the naming convention.
<?php
ini_set('display_errors','on');
$data= "";
foreach ($_POST as $key => $value) {
$data.= str_replace("_"," ",$key)."\n\n ". $value."\n\n\n\n"; preg_replace("/[^ 0-9a-zA-Z]/", "_", $value);
}
$file = $_POST['First_Name'].'.txt';
$i = 0;
while (is_file("Submissions/".$file)) {
$file = $_POST['First_Name'].'_'.$i.'.txt';
$i++;
}
$fileName= fopen("Submissions/".$file,'w');
fopen("Submissions/".$fileName,'w');
fwrite($fileName, $data);
fclose($fileName);
?>
I am trying to get the maximum value from an array using max finction in php. However despite making sure that the array appears as I expect using print_r, the max($array) returns the wrong result.
Please see the code below, I used "simple_html_dom.php" from http://simplehtmldom.sourceforge.net/. I am expecting a value of 220, but when I echo max($items) it returns 24 when submit is clicked. Any assistance is much appreciated.
<html>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" value="google"/>
<input type="submit" value="Submit">
</form>
<?php
include 'simple_html_dom.php';
if (isset($_POST['q'])) {
$search = $_POST['q'];
$search = ucwords($search);
$search = str_replace(' ', '_', $search);
$html = file_get_html("http://en.wikipedia.org/wiki/$search");
?>
<h2>Search results for '<?php echo $search; ?>'</h2>
<ol>
<?php
$items = array();
foreach ($html->find('img') as $element): ?>
<?php $photo = $element->src;
$logo = 'Logo';
if(strpos($photo, $logo))
{
if (preg_match_all('/[0-9]+px/', $photo, $result)) {
echo '<br/>';
$rp = trim($result[0][0],"px") .'<br/>';
$items[] = $rp;
} else {
echo "Not found";
}
}
?>
<?php endforeach; echo max($items);
print_r($items);?>
</ol>
<?php
}
?>
</body>
</html>
Here is result of var_dump($items):
array (size=2)
0 => string '220<br/>' (length=8)
1 => string '24<br/>' (length=7)
As you see, it takes it as a string. So max() works as it should, and you need to properly format it first, cut tags and cast to int.
Assuming it's an integer, simply change $items[] = $rp; to $items[] = intval($rp);... As an example this will change the array entry from '220<br/>' (string) to 220 (integer).
I am trying to export all domains located in domains.txt file that match exactly with the links from the all-urls.txt file. This is my script:
<?php
if (isset($_POST['submit'])) {
$badwords = file('domains.txt', FILE_SKIP_EMPTY_LINES);
$domains = file('all-urls.txt', FILE_SKIP_EMPTY_LINES);
$newarr = array();
echo '<table>';
foreach($badwords as $k=>$v) {
foreach($domains as $k1=>$v1) {
if(strpos($v1,$v)!==false) {
array_push($newarr,$v1);
$links = array_shift($newarr);
echo '<tr><td>';
echo $links;
echo '</td></tr>';
}
}
}
echo '</table>';
}
?>
<body>
<form action="" name="submit">
<p><label>Ready to submit</label></p>
<p><input name="submit" type="submit" value ="Go"></p>
</form>
</body>
Instead of $badwords = file('domains.txt', FILE_SKIP_EMPTY_LINES);
I had
$badwords = array('domain1.com', 'domain2.com');
and instead of
$domains = file('all-urls.txt', FILE_SKIP_EMPTY_LINES);
I had
$domains = array('domain1.com/url/subfoler.html', 'domain1.com/url/subfoler.html','domain2.com/sublink/otherthings.php');
And right now i am trying to replace the array with file because it's way easier for me to load them like this because i have a large number of domains and url.
The problem is that the script doesn't do anything in this form. Where am i mistaking
How do you know that you actually have read the file?
$badwords = file('domains.txt', FILE_SKIP_EMPTY_LINES);
if ( $badwords === false )
die ("error on file " . 'domains.txt');
$domains = file('all-urls.txt', FILE_SKIP_EMPTY_LINES);
if ( $domains === false )
die ("error on file " . 'all-urls.txt');
...
additionally, the expressions
array_push($newarr,$v1);
$links = array_shift($newarr);
are quite the same as
$newarr = array();
$links = $v1;
and use some cpu cycles with no effect at all ...
The default method to post a form, is GET, so if you don't specify a method, GET will be used and you will never enter the section where you compare the files as:
isset($_POST['submit'])
is false
You can add a method to the form to solve that:
<form action="" name="submit" method="post">
Found my answer:
<?php
$domains = file("domains.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$urls = file("all-urls.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$newarr = array();
$f = fopen("result.txt", w);
echo "<table>";
foreach($domains as $k=>$v) {
foreach($urls as $k1=>$v1) {
if(strpos($v1,$v)!==false) {
array_push($newarr,$v1);
$links = array_shift($newarr);
echo "<tr><td>";
echo $links;
echo "</td></tr>";
fwrite($f, "$links\r\n");
}
}
}
echo "</table>";
?>
I needed to add the FILE_IGNORE_NEW_LINES, because the urls are placed in new lines.
OK, one more problem and then I think my function will work.
Right now, my second function is just reporting the character length back next to the string like so:
string(20) "testing testing nice"
is there anyway to change the format of that return? And what do I need to change to get the WORD count too?
Is it even possible to make the format look like this:
string word count: 3 character count: 20 "testing testing nice"
thanks
file1.php
<?php
require('myfunctions.php');
if($_POST) {
$result = phptest($_POST['input']);
if ($result === false) {
echo 'No mean words were found.';
} else {
var_dump($result);
}
}
?>
<?php
echo "<br/> Sum function: ".sum(1,2,3,4)."<br/>";
echo "Average function: ".average(1,2,3,4)."<br/>";
?>
<form action="" method="post">
<input name="input" type="text" size="20" maxlength="20" />
<input name="submit" type="submit" value="submit" />
</form>
myfunctions.php
<?php
function sum() {
return array_sum(func_get_args());
}
function average() {
$args = func_num_args();
if ($args == 0) {
return 0;
}
return array_sum(func_get_args()) / $args;
}
?>
<?php
function phptest($input) {
$search = array('ugly', 'rude');
$replace = array('nice', 'sweet');
$output = str_ireplace($search, $replace, $input, $replace_count);
if ($replace_count === 0) {
return false;
} else {
return $output;
}
}
?>
You can use the str_word_count function to count words in a string.
function str_info($string) {
$words = str_word_count($string);
$chars = strlen($string); //Consideer using mb_strlen if you're using Unicode
return 'string word count: '. $words .' character count: '. $chars .' '. $string;
}