I have the following PHP to grab a part of the URL.
I have a URL www.mysite.com/my-team2.php and it echoes my team instead of my team2.
$page = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos(strtolower($page),'my-team') !== false) {
echo 'my team';
} elseif (strpos(strtolower($page),'my-team2') !== false) {
echo 'my team2';
}
Why is this?
this is because it is finding the first instance first, the else if will never occur, what you should do is swap them
if (strpos(strtolower($page),'my-team2') !== false) {
echo 'my team2';
} elseif (strpos(strtolower($page),'my-team') !== false) {
echo 'my team';
}
so basically what it was doing without swapping them was finding the text 'my-team'
since the text 'my-team'is part of the text 'my-team2', it would always trigger the if without ever seeing the else if, because the if would always == TRUE.
by swapping them and putting the 2 first, 'my-team2' it will have to find that first, thus if the 2 is not in it, then the else if will trigger
That's because my-team is contained in my-team2, so the first test is already true.
Either reverse them (rather simplistic) or use another approach, such as comparing the whole string or using a regular expression match.
Because "my-team" is substring of "my-team2". It's better to use regular expressions on these kind of situtaions.
You should put the most specific match in the first
echo strpos(strtolower($page),'my-team2') !== false ? 'my-team2' : strpos(strtolower($page),'my-team2') !== false ? 'my-team' : '';
Related
I use the code below to check if the URL contains a specific word (eg. foobar):
<?php $geturl = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>
<?php if (strpos($geturl, 'foobar') == true) {
//Do something here
} ?>
This works pretty much perfect but if i try to search for a Greek word (eg. καλημέρα)
<?php if (strpos($geturl, 'καλημέρα') == true) {
//Do something here
} ?>
then it doesn't work. I tried to use also mb_strpos and didn't work too. How can i make it work ?
UPDATE: If i try to echo the saved url with <?php echo $geturl; ?> i am getting this:
/myserver/%CE%BA%CE%B1%CE%BB%CE%B7%CE%BC%CE%AD%CF%81%CE%B1
Instead it should be like that:
/myserver/καλημέρα
For this case apreg_match can do the job for you. You need to match anything that is not in a default character set. In this case I assume that the greek characters are not inside ASCII.
According to this answer by Karolis, you could try to use the following:
if(preg_match('/[^\x20-\x7e]/', $string))
That is not correct
if (strpos($geturl, 'foobar') == true) ..
You must use
if( strpos($geturl, 'καλημέρα') !== false){
//do
}
If the word you are looking for is somewhere in the string, strpos returns a numeric value. It returns false if nothing is found. It never returns true.
Update:
Use for $geturl that
$geturl = 'http://' . urldecode($_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
I currently use:
if(strpos($command->href,§current_view) !== false){
echo '<pre>true</pre>';
} else {
echo '<pre>false</pre>';
}
$command->href will output something like this: /path/index.php?option=com_component&view=orders Whereas
§current_view is outputting orders. These outputs are dynamically generated, but the scheme will always be the same.
What I need to do is return true/false if the words from $current_view match the view=orders in the URLs from $command->href. The issue with my code is, that it doesnt match anything.
What is the correct way to do this?
Please note that the $command->href and the whole code is inside a while function, that pass multiple URLs and this only needs to match the same ones.
Breaking it down to a simple example, using your code and variable values.
$current_view = 'orders';
$command = '/path/index.php?option=com_component&view=orders';
if(strpos($command,$current_view) !== false){
echo '<pre>true</pre>';
}
else {
echo '<pre>false</pre>';
}
The oputput is "true".
Now, go and debug the REAL values of $command->href and $current_view...
I'm pretty confident that the values are not what you think they are.
Does something like:
if(substr($command->href, strrpos($command->href, '&') + 6) == $current_view)
accomplish what you are after?
To explain, strpos get the last instance of a character in a string (& for you, since you said it always follows the scheme). Then we move over 6 characters to take "&view=" out of the string.
You should now be left with "orders" == "orders".
Or do you sometimes include some arguments after the view?
Try parsing url, extracting your view query string value and compare it to $current_view
$query= [];
parse_str(parse_url($command->href)['query'], $query);
if($current_view === $query["view"])
echo '<pre>true</pre>';
} else {
echo '<pre>false</pre>';
}
I have the following strings that contains parts of a domain as string.
$scheme="http";
$host="example.com";
$filename="demo.php";
$request_uri="/folder/demo.php";
$host and $filename variables one of them is optional.
I am using the following code to check if strings contain the correct value, print the successful messege ,else print the error message
if($scheme ="http" OR $host ="example.com" & $filename ="demo.php" & $request_uri ="/folder/demo.php")
{echo "Sucessful";}
else
{echo "Fail";}
It doesnt work as expected, and I am getting "Successful" everytime . I think the AND oprator is being ignored in the if statement.
Any Idea?
if( $scheme == "http"
&& ($host == "example.com" || $filename == "demo.php")
&& $request_uri == "/folder/demo.php"
) {
echo "Sucessful";
} else {
echo "Fail";
}
&& and || are PHP's operators for AND and OR. Also = assigns a value to a variable, not comparing for equality. Use == or === for comparing.
Also, it seemed that your written statement of requirements did not match your code ... so I changed the logic a little and added () to group the logic. From the written it sounds like the $scheme AND $request_uri test were required and either $host or $filename were required. Your code didn't seem to match that. If I misunderstood your written requirment, change the && and || and () around as you require. Note that breaking long boolean expressions into multiple lines and the use of () to group logic often helps with getting it right.
I have this function in a class:
protected $supportedWebsitesUrls = ['www.youtube.com', 'www.vimeo.com', 'www.dailymotion.com'];
protected function isValid($videoUrl)
{
$urlDetails = parse_url($videoUrl);
if (in_array($urlDetails['host'], $this->supportedWebsitesUrls))
{
return true;
} else {
throw new \Exception('This website is not supported yet!');
return false;
}
}
It basically extracts the host name from any random url and then checks if it is in the $supportedWebsitesUrls array to ensure that it is from a supported website. But if I add say: dailymotion.com instead of www.dailymotion.com it won't detect that url. Also if I try to do WWW.DAILYMOTION.COM it still won't work. What can be done? Please help me.
You can use preg_grep function for this. preg_grep supports regex matches against a given array.
Sample use:
$supportedWebsitesUrls = array('www.dailymotion.com', 'www.youtube.com', 'www.vimeo.com');
$s = 'DAILYMOTION.COM';
if ( empty(preg_grep('/' . preg_quote($s, '/') . '/i', $supportedWebsitesUrls)) )
echo 'This website is not supported yet!\n';
else
echo "found a match\n";
Output:
found a match
You can run a few checks on it;
For lower case vs upper case, the php function strtolower() will sort you out.
as for checking with the www. at the beginning vs without it, you can add an extra check to your if clause;
if (in_array($urlDetails['host'], $this->supportedWebsitesUrls) || in_array('www.'.$urlDetails['host'], $this->supportedWebsitesUrls))
I have a new feature on my site, where users can submit any text (I stopped all HTML entries) via a textarea. The main problem I still have though is that they could type "http://somewhere.com" which is something I want to stop. I also want to blacklist specific words. This is what I had before:
if (strpos($entry, "http://" or ".com" or ".net" or "www." or ".org" or ".co.uk" or "https://") !== true) {
die ('Entries cannot contain links!');
However that didn't work, as it stopped users from submitting any text at all. So my question is simple, how can I do it?
This is a job for Regular Expressions.
What you need to do it something like this:
// A list of words you don't allow
$disallowedWords = array(
'these',
'words',
'are',
'not',
'allowed'
);
// Search for disallowed words.
// The Regex used here should e.g. match 'are', but not match 'care' or 'stare'
foreach ($disallowedWords as $word) {
if (preg_match("/\s+$word\s+/i", $entry)) {
die("The word '$word' is not allowed...");
}
}
// This variable should contain a regex that will match URLs
// there are thousands out there, take your pick. I have just
// used an arbitrary one I found with Google
$urlRegex = '(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*#)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*';
// Search for URLs
if (preg_match($urlRegex, $entry)) {
die("URLs are not allowed...");
}
You must use strpos more the once. With your way you evaluate the or statement with returns true / false and pass it to strpos.
This way it should work:
if (strpos($entry, "http://") !== false || strpos($entry, "https://") !== false || strpos($entry, ".com") !== false)
A simple way to do this is to put all the words not allowed into an array and loop through them to check each one.
$banned = array('http://', '.com', '.net', 'www.', '.org'); // Add more
foreach ($banned as $word):
if (strpos($entry, $word) !== false) die('Contains banned word');
endforeach;
The problem with this is if you get too carried away and start banning the word 'com' or something, there are other words and phrases that could be perfectly legal that contains the letters 'com' in that way that would cause a false positive. You could use regular expressions to search for strings that look like URLs, but then you can easily just break them up like I did above. There is no effective way to completely stop people from posting links into a comment. If you don't want them there, you'll ultimately just have to use moderation. Community moderation works very well, look at Stack Overflow for instance.