I am trying to isolate link from array but in foreach loop it does not work for me.it cosider both elements as a link.
i just want to hyper link google.com and not bakery text but i am getting link on both so if part is not working and its considering bakery as a link.
$services=array('Bakery','www.google.com');
foreach($services as $service):
if (!filter_var($service, FILTER_VALIDATE_URL) === false) {
$service = $service;
} else {
$service = '<a href='.$service.'>'.$service.'</a>';
}
echo $service;
endforeach;
The problem here is with the following statement:
if (!filter_var($service, FILTER_VALIDATE_URL) === false)
^ ^^^^^
You're using a double negative here, being the ! operator which means "not" and you're using "false".
Either remove the ! or change the "false" to "true".
You're also going to need to add http:// to the url you wish to use in order to validate properly.
$services=array('Bakery','www.google.com');
will fail for the Google link. If you want it to validate, you will need to change it to:
$services=array('Bakery','http://www.google.com');
Related
I am now using this code for facebook. "https" is active and wordpress site.
<?php
$ref = $_SERVER['HTTP_REFERER'];
if (strpos($ref, 'facebook.com') != false) {
?>
DON'T SHOW ADS
<?php } else { ?>
SHOW ADS
<?php } ?>
This code works for facebook. I wanted to add twitter, but when I add twitter it doesn't work at all. I tried this.
if (strpos($ref, 'facebook.com', 'twitter.com', 't.co') != false) {
It didn't work that way. If else query or "false" is correct? How can I do it in the simplest way? If the visitor comes from Facebook, Twitter, I don't want to show ads. thanks
strpos() does not check multiple "needles" to look for. You can store them in an array
and iterate over each one individually though:
<?php
$ref = $_SERVER['HTTP_REFERER'];
$sitesWithAdsHidden = [
'facebook.com',
'twitter.com',
't.co',
];
$isHiddenSite = false;
foreach ($sitesWithAdsHidden as $site) {
if (strpos($ref, $site) !== false) {
$isHiddenSite = true;
break;
}
}
if ($isHiddenSite) {
?>
DON'T SHOW ADS
<?php } else { ?>
SHOW ADS
<?php } ?>
Note that I also changed the strpos comparison to !== because a non-strict check could lead to evaluating to false if the position is actually 0 (the start of the string).
First and foremost, directly from Wikipedia:
"The referrer field is an optional part of the HTTP request sent by the web browser to the web server."
Therefore, you should always check that the Http Referer exists in the request. You can achieve this by using !empty() or isset(), however, for future maintainability, you can also use array_diff and array_keys.
You can then also achieve this without having to iterate over an array using preg_match.
if(!array_diff(['HTTP_REFERER'], array_keys($_SERVER)))
if(preg_match('/facebook|twitter/', $_SERVER['HTTP_REFERER']))
// todo: disable adverts
You could also use the null cascading operator to reduce this to one line. Do this if you have no further checks to make from the $_SERVER global variable.
if(preg_match('/facebook|twitter/', $_SERVER['HTTP_REFERER'] ?? ''))
// todo: disable adverts
I need to create a an if statement that fires if there is something after a given string in the URL.
For example, if my string is 'Honda' I need to check if something appears after that word in the url, eg something like:
$brand = "honda";
if (url contains $brand . '/*'){
// Do something.
}
Example urls could be:
mysite.com/honda (which would fail the above)
mysite.com/cars/honda (which would fail the above)
mysite.com/honda/civic (which would pass the above)
mysite.com/honda/accord (which would pass the above)
I know I can use strpos() to detect if the string is within the URL, but how can I detect if anything comes after that?
Use a regular expression that looks for the $brand at the end of the string.
if (! preg_match("/{$brand}$/", $url)) {
// ...
}
If you need to check if the $brand actually appears in the URL before running your end of string check:
if (strpos($brand, $url) !== false && ! preg_match("/{$brand}$/", $url)) {
// ...
}
I'm having php script that deals with thousands of queries starting just like (i.e. http://localhost:1234/browse.php?cat=2) so I don't want to write thousands of URLs in an array to deal with if and else condition such as below,
Please guide me how can i make it possible to use "?" sign in my url to distinguish between what command to process if url contains "?" sign.
I used "/browse.php?*" in code as shown in below example but it's not working for me still...Please guide because I'm new in php and search and lot regarding this answer but unable to find a single authentic answer for it, thanks
if(in_array($_SERVER['REQUEST_URI'],array('/browse.php','/browse.php?*')))
{
echo "<Something Like this 1>";
}
elseif ($url == "")
{
echo "<Something Like this 2>";
};
in_array would only check for a full match here and is not appropriate for what you are trying to do. PHP has many String Functions you should look at.
if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {
//URL has '?' mark
}
else{
//URL has no '?' mark
}
I believe you are only concerned with the cat URL search parameter? If so, you can access this parameter in your browse.php script using the $_GET array:
<?php
if (array_key_exists('cat', $_GET)) {
echo "cat parameter: {$_GET['cat']}"; // display ?cat=value
} else {
echo 'No cat URL parameter'; // ?cat was not in the URL
}
?>
http://localhost:1234/browse.php -> No cat URL parameter
http://localhost:1234/browse.php?cat=57890 -> cat parameter: 57890
So, a lot of my form systems redirect back to the previous page, although, they display a message in the process. The way I display a message is by simply using ?message=messageCode in the URL.
However, if they use the form from a page that already has a query string, it adds a second query string, messing everything up.
Example:
if I were to login from the navigation bar, on the URL "mywebsite.com/something?message=1", it would log in, but redirect to "mywebsite.com/something?message=1?message=2"
This results in no message being displayed.
What I am asking here is, how could I change all of the question marks AFTER the first question mark, to and signs?
Example:
From: mywebsite.com/page?blah=1?something=2?hi=3
To: mywebsite.com/page?blah=1&something=2&hi=3
I have searched around, as well as tried some methods of my own, but nothing seems to work properly.
What you should be doing is build a proper URL, appending ? or & when appropriate.
$url = 'mywebsite.com/something?message=1';
$new_url = sprintf('%s%s%s',
$url,
strpos($url, '?') === false ? '?' : '&',
http_build_query(['message' => 2])
);
Or, first parse the previous URL and merge the query string.
Use it like below:-
<?php
$str = 'mywebsite.com/something?message=1?message=2';
$pos = strpos($str,'?'); //check the last occurrence of ?
if ($pos !== false) {
$str = substr($str,0,$pos+1) . str_replace('?','&',substr($str,$pos+1));// replacement of ? to &
}
echo $str;
?>
Output:- https://eval.in/388308
I'm trying to check if a user submitted URL is valid, it goes directly to the database when the user hits submit.
So far, I have:
$string = $_POST[url];
if (strpos($string, 'www.') && (strpos($string, '/')))
{
echo 'Good';
}
The submitted page should be a page in a directory, not the main site, so http://www.address.com/page
How can I have it check for the second / without it thinking it's from http:// and that doesn't include .com?
Sample input:
Valid:
http://www.facebook.com/pageName
http://www.facebook.com/pageName/page.html
http://www.facebook.com/pageName/page.*
Invalid:
http://www.facebook.com
facebook.com/pageName
facebook.com
if(!parse_url('http://www.address.com/page', PHP_URL_PATH)) {
echo 'no path found';
}
See parse_url reference.
See the parse_url() function. This will give you the "/page" part of the URL in a separate string, which you can then analyze as desired.
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)
More information here :
http://ca.php.net/filter_var
Maybe strrpos will help you. It will locate the last occurrence of a string within a string
To check the format of the URL you could use a regular expression:
preg_match [ http://php.net/manual/en/function.preg-match.php ] is a good start, but a knowledge of regular expressions is needed to make it work.
Additionally, if you actually want to check that it's a valid URL, you could check the URL value to see if it actually resolves to a web page:
function check_404($url) {
$return = #get_headers($url);
if (strpos($return[0], ' 404 ') === false)
return true;
else {
return false;
}
}
Try using a regular expression to see that the URL has the correct structure. Here's more reading on this. You need to learn how PCRE works.
A simple example for what you want (disclaimer: not tested, incomplete).
function isValidUrl($url) {
return preg_match('#http://[^/]+/.+#', $url));
}
From here: http://www.blog.highub.com/regular-expression/php-regex-regular-expression/php-regex-validating-a-url/
<?php
/**
* Validate URL
* Allows for port, path and query string validations
* #param string $url string containing url user input
* #return boolean Returns TRUE/FALSE
*/
function validateURL($url)
{
$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?#)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
return preg_match($pattern, $url);
}
$result = validateURL('http://www.google.com');
print $result;
?>