Extract location from URL using strpos - php

How do I extract a location from a url using strpos? If I can't use strpos, then what is a good alternative?
Here's the URL:
http://www.kijiji.ca/rss-srp-jobs/ontario/c45l9004
I've tried to use strpos:
if (strpos($url,'ontario') !== false){
echo "yes";
}
But it comes up with nothing. On top of this, I need to determine the source of the feed. The breakdown's like this:
Determine the source of the RSS Feed (Kijiji)
Check for the location in the $url variable (ontario) only if the source is Kijiji.
Here's my code so far:
if (strpos($url,'kijiji') !== false){
if (strpos($url,'ontario') !== false){
echo "ontario";
}
}
Ideally, Id like this script to check for a location in many different urls, so I can pinpoint the location when displaying a Job Ad.

Use parse_url function in order to get all the infgo you need.
See parse_url

Your script works for me. Are you sure you have defined $url? Like:
$url = 'http://www.kijiji.ca/rss-srp-jobs/ontario/c45l9004';
if (strpos($url,'ontario') !== false){
echo "yes";
}
And indeed have a look at url_parse function, which is for this kind of things

means domain related locality/local jobs
$listedDomains["http://www.kijiji.ca/rss-srp-jobs/%loc%/c45l9004"] = "ontario";
$listedDomains["http://www.example.com/rss-srp-jobs/%loc%/c45l9004"]= "bangalore";
foreach($listedDomains as $keyUrl=>$keyLocation)
{
echo str_replace("%loc%",$keyLocation,$keyUrl);
echo "<br />";
}

Related

I don't want to display ads to Facebook, Twitter Visitors

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

Return true/false if word in URL matches specific word

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>';
}

How to select multiple URLs wiht request_uri

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

Most efficient way to check a URL

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;
?>

how to echo data that we read with file_get_contents

i want to check remote url's page contents. IF remote site's page content contains string http://yahoo.com set $qqq = YH if not contains $qqq = NOYH. i am not talking about "url of that page" im talking about page content of url
$url = "'".$get['url']."'";
$needle = "http://yahoo.com/";
$contents = file_get_contents($url);
if(stripos($contents, $needle) !== false) {
$qqq = "YH";
}
But it's not working. Can anybody help me with the correct syntax? thanks..
$url = $get['url'];
$needle = "http://yahoo.com/";
$contents = file_get_contents($url);
if(stripos($contents, $needle) !== false) {
$qqq = "YH";
echo $qqq; // <--in order to echo, you need to call echo.
}
If your goal is just to echo YH if it exists, you can just call it directly with,
echo "YH";
Rather than storing it into a variable.
It think your code won't work. For a number of reasons:
In your first line, you create a string, that contains single-quotes. So basically, $url contains something like 'http://url.here'. If you pass this to file_get_contents you get an error:
$url = "'http://www.google.com'";
echo file_get_contents($url);
Warning: file_get_contents('http://www.google.com/'): failed to open stream:
No such file or directory in ...
You said want to check whether $url contains a certain string. But you are checking whether the document the URL is pointing to, contains this string.
3. Maybe you mean $_GET instead of $get to retrieve the parameter url that is contained in the URL?
Ok, I read from the comments that you indeed want to search for the string in the content. Still, the first line of code is wrong, so it is probably:
$needle = "http://yahoo.com/";
$contents = file_get_contents($get['url']);
if(stripos($contents, $needle) !== false) {
$qqq = "YH";
}
(<?= $qqq ?> should work as it is).
There seems to be some confusion with your question and the title.
To answer "if $url contains http://yahoo.com/" then the following will do:
$url = "'".$get['url']."'";
$needle = "http://yahoo.com/";
if(stripos($url, $needle) !== false) {
$qqq = "YH";
}
Of course, you can use <?=$qqq?> to output the result.
You need to debug, so break it down step by step:
<?PHP
// make sure you see any errors (remove this later)
error_reporting(E_ALL);
ini_set('display_errors',1);
$url = $get['url'];
die($url);
?>
Is the URL correct?
<?PHP
// make sure you see any errors (remove this later)
error_reporting(E_ALL);
ini_set('display_errors',1);
$url = $get['url'];
die(file_get_contents($url));
?>
Does your script echo what looks like the response from $url?
Then continue building out and testing...
Without seeing all of your code, nobody here will be able to guess what you're doing wrong, but it should be easy, fun, and instructional for you to figure it out for yourself.
I hope this answer sends you off in the right direction.
Make sure you have PHP warnings on -- you should always set error_reporting(E_ALL) in a development environment anyway.
Make sure you have allowed URIs as parameters for fopen based functions allow_url_fopen - http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

Categories