PHP strpos() return empty value - php

I meet a strange thing with the PHP function strpos().
I have a function that check if a passed string is found in a txt file.
I can display the content of the file line by line but the strpos() doesn't return a value (nothing in fact). var_dump() of the return empty.
Can someone see a mistake, because I am lost.
Thank you in advance.
My function :
function checkIfExist($string)
{
$path = "\\\\server\\temp\\test.txt";
$file = file($path);
foreach( $file as $line )
{
echo $line; //display the string in this line
$found = strpos($file,$string);
echo $found; //display nothing, not even a boolean/int
}
return $found;
}

Try to change $found = strpos($file,$string); to $found = strpos($line,$string);

Echoing a false boolean won't show up. Try changing it to a var_dump and you will see that it's a boolean set to false.

Sorry, I have made a mistake when writen the code, this is the good one :
function checkIfExist($string)
{
$path = "\\\\server\\temp\\test.txt";
$file = file($path);
foreach( $file as $line )
{
echo $line; //display the string in this line
$found = strpos($line,$string);
echo $found; //display nothing, not even a boolean/int
var_dump($found); //display boolena(false) for all the test even if the
string is well present once.
}
return $found;
}

This code give the same result
foreach( $file as $line )
{
echo $line; //display "www.google.be"
echo $string; //also display "www.google.be"
//but when I then if the line contain the string, the function doesn't find
it!!!
$pos = stripos($line,$hostname);
var_dump($pos); // FALSE for all the test
}
I have done this thes in other code, and I never had this issue.

Setup debugging, so you see the values of strpos. If debugging cannot be arranged than vardump $line and $string. You will probably get unexpected values. Also try avoiding typecasting-issues. Perhaps this will work better.
if (strpos($line,$string) != false){...}else{...}

Related

how to strpos with array or in_array in multiple text string

I made this code
$message = 'This domain has strpos';
$links = array('domain.com', 'do.main');
$safe = strpos($message, $links);
return $message;
but got error errorHandler->error in my page, whats wrong with my code?
did I do some missing code?
what I want just detect if the message have string in $links then do rest of my code
thanks for droping out
Since PHP has no elegant solution and all I see is full blown functions here's a simple one that will work
$arr will hold an array of string you do NOT want
// If string has illegal characters return false
function str_allowed($str, $arr) {
foreach ($arr as $bad_string) {
if(strpos($str, $bad_string) !== false)
return false; // bad string detected, return false
}
return true; // if we got this far means everything's good return true
}
Please try this one will give expected output.
$message = 'This domain has strpos';
$links = array('domain.com', 'do.main');
$safe = array();
foreach($links as $key=>$result){
if(strpos($message, $result) != false){
$safe[$result] = "String is available";
} else{
$safe[$result] = "String is not available";
}
}
print_r($safe);

Remove a line from file if it exists

I'm getting used to PHP and trying to remove a line from a file (if it exists) and resave the file.
So if I had the file
user1
user2
user3
user4
I could use
if(existsAndRemove("user3")){
do thing
}
I've tried using code similar to the code below but it sometimes bugs out and will only remove a line if it is last in the file. I have no idea how to fix this.
$data2 = file("./ats.txt");
$out2 = array();
foreach($data2 as $line2) {
if(trim($line2) != $acc) {
$out2[] = $line2;
}
}
$fp2 = fopen("./ats.txt", "w+");
flock($fp2, LOCK_EX);
foreach($out2 as $line2) {
fwrite($fp2, $line2);
}
flock($fp2, LOCK_UN);
fclose($fp2);
}
}
Any help at all would be greatly appreciated, and i would also appreciate if you could explain the code too so I could easier learn from it!!
Thank you.
If the file size is small enough that you're not worried about reading it all into memory, you could do something more functional
// Read entire file in as array of strings
$data = file("./ats.txt");
// Some text we want to remove
$acc = 'user3';
// Filter out any lines that match $acc,
// ignoring any leading or trailing whitespace
//
$filtered_data = array_filter(
$data,
function ($line) use ($acc) {
return trim($line) !== $acc;
}
)
// If something changed, write the file back out
if ($filtered_data !== $data) {
file_put_contents('./ats.txt', implode('', $filtered_data));
}
Something like this might work:
function remove_user($user) {
$file_path = "foo.txt"
$users = preg_split("[\n\r]+", file_get_contents($file_path));
foreach ($users as $i => $existing) {
if ($user == $existing) {
$users = array_splice($users, $i, 1);
file_put_contents($file_path, implode("\n", $users));
break;
}
}
}
Should be much easier since you're already using file():
$data2 = file("./ats.txt", FILE_IGNORE_NEW_LINES);
unset($data2[array_search('user3', $data2)]);
file_put_contents("./ats.txt", implode("\n", $data2));
Or to check if it exists first:
$data2 = file("./ats.txt", FILE_IGNORE_NEW_LINES);
if( ($key = array_search('user3', $data2)) !== false ) {
unset($data2[$key]);
file_put_contents("./ats.txt", implode("\n", $data2));
}

