How to simlify php code by using arrays from url strings - php

i'm new at this forum and php.
I want to show some info when the script detects one or more words in the postname (Wordpress)
In my exapmle like to dispaly extra info when Omnik + reset or wifi is detected.
I like to know how i can simplify the following code:
$url = "www.myurl.nl/postname"
if (strpos($url, 'omnik' )!==false){
echo "Omnik";
}
else if (strpos($url, 'reset' )!==false){
echo "Reset";
}
else if (strpos($url, 'wifi' )!==false){
echo "Wifi";
}
else {
echo "No Omnik,Reset or Wifi there";
}
At this moment i can only show the extra info when the word "Omnik" is detected.
Example: https://geaskb.nl/omnik shows the extra info, but https://geaskb.nl/omnik-reset and https://geaskb.nl/omnik-wifi should show the info too, while https://geaskb.nl/solaredge shouldn't show the info.
Hope you get what i mean.
====== Added 20:00 ========
Hi All, thanks for the ansewers.
I should have be clear the 1st time i guess.
This is the code i use now:
// Verkrijg URL incl. subdir.
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
$geturl= "https";
else
$geturl = "http";
// Here append the common URL characters.
$geturl .= "://";
// Append the host(domain name, ip) to the URL.
$geturl .= $_SERVER['HTTP_HOST'];
// Append the requested resource location to the URL
$geturl .= $_SERVER['REQUEST_URI'];
if (strpos($_SERVER['REQUEST_URI'], "omnik" )!==false){
echo "Omnik in url";
}
else {
echo "Geen Omnik in $geturl";
}
============= 20:30u ==================
Problem solved!! stripos solved the problem!
Thanks for all your help!

One way for doing it through foreach loop
<?php
$url = "www.myurl.nl/postname";
$needles = ['omnik', 'reset', 'wifi']; // Add more if needed
foreach($needles as $needle){
if (strpos($url, $needle )!==false){
echo $needle;
}
}
?>

Related

Determine Logo link based on URL using PHP

Situation is getting a logo on:
domain.com/special_dir/any_page
or
domain.com/special_dir/any_dir/
to use a link to [domain.com/special_dir/].
Everywhere else on [domain.com/] the logo must a link to [domain.com/]
This is what I have so far.
<?php
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if( $host == 'domain.com/special_dir/' ) {
echo '<div"><img src="..."></div>';
} else {
echo '<div"><img src="..."></div>';
}
?>
The logo for [domain.com/special_dir/] only works for [domain.com/special_dir/] URL, no others. I suppose the code it doing what it should, I just don't know how to make it recursive. I did search and read a lot of similar situations but none based on PHP code worked for me.
It is WordPress Multi-site setup and the "special_dir" is a regular sub-directory.
How to correct?
Thanks
Your if ($host == 'domain.com/special_dir/') statement means the special link will be printed for domain.com/special_dir/ only. It excludes everything else, including comain.com/special_dir/any_dir and domain.com/special_dir/any_page.
If think you want ...
if (substr($host,0,22) == 'domain.com/special_dir/') { ... }
This did the trick.
<?php
$url = $_SERVER["REQUEST_URI"];
if (strpos($url, "/special_dir/") === 0) {
echo '<div"><img src="..."></div>';
} else {
echo '<div"><img src="..."></div>';
}
?>

This URL validation is not working properly

I have a code that I which is taken from another stackoverflow post,
here it is,
function validate_url($url)
{
$pattern = "/^((ht|f)tp(s?)\:\/\/|~/|/)?([w]{2}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?/";
if (!preg_match($pattern, $url))
{
$this->form_validation->set_message('validate_url', 'The URL you entered is not correctly formatted.');
return false;
}
return false;
}
It is not working properly. It is allowing URL without (something like) .com or .in (anything after dot).
Meaning, it should allow proper the URL as
http://something.com or
http://www.something.in or
but not
http://something (without .in or .com or any other) or
something or
www.something
I don't know much about regular expressions. Please help me..
take a look at this site:
https://mathiasbynens.be/demo/url-regex
It contains a lot of different URL validation regex.
The one from Diego Perini:
_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?#)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS
seems so much better than the one used by filter_var.
You can use filter_var filter_var('http://example.com', FILTER_VALIDATE_URL); for validating your urls.
Here you can find all types of validation types you can use.
If you want to require the http(s) you can add use this.
filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)
Use this
<?php
$url = "http://something";
if ((!filter_var($url, FILTER_VALIDATE_URL) === false) && #fopen($url,"r")) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
Or use this
<?php
$url = 'http://example';
if(validateURL($url)){
echo "Valid";
}else{
echo "invalid";
}
function validateURL($URL) {
$pattern_1 = "/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
$pattern_2 = "/^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){
return true;
} else{
return false;
}
}
?>
You can use following regular expression
$url = 'http://something.com';
$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?#)?"; // User and Pass
$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:#&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
if(preg_match("/^$regex$/", $url)) {
echo "Matched";
} else {
echo "Not Matched";
}

Find the Page Urls

I have page and I don't show a specific block to a specific urls.
So my urls are www.example.com/products/product1.html, www.example.com/products/product2.html etc..
So what I want to do. I want to find all the urls that starts with www.example.com/products/ and in those urls, exclude the block.
So far my code for one url is:
<?php
$a = "www.example.com/products/product2";
$p = curPageURL(); ?>
<?php
if($a == $p ){
Dont show the block
?>
But I have 100 urls that I don't show the block.
Is there any change to do for all the urls without write 200 lines of code?
Use PHP's strpos
This function will check if the specified string exists in the URL and if it exists, do not show the block.
$findme = 'www.example.com/products/';
$pos = strpos($mystring, $findme);
if ($pos === FALSE) {
// SHOW BLOCK
}
Try with strpos()
$cururl= "http://.".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$pos = strpos($cururl, '/products/');
if ($pos !== FALSE) {
// products found do your stuff
}
I think you can do this with the in_array()-function like this:
$blockedUrlArray[] = "www.example.com/products/product2";
$blockedUrlArray[] = "www.example.com/products/product3";
.
.
.
$searchUrl = curPageURL();
//if the current Url is not in blocked Urls
if(!in_array($searchUrl, $blockedUrlArray){
//do something
}
//if the url is a blocked url
else{
//do something
}

Url validation with regex for old php version

Note: I'm using an older PHP version so FILTER_VALIDATE_URL is not available at this time.
After many many searches I am still unable to find the exact answer that can cover all URL structure possibilities but at the end I'm gonna use this way:
I'm using the following function
1) Function to get proper scheme
function convertUrl ($url){
$pattern = '#^http[s]?://#i';
if(preg_match($pattern, $url) == 1) { // this url has proper scheme
return $url;
} else {
return 'http://' . $url;
}
}
2) Conditional to check if it is a URL or not
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i", $url)) {
echo "URL is valid";
}else {
echo "URL is invalid<br>";
}
Guess What!? It works so perfect for all of these possibilities:
$url = "google.com";
$url = "www.google.com";
$url = "http://google.com";
$url = "http://www.google.com";
$url = "https://google.com";
$url = "https://www.codgoogleekarate.com";
$url = "subdomain.google.com";
$url = "https://subdomain.google.com";
But still have this edge case
$url = "blahblahblahblah";
The function convertUrl($url) will convert this to $url = "http://blahblahblahblah";
then the regex will consider it as valid URL while it isn't!!
How can I edit it so that it won't pass a URL with this structure http://blahblahblahblah
If you want to validate internet url's, add a check for including a dot (.) character in your reg-ex.
Note: http://blahblahblah is a valid url as is http://localhost
Try this:
if (preg_match("/^(([\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})*)?$/", $url)) {
echo "URL is valid";
}else {
echo "URL is invalid<br>";
}

verify a PHP variable and get result from it

Here is my code:-
<?php
$URL = "http://www.mylink.com/show_album/XXXXX";
/*The value of $URL will be passed from previous page via Form*/
?>
First, The value of the variable must be a link/URL. If not, echo "Not an URL"; should be executed. But, I am unable to check if it's a link or not. Please, anyone help me to figure out this. As a newbie, I need help badly.
Second, The http:// is optional. If provided, it's okay. Else, "http://" will be added automatically. I used this code for this and it works.
if(strpos($URL, "http://") !== false){
echo $URL;
echo "<br />http:// already provided";
return $URL;
}
else {
echo "http://" . $URL;
$URL = "http://" . $URL;
echo "<br />http:// automatically added";
return $URL;
}
Third, The text "mylink.com/show_album/" (without quote) must be available in $URL. I used this code for this:-
if (strpos($URL, "mylink.com/show_album/") !== false){
echo "The "mylink.com/show_album/ is available";
}
else {
echo "The "mylink.com/show_album/ is not available";
}
It's okay.
Next, In the $URL, the value is a link name with a last word XXXXX. It must be the last word of this variable. XXXXX is a number. It can be any number like "12345" or any other. But, I want to get the Number from this $URL and show it. How can I do this?
At last, The link can only contain http:// and www.mylink.com/show_album/XXXXX . Otherwise, the echo "Not a valid link"; will be executed. How to do this?
For Validating URLs:
$text = preg_replace("
#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie",
"'$3$4'",
$text
);
For validating/appending http:// on front of URL, do something like:
$protocol = substr($URL, 0, 7);
if($protocol!="http://")
{
$URL="http://".$URL;
}
EDIT
Now for fetching the last numbers:
$XXXXX=substr( $URL, strrpos( $url, '/' )+1 );

Categories