I am trying to use the following code to check if the current URL is within an array.
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (strpos($url, $reactfulPages) == true) {
echo "URL is inside list";
}
I think the way I have set up the array is incorrect as the following code (checking for one URL) works fine..
if (strpos($url,'url-one') == true) { // Check if URL contains "landing-page"
}
Can anyone help me out?
The array is fine, the functions to check is not the right way. The strpos() function is for checking the string position(s).
The right way to check if something is in your array you can use the in_array() function.
<?php
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if(in_array($url, $reactfulPages)) {
echo "The URL is in the array!";
// Continue
}else{
echo "The URL doesn't exists in the array.";
}
?>
I hope this will work for you.
The function strpos() looks for a substring within a string, and returns the the position of the substring if it is found. That is why your last example works.
If you want to check whether something exists in an array, you should use the in_array() function, like so:
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (in_array($url, $reactfulPages) == true) {
echo "URL is inside list";
}
However, since you're comparing URL's, I'm assuming you want to check whether the URL contains one of the strings from the array, not necessarily matching them as a whole.
In this case, you will need to write your own function, which could look like this:
function contains_any($string, $substrings) {
foreach ($substrings as $match) {
if (strpos($string, $match) >= 0) {
// A match has been found, return true
return true;
}
}
// No match has been found, return false
return false;
}
You can then apply this function to your example:
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (contains_any($url, $reactfulPages)) {
echo "URL is inside list";
}
Hope this helps.
Related
First of all: Yes i did check other answers but they sadly didn't do the trick.
So i'm currently working on a script that checks if an email exists in the database. So the database data is obtained through a webservice and with an input filter function the following JSON object is returned:
{"customers":{"customer":{"lastname":"test","firstname":"login","email":"nielsvanenckevort#hotmail.com"}}}
Now i would like to check if the email is filled in correctly. I'm using a foreach() statement to compare the values but i'm always getting a not found returned. Maybe someone here is able to find the mistake i've made. So the full code is shown down below.
$resultEmail = ($webService->get( $optUser ));
$emailResult = json_encode($resultEmail);
$emailArray = json_decode($resultEmail);
echo ($emailResult);
echo ($chopEmail);
foreach($emailArray->customers->customer as $item)
{
if($item->email == $email)
{
echo "found it!";
}
}
// The $optUser is the JSON object
Probably the quickest way would be strpos function, so you can use it this way
function hasEmail($string, $email)
{
return strpos($string, $email) !== false;
}
//example
echo hasEmail($resultEmail, $email) ? 'Has email' : 'Email not found';
The easiest way to do this would probably be to decode the string as an associative array instead of a json object, and then check if the key email exists using the array_key_exists function.
// passing true to json_decode will make it return an array
$emailArray = json_decode($resultEmail, true);
foreach($emailArray['customers'] as $customer) {
if(array_key_exists('email', $customer)) {
echo 'Found it!';
}
}
It seems your mistake come from the foreach loop. You should write it this way :
foreach($emailArray->customers as $customer) {
if($customer->email == $email) {
echo "found it!";
}
}
Please note that $emailArray is not an array but an object when you don't set the second parameter of the json_decode function :
$obj = json_decode($data);
$array = json_decode($data,true);
Just after some help, I have an array with disallowed words in which I cant show here as they are obscene.
What I want to do is check if $_POST['urlprefix'] != one of the array elements, I am wondering what the easiest way to do this is. Obviously the below only stops one element of the array.
Thanks for any help you may provide
if($_POST['urlprefix'] != $arr[1]) {
print("You've Passed");
} else {
print("You Are Not Allowed To Use That URL Prefix");
}
The examples with in_array() are a quick way to achieve that. You can also use a case-insensitive in_array function by using preg_grep.
But, if ship is a bad word, do you want to allow shippy ? The following code will forbid any prefixes that contain the word, too.
$disallow = false;
foreach($arr as $bad_word) {
if(stripos($_POST['urlprefix'], $bad_word) !== false) {
$disallow = true;
break;
}
}
if($disallow) {
die('Bad words in URL!');
}
You can use the in_array function :
if (!in_array($_POST['urlprefix'], $arr))
{
print("You've Passed");
}
else
{
print("You Are Not Allowed To Use That URL Prefix");
}
http://www.php.net/manual/fr/function.in-array.php
You can use this way. in_array is slower than this method. See more about array_flip.
$words = array('damn','shit');
$flip = array_flip($words);
if(!isset($flip[$_POST['urlprefix']])){
//valid url
}
You can use php in_array function. It checks if a value exists in an array
if(!in_array($_POST['urlprefix'], $arr)) {
print("You've Passed");
} else {
print("You Are Not Allowed To Use That URL Prefix");
}
I'm trying to check if the following is empty or not.
{"players":""}
I have a function that gets that from an api/site and.. well, heres the code.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
}
However, using !=, empty(), or isset(), I still get an empty string, example:
https://minotar.net/avatar//32
Where it should be..
https://minotar.net/avatar/Notch/32
When it's empty, I'd like it to just return 'empty'.
I'm not sure what I'm doing wrong. Any ideas?
In pure php you can check the url segments like
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);
if($segments[2] == '') {
}
//or
if(empty($segments[2])) {
}
//or do your condition
if you are using codeigniter you might say
if(empty($this->uri->segment(2)))
But be sure you loaded the url helper
Hope I understand your question!
Since you were able to have some output, see my changes in the codes.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
// check conversion
if(is_array($players) && !empty($players){
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
} else {
return 'empty';
}
}
You should do this;
print_r($playersList);
just after you set it to see what it actually is. My guess is that you are not getting what you suspect from the getURL call.
Add one more equals sign to take type comparison into account as well
if ($playerList !== '')
try this
if (isset($playersList) && is_array($playersList) && !empty($playersList)) {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
I have a path that I want to check for in a url. How would I isolate
'pages/morepages/'
http://www.mypage.com/pages/morepages/
I've tried running a parse url function on my url and then I get the path. I don't know how to access that key in that array though. For example..
$url = 'http://www.mypage.com/pages/morepages/';
print_r(parse_url($url));
if ($url['path'] == '/pages/morepages/') {
echo 'This works.';
};
I want to run an if conditional on if that path exists, but I am having trouble accessing it.
If you're just looking for one string within another, strpos() will work pretty well.
echo strpos( $url, $path ) !== false ? 'Exists' : 'Does Not Exist' ;
something like find in string ?
if ( strpos($url['path'], '/pages/morepages/') !== false ){
//echo "this works";
}
Here you go
$url = 'http://www.mypage.com/pages/morepages/';
if (strpos($url, '/pages/morepages/') !== false) {
echo "found";
} else {
echo "not found";
}
You can simply use
if (parse_url($url['path'], PHP_URL_PATH) == '/pages/morepages/') {
echo 'This works.';
} // No semicolon
It's probably better to use strpos() though, which is a LOT faster.
Just assign function's result to any variable:
$parts = parse_url($url);
if ($parts['path'] == '/pages/morepages') {
}
Parse_url needs to return something to a new array variable. So use:
$parsedUrl = parse_url($url));
if ($parsedUrl['path'] == '/pages/morepages/') {
echo 'This works.';
};
You are not assigning the output of parse_url to a variable. $url is still equal to the string (parse_url returns an array, it doesn't modify the string passed in).
$url = parse_url($url);
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';