PHP get value from file function acts wierd

The function reads two strings from file data.db (utf-8). The file contains strings: '123' and '123'. I checked it via ECHO and it displays the content correctly. Thus im sure the problem is not in the file.
When I try to match the values with the file the variable $access never change.
//got data from $_POST....
function au_check($login,$psw){
$f = file('data.db');
$l = $f[0];
$p = $f[1];
$access = 'fail';
if ($login==$l && $psw==$p){
$access='CHANGED';
}
return $access;
}
echo (au_check($_POST['login'],$_POST['pass'])); //returns FAIL :((((
BUT! If i change my values DIRECTLY in code IT WORKS...
//got data from $_POST....
function au_check($login,$psw){
$f = file('data.db');
$l = '123';
$p = '123';
$access = 'fail';
if ($login==$l && $psw==$p){
$access='CHANGED';
}
return $access;
}
echo (au_check($_POST['login'],$_POST['pass'])); //returns CHANGED.
?>
plz help! how to fix and what is wrong? that's so weird ....
file returns the lines, complete with newline character.
Use something like this to trim them off (the trim function is too heavy-handed):
$lines = file('data.db');
$f = array_map(function($line) {return rtrim($line,"\r\n");},$lines);

Check whether the given two words are existing in a PHP string

I want to check if a string contains two specific words.
For example:
I need to check if the string contains "MAN" & "WAN" in a sentence like "MAN live in WAN" and returns true else false.
What I've tried is looping string function in a conditional way:-
<?php
$data = array("MAN","WAN");
$checkExists = $this->checkInSentence($data);
function checkInSentence( $data ){
$response = TRUE;
foreach ($data as $value) {
if (strpos($string, $word) === FALSE) {
return FALSE;
}
}
return $response;
}
?>
Is it the right method or do I've to change it? How to implement this any suggestions or idea will be highly appreciated.
Note: data array may contain more than two words may be. I just need check whether a set of words are exists in a paragraph or sentence.
Thanks in advance !
It's alsmost good. You need to make it set the response to false if a word is not included. Right now it'll always give true.
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
Try this:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
This also should work!
$count = count($data);
$i = 0;
foreach ($data as $value) {
if (strpos($string, $value) === FALSE) {
#$response = TRUE; // This is subject to change so not reliable
$i++;
}
}
if($i<$data)
response = FALSE;

Search for a specific string within another string with PHP

I need to search a string for any occurances of another string in PHP. I have some code that I've been playing with, but it doesn't seem to be working.
Here is my code:
while (list($key, $val) = each($keyword)) {
$pos = strpos($location, $val);
if($pos == false) {
echo "allow";
exit;
} else {
echo "deny";
exit;
}
}
I have tried some of the options below, but it still does not find the match. Here is what I'm searching:
I need to find:*
blah
In:
http://blah.com
Nothing seems to find it. The code works in regular sentences:
Today, the weather was very nice.
It will find any word from the sentence, but when it is all together (in a URL) it can't seem to find it.
When checking for boolean FALSE in php, you need to use the === operator. Otherwise, when a string match is found at the 0 index position of a string, your if condition will incorrectly evaluate to true. This is mentioned explicitly in a big red box in the php docs for strpos().
Also, based on a comment you left under another answer, it appears as though you need to remove the exit statement from the block that allows access.
Putting it all together, I imagine your code should look like this:
while (list($key, $val) = each($keyword)) {
$pos = strpos($location, $val);
if($pos === false) { // use === instead of ==
echo "allow";
} else {
echo "deny";
exit;
}
}
Update:
With the new information you've provided, I've rewritten the logic:
function isAllowed($location) {
$keywords = array('blah', 'another-restricted-word', 'yet-another-restricted-word');
foreach($keywords as $keyword) {
if (strpos($location, $keyword) !== FALSE) {
return false;
}
}
return true;
}
$location = 'http://blah.com/';
echo isAllowed($location) ? 'allow' : 'deny';

Categories