Wrong parameter count when calling strstr function - php

I am getting
Severity: Warning
Message: Wrong parameter count for strstr()
for the following code
$ext = strrev(strstr(strrev($file), ".", TRUE));
What should I do?
Update
In stead of $ext = strrev(strstr(strrev($file), ".", TRUE));
I have used this.
$ext = strrev(substr(strrev($file)), 0 ,strpos(strrev($file), ":"));
Still getting the same error for substr and strrev
This is kind of wierd. Is it related with version problem?

http://php.net/manual/en/function.strstr.php
$user = strstr($email, '#', true); // As of PHP 5.3.0
Check your php version. the 'before_needle' parameter was only added in php version 5.3.0
Maybe you need to upgrade or you will have to remove the parameter.
Hope this helps

As per the docs, you need to update your PHP version to >= 5.3.0 to get the [, bool $before_needle = false ] parameter. It was added in 5.3.0.
If you're just trying to get the extension of a file, you should use pathinfo, like so:
$ext = pathinfo( $file, PATHINFO_EXTENSION);

as others have pointed out, the third parameter of strstr appeared only in PHP 5.3.0. Maybe what you wanted to do is simply
$ext = substr($file, strrpos($file, '.') + 1);
or better
$dotpos = strrpos($file, '.');
if ($dotpos === false) {
$ext = ''; // or other special handling like, e.g., $ext = false;
} else {
$ext = substr($file, $dotpos + 1);
}
This will let you handle separately the cases of a missing and of a trailing dot (pathinfo() returns an empty string in both cases), and also avoids all intermediate strings (just not to waste CPU time)

Try this simple function:
<?php
function my_strstr($haystack, $needle, $before_needle = false)
{
$output = false;
$before_needle = $before_needle === true ? true : false;
if (is_string($haystack) && is_string($needle) && is_bool($before_needle)) {
switch ($before_needle) {
case true:
$output = substr($haystack, 0, strpos($haystack, $needle));
break;
case false:
$output = strstr($haystack, $needle);
break;
}
}
return $output;
}

Related

PHP get file line by line and compare to string

I have a file which is basically a list of names in that format:
name.lastname
name.lastname
name.lastname
myname.mylastname
name.lastname
and I want to check whether a string I have is equal to one of the names (with the dot).
Thats what I tried already:
$username = "myname.mylastname";
$boolean = False;
$handle = fopen("thelist.txt","r");
while (($line = fgets($handle)) !== false) {
if ($line === $username){
$liste = True;
}
}
after that list keeps being False and I dont know why.
Thanks in advance :)
There are a few potential issues I see.
First $boolean = False; while $liste = True;, so you may have a potential typo in your output variable.
Second issue is that thelist.txt is not an absolute path. So the file resource may have failed to be loaded. It is highly recommended that you use an absolute path to file resources such as /full/path/to/file or __DIR__ . '/path/to/file'.
The main issue is that fgets will include the \r and \n at the end of each line in the file, that does not exist in the compared string variable. You can use trim to remove extraneous line endings and white spaces to compare with the string variable.
Example: https://3v4l.org/4VG4D
$username = "myname.mylastname";
$liste = false;
$handle = fopen("thelist.txt", 'rb');
while (false !== ($line = fgets($handle))) {
if (trim($line) === $username){
$liste = true;
break; //stop at first match
}
}
fclose($handle);
var_dump($liste); //true

PHP get the last line of an open file handle with multiple lines

This seems like it should be a simple thing to do but I'm having a bit of trouble with fgetc() when returning the last line of a open file handle. what I'm trying to do is return the last line written to the handle, I have the following which works if the handle has only one line:
function getLastLineFromHandle($handle)
{
$seeker = function($handle) use (&$seeker) {
fseek($handle, -1, SEEK_CUR);
return ftell($handle) ?
$seeker($handle) :
$handle;
};
return trim(fgets($seeker($handle)));
}
$handle = fopen('php://temp', 'w+');
fwrite($handle, 'Hello World'.PHP_EOL);
//prints Hello World
print getLastLineFromHandle($handle);
The problem is when I have multiple lines written to the handle, adding an fgetc() to the check condition doesn't seems to work for example:
function getLastLineFromHandle($handle)
{
$seeker = function($handle) use (&$seeker) {
fseek($handle, -1, SEEK_CUR);
return ftell($handle) && fgetc($handle) != PHP_EOL ?
$seeker($handle) :
$handle;
};
return trim(fgets($seeker($handle)));
}
This returns blank if multiple lines are written to the handle and fgetc($handle) seems to return the same character each time?
I'm sure there is something very simple that I've missed, but any pointers would be great as this is driving me crazy!
Thanks.
Found what was missing from example above, turns out it was case of there being an unexpected end of line char at the pointer at start so moving one position in solves the issue, for example:
function getLastLineFromHandle($handle)
{
$seeker = function($handle) use (&$seeker) {
fseek($handle, -2, SEEK_CUR);
return ftell($handle) && fgetc($handle) != PHP_EOL ?
$seeker($handle) :
$handle;
};
return trim(fgets($seeker($handle)));
}
While exploring this I also found another way of doing the same thing, thanks to #TheMarlboroMan's comment about seeking to the end which sparked this:
function getLastLineFromHandle($handle)
{
$seeker = function($handle, $cur = -2, $line = '') use (&$seeker)
{
$char = '';
if (fseek($handle, $cur, SEEK_END) != -1) {
$char = fgetc($handle);
$line = $char.$line;
}
return ftell($handle) > 0 && $char != PHP_EOL?
$seeker($handle, $cur-1,$line) :
$line;
};
return trim($seeker($handle));
}
This hasn't been through a refactor loop, however it passes the same tests as the other method above. This solution seems to be a bit messy to return the line string instead of the file handle as that is what you would expect back.
Setting this as solved but open for comments if anyone has a different way :)

What is opposite of strrchr function?

I want to remove all characters after last specific string.
For this function I need opposite of strrchr function.
For example, I want to remove all characters after last "." from "Hello.World.pdf". But with strrchr function I can only remove "Hello.World" before "."!
I want something like this code:
<?php
echo strrchr("Hello.World.pdf" , "." , true);
?>
But this code isn't working!
If you are dealing with file names that can have various extensions and you would like to remove the extension, you can get the extension using pathinfo() and then use str_replace() to get rid of it:
$filename = 'Hello.World.pdf';
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$filename = str_replace('.' . $extension, '', $filename);
echo $filename; //Hello.World
More info on pathinfo and str_replace
Try the following:
echo substr('Hello.World.pdf', 0, strrpos('Hello.World.pdf', '.'));
Reading material:
http://php.net/manual/en/function.strrpos.php
http://php.net/manual/en/function.substr.php
Note:
I recommend you verify that strrpos actualy returns a valid value.
EDIT:
$haystack = 'Hello.World.pdf';
$needle = '.';
$pos = strrpos($haystack, $needle);
echo ($pos === false ? $haystack : substr($haystack, 0, $pos));
Since you're interested in filenames and extensions; junkstu almost had it, but you can just use PATHINFO_FILENAME to get the filename without the extension:
echo pathinfo("Hello.World.pdf", PATHINFO_FILENAME);

Strpos is saying it didn't find the string when it should have

I have this:
$fi2 = "/var/www/server/poll/ips.txt"; //IP file
$mystring = $_SERVER['REMOTE_ADDR']; //IP according to server
$findme = file_get_contents($fi2);
$pos = strpos($mystring, $findme);
if ($pos === true) {
echo "Found";
} else {
echo "not found";
}
However, it does not say "not found" even if the IP matches something in the text file. I have done
echo "$mystring $findme";
And it outputs my IP and the text file correctly.
I have been told that I should replace
if ($pos === true) {
with
if ($pos !== false) {
Which I did and it still does not work.
Here's the code I used to save to the text file:
//Record IP
$fi2 = "/var/www/server/poll/ips.txt"; //IP file
file_put_contents($fi2, "\r\n$mystring", FILE_APPEND); //Stick it onto the IP file
I think it's combination of three problems.
Firstly if the file you're loading has a new line at the end of the ip address, it's not going to match:
$findme = file_get_contents($fi2);
change to
$findme = trim(file_get_contents($fi2));
Also as others have pointed out, your pos logic is incorrect.
if ($pos !== false) {
Edit:
Also your argument order for strpos is wrong:
$pos = strpos($findme, $mystring);
Straight from the manual on strpos():
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So the result is a numeric position or FALSE, this means that $pos === true always fails! Another problem is the signature of strpos() is the following:
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
You mixed up $haystack and $needle which may be caused by the poor naming. Try something like this:
$fi2 = "/var/www/server/poll/ips.txt"; //IP file
$ip = $_SERVER['REMOTE_ADDR']; //IP according to server
$file = file_get_contents($fi2);
$pos = strpos($file, $ip);// ($findme, $mystring)
if ($pos !== FALSE) {
echo "found";
} else {
echo "not found";
}
strpos returns a number or false if not found.
The correct if statement would be:
if ($pos !== false) {
Another common mistake is to write:
if (!$pos) {
But if $pos is 0 - which happens if the string is found at the beginning of the string - this check will also fail.
An alternative for the if statement:
if(!is_bool($pos)){
I just figured it out myself.
I changed
file_put_contents($fi2, "\r\n$mystring", FILE_APPEND); //Stick it onto the IP file
To
file_put_contents($fi2, "$mystring", FILE_APPEND); //Stick it onto the IP file
I don't know why this fixed it (just starting PHP) but that's the reason it's broken, so if someone proposes an answer to fix it with the original line I'll accept it.
Changing $pos === true to $pos !== false also was required.

strings comparison in PHP

I feel like the biggest fool on the planet earth. But I am looping through a text file and attempting to compare each line and find the line breaks... You know... "\n". But I can't seem to compare the strings!!!!
Here is what I am doing.
$filename = 'StatesCities.txt';
$file = file($filename);
$matchedLines = array();
foreach($file as $line) {
$matchesLines[] = $line;
if(strcmp($line, "La Mesa") == 0)
{
echo("Yeah");
}
echo($line);
echo("<br />");
}
Are you trying to remove the line breaks? If that's the case then you can explode them.
$file = file_get_contents( $file_path );
$page = explode( "\n", $file );
//Now they're gone
foreach( $page as $line )
{
if( strpos( $line, 'searchfor' ) !== false )
{
//do this
}
}
The strpos is how I usually search in a string, just make sure to use !== which checks for false not false or 0. If the string your looking for has a strpos of 0 ( first character ) it would return a false positive if you don't check for the type with !==. Good luck.
Your question says you're looking for "\n" but your code is looking for "La Mesa". Perhaps you wanted to say
if (strpos($line, "\n"))
?
The file() function will maintain newline characters (\n) in the array that it creates by default. See here for more info; in particular, the flags section. To fix your problem...
Instead of this:
$file = file($filename);
Use this:
$file = file($filename, FILE_IGNORE_NEW_LINES);

Categories