how to search string in txt with PHP Stripos - php

I have a text file containing
number, zero, one
number, two, three
number, four, five
in a file called data.txt
I want to search for the number and tried this but doesnt seem to work
$file = 'domain.com/data.txt';
$searchnum = 'zero';
if (stripos($file, $searchnum) == true) { echo 'number found' }
Update 1.0
i tried this as well but it doesnt seem to pull the data on the txt file
$file = "domain.com/data.txt";
$searchnum = "zero";
if(exec('grep '.escapeshellarg($searchnum).' '.$file )) {
echo "record found";
}
else {
echo "record notfound";
}

You're doing it correctly, you just need to pull the file contents.
$file = file_get_contents('./data.txt'); // you can use a full http address if your server allows it
$searchnum = 'zero';
if (stripos($file, $searchnum) !== false) { echo 'number found'; }

stripos() returns the index of the searched string, or FALSE if it is not found.
So you would do if (stripos($file, $searchnum) !== false) { echo 'number found'; }
!== is used because you need to distinguish false from 0.

Related

Loop until the request response message equals to "true" in php

I'm trying to make a php script that would make a loop that would get the contents of my site/server and if the text response is for example "false" then it would do the same thing, basically will loop until the site's text response will echo "true".
This is what i tried:
$getcontents = file_get_contents("http://example.com/script.php"); // it will echo false
if (strpos($getcontents , 'false')) {
$getcontents = file_get_contents("http://example.com/script.php");
else if (strpos($getcontents , 'false')) {
$getcontents = file_get_contents("http://example.com/script.php");
}
else if (strpos($getcontents , 'true')) {
echo "finished".;
}
I'm not sure if this is the right way or even if it is possible and i apologize in advance if i did not explain myself very well. Thank you for attention!
You could use a regular while loop.
$getcontents = 'false'; //set value to allow loop to start
while(strpos($getcontents , 'false') !== false) {
$getcontents = file_get_contents("http://example.com/script.php");
}
echo "finished";
This will loop until $getcontents does not contain false.
You could also use a recursive function like this.
function check_for_false() {
$getcontents = file_get_contents("http://example.com/script.php");
if(strpos($getcontents , 'false') !== false) {
check_for_false();
} else if(strpos($getcontents , 'true') !== false) {
echo "finished";
} else {
echo "response didn't contain \"true\" or \"false\"";
}
}
This function should keep calling itself until $getcontents contains the word true, and does not contain false.

Check if URL has an exact string with PHP

I've tried the following:
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'car') !== false) {
echo 'Car exists.';
} else {
echo 'No cars.';
}
However if the url contains the word "care" or "car2" it will also trigger "Car Exists". How do I get a match if only "car" is found?
Change
if (strpos($url,'car') !== false) {
into
if (preg_match('/\bcar\b', $url) !== 0) {
Basically, you search for word car with no other alphanumeric surrounding it.
Hope this helps!

PHP Search txt file dosen't look on the first line

Ive got this bit of code to look in my txt file to see if i already have the item, However it never looks on the first line. Is there something i can do to fix this?
<?php
for($i=0, $count = count($match[1]);$i<$count;$i++) {
$filename = 'alreadyadded.txt';
$searchfor = $match[1][$i];
$file = file_get_contents($filename);
if(strpos($file, $searchfor)) {
echo $match[1][$i]." Is already added, No Actions needed. <br />";
} else {
echo "grabbing this one".$match[1][$i]."<br />";
}
}
?>
You should do it this way:
if(strpos($file, $searchfor) !== false) {
echo $match[1][$i]." Is already added, No Actions needed. <br />";
} else {
echo "grabbing this one".$match[1][$i]."<br />";
}
if the position found is 0 (the first character) you basically get wrong result. You want to compare the result to false including datatype.
0 == false returns true
0 === false returns false
0 != false returns false
0 !== false returns true
This doesn't solve the problem but should make it slightly faster. You don't need to read the file each time.
$filename = 'alreadyadded.txt';
$file = file_get_contents($filename);
for($i=0, $count = count($match[1]);$i<$count;$i++) {
$searchfor = $match[1][$i];
if(strpos($file, $searchfor)!==false) {
echo $match[1][$i]." Is already added, No Actions needed. <br />";
} else {
echo "grabbing this one".$match[1][$i]."<br />";
}
}

Multiple Strpos checks

Would there be anyway to merge the below queries into a single function? As it stands only the second Strpos function works. If i remove the second one then the first one will work. I need to run both as I have to check for 2 separate strings.
$check1 = QueryWhoisServer($whoisserver, $domain);
if(strpos($check1,"No match for") !== FALSE){
return "Result Example";
}
$check2 = QueryWhoisServer($whoisserver, $domain);
if(strpos($check2,"No Data Found") !== FALSE){
return "Result 2 example";
}
else {
Any help would be much appreciated.
First of all, you should keep the output of your whois query.
$response = QueryWhoisServer($whoisserver, $domain);
Then, you can run multiple searches:
if (false !== strpos($response, 'No match for')) {
// ...
} elseif (false !== strpos($response, 'No Data Found')) {
// ...
} else {
// ...
}

How to determine if file text search returns no matches?

I have created a piece of code that checks files for a user-submitted string within a set of files. The code searches a directory, returns the file, then searches for the string in the file. The user will input the custom string through an input field and then clicking a submit button.
I have successfully been able to create a condition where, if the user does not enter any information, the output will say, "Your search produced no results". However, I have not been able to figure out how to create a condition where, if the user enters a string that isn't found within the files, that the output will also be, "Your search produced no results".
The code for the existing conditional I have as of now is this:
if ((isset($query)) && (empty($query))) {
echo "Your search produced no results";
}
The code that searches for the files and also searches for the string is found here (this is the entire PHP file, actually, and it includes the conditional I posted above.) I need help on how to create another conditional that throws a message if the user-input isn't found in any of the files.
If this seems unclear, I apologize and will clarify any information you need if you think it will help.
Calling Code
$query = $_POST['query'];
if ((isset($query)) && (empty($query))) {
echo "Your search produced no results.";
}
else {
find_files('.');
}
find_files()
function find_files($seed)
{
if (! is_dir($seed))
return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs)))
{
if($dh = opendir($dir))
{
while( false !== ($file = readdir($dh)))
{
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if (is_dir($path)) {
$dirs[] = $path;
}
else {
if (preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
check_files($path);
}
}
}
}
closedir($dh);
}
}
check_files()
function check_files($this_file)
{
$query = $_POST['query'];
$str_to_find = $query;
if(!($content = file_get_contents($this_file))) {
echo("Could not check $this_file");
}
else {
if (stristr($content, $str_to_find)) {
echo("$this_file -> contains $str_to_find");
}
}
unset($content);
}
If the query is not empty the find_files function is simply executed with no instructions of doing something if it returns false, hence you need to evaluate the result of calling find_files. For example you could do:
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
elseif (!find_files('.'))
{
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
with the condition that you update you find_files function to return false for all cases that fail.
or you could update the find_files function to return a string in case of errors and a string empty for succesful execution
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
else
{
$result = find_files('.');
if (!empty($result))
{
echo "<p style=\"color:darkgray; font-family:arial\">".$result."</p>";
}
}
A couple of notes regarding your code that will improve the readability and code quality:
proper indentation will save a lot of time spent in maintenance;
when using if else imbrications ALWAYS use curly braces even if it is only one instructions. Improves readability and avoids errors.
when accessing a variable declared outside a function (in procedural code) use global keyword. For example for accessing the query variable inside the check_files function use global $query; instead of retrieving the variable again from the post.
use $_REQUEST instead of $_POST or $_GET unless there is a special reason for doing otherwise. Unifies code, makes for more readable code and changing from GET to POST or vice-versa can be done without changing code.
You may make your find_files function to return a boolean value: true if at least one matching file was found, false otherwise. Then update your if condition:
if ((isset($query)) && (empty($query)) && !find_files('.')) {
echo "<p style=\"color:darkgray...";
}
Because && is lazily evaluated, find_files will be called only if $query isn't empty.

Categories