Check URL parameter in php - php

I want to check a parameter in a url variable, for example:
$var2join = 'en'; // can be anything else
$url = 'https://www.example.com/hello/parameter2';
$url2 = 'https://www.example.com/hello2';
$url3 = 'https://www.example.com/en/hey';
first check if the $url vars have the $var2join into $var as parameter if have it, leave it intact and if not add it.
Wanted output:
$url = 'https://www.example.com/en/hello/parameter2';
$url2 = 'https://www.example.com/en/hello2';
$url3 = 'https://www.example.com/en/hey';
I tried:
$url = (!preg_match('~^/[a-z]{2}(?:/|$)~', $location)) ? '/' . $var2join . $url : $url;

Use parse_url(), it is specifically for analysing URLs and their various elements.
Note this code assumes your parameters are path segments, as you describe above. If you ever use query string parameters like ?foo=bar, you'd need to adjust.
$var2join = 'en';
$url = 'https://www.example.com/hello/parameter2';
// Split URL into each of its parts
$url_parts = parse_url($url);
// Create an array of all the path parts, which correspond to
// parameters in your scheme
$params = explode('/', $url_parts['path']);
// Check if your var is in there
if (!in_array($var2join, $params)) {
// If not, reconstruct the same URL, but with your var inserted.
// NOTE this assumes a pretty simple URL, you'll need to adjust if
// you ever have other elements like port number, u/p, query strings
// etc. #Jason-rush links to something in the PHP docs to handle
// such cases.
$url = $url_parts['scheme'] . '://' . $url_parts['host'] . '/' . $var2join . $url_parts['path'];
}
// Check your result - https://www.example.com/en/hello/parameter2
echo $url;

This is a little generic function with some support code to give you some ideas... Not very elegant but it works.
<?php
$base_url = 'https://www.example.com/';
$var2join = 'en'; // can be anything else
$url = $base_url . 'hello/parameter2';
$url2 = $base_url . 'hello2';
$url3 = $base_url . 'en/hey';
$url4 = $base_url . 'hey/this/is/longer';
echo prepend_path_to_url($base_url, $url, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url2, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url3, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url4, $var2join);
echo '<br>';
/**
* Prepend a Path to the url
*
* #param $base_url
* #param $url
* #param $path_to_join
* #return string
*/
function prepend_path_to_url($base_url, $url, $path_to_join) {
// Does the path_to_join exist in the url
if (strpos($url, $path_to_join) === FALSE) {
$url_request = str_replace($base_url,'',$url);
$url = $base_url . $path_to_join . '/'. $url_request;
}
return $url;
}

Related

How to construct url with http_build_query, but display values without variables?

I'm trying to generate an URL from all values of two arrays by using http_build_query:
Array 1:
$server = array($_GET["server"]);
Array 2:
$data = array($_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"],);
The code for generating URL I currently have written:
$server = array(''=>$_GET["server"]);
$data = array($_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"],);
$url = '.tile.openstreetmap.org';
$saite = http_build_query($server). $url ."/". http_build_query($data,'','/').".png";
Here's the URL made of code above:
=c.tile.openstreetmap.org/0=6/1=90/2=110.png
Here's the structure of url I'm trying to make:
c.tile.openstreetmap.org/6/90/110.png
I have reviewed some other posts about this topic like this one and this, but those posts aren't completely useful for solving my problem.
So I hope someone with greater knowledge could show me a solution or at least a hint how to get closer to solution.
You could use implode():
$server = $_GET["server"];
$data = [$_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"]];
$url = '.tile.openstreetmap.org';
$saite = "$server/$url/" . implode('/', $data) . ".png";
I'm not sure about some things in this code, but the implode() should do the job.
You are using http_build_query in the wrong way. You just don't need that. There are 2 options, you may use any one of them.
Use implode(), the simplest way to do the job.
$server = array(
'' => $_GET['server']
);
$data = array(
$_GET['z_koord'],
$_GET['x_koord'],
$_GET['y_koord'],
);
$url = $server . '.tile.openstreetmap.org';
$saite = $url . '/' . implode("/", $data) . '.png';
Directly create the URL using the Parameters as shown here:
$url = '.tile.openstreetmap.org' .;
$saite = $_GET['server'] . $url . '/' . $_GET['z_koord'] .'/'. $_GET['x_koord'] . '/'.$_GET['y_koord'] . '.png';

How can I implement an add/edit parameter mechanism?

Assume this is my current URL:
http://example.com/search?param1=foo&param2=bar
Now I want to add param3=baz. So this is the code:
<a href="?param3=baz" >add param3</a>
//=> http://example.com/search?param3=baz
See? param1 and param2 will be removed. So I have to handle it like this:
<?php
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
$query_params = $query_params == '' ? '?' : $query_params . '&';
?>
<a href="?{$query_params}param3=baz" >add param3</a>
Seems ugly, but ok, nevermind. Now what happens if a parameter be already exist and I need to edit it? Assume this example:
http://example.com/search?param1=foo&param2=bar
Now how can I make a link which edits the value of parame2? (plus keeping other parameters)
You can use function http_build_query to generate new query, like this:
$url = 'http://example.com/search?param1=foo&param2=bar';
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $params);
$data = [
'param3' => 'baz'
];
$params = array_merge($params, $data);
echo http_build_query($params) . "\n";
And output will be:
param1=foo&param2=bar&param3=baz
I use array_merge for override exist params, if we get url:
$url = 'http://example.com/search?param1=foo&param3=bar';
The same code output will be:
param1=foo&param3=baz
We override exist param and save old params.
There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.
You have to Do again:
search?param1=foo&param=bar&param3=baz
Or
Using Javascript is Possible
How to add a parameter to the URL?
Or
function currentUrl() {
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
return $protocol . '://' . $host . $script . '?' . $params;
}
Then add your value with something like;
echo currentUrl().'&param3=baz';
or
Whatever GET parameters you had will still be there and if param3 was a
parameter before it will be overwritten, otherwise it will be included
at the end.
http_build_query(array_merge($_GET, array("param3"=>"baz")))

PHP: Change HTML href Parser function to only match if it finds a static string in url

i am trying to modify some code that parses text for html hyperlinks and puts them into a database.
The change i'm trying to make is to only match if html hyperlink contains a certain text such as:
my image
would not be matched but
my image2
would be matched based on that it has the "/thisismyunique/string" in the url.
Any ideas?
class blcHTMLLink extends blcParser {
var $supported_formats = array('html');
/**
* Parse a string for HTML links - anchor text
*
* #param string $content The text to parse.
* #param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
* #param string $default_link_text
* #return array An array of new blcLinkInstance objects. The objects will include info about the links found, but not about the corresponding container entity.
*/
function parse($content, $base_url = '', $default_link_text = ''){
//remove all <code></code> blocks first
$content = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $content);
//Find links
$params = array(
'base_url' => $base_url,
'default_link_text' => $default_link_text,
);
$instances = $this->map($content, array($this, 'parser_callback'), $params);
//The parser callback returns NULL when it finds an invalid link. Filter out those nulls
//from the list of instances.
$instances = array_filter($instances);
return $instances;
}
/**
* blcHTMLLink::parser_callback()
*
* #access private
*
* #param array $link
* #param array $params
* #return blcLinkInstance|null
*/
function parser_callback($link, $params){
global $blclog;
$base_url = $params['base_url'];
$url = $raw_url = $link['href'];
$url = trim($url);
//$blclog->debug(__CLASS__ .':' . __FUNCTION__ . ' Found a link, raw URL = "' . $raw_url . '"');
//Sometimes links may contain shortcodes. Execute them.
$url = do_shortcode($url);
//Skip empty URLs
if ( empty($url) ){
$blclog->warn(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (empty URL)');
return null;
};
//Attempt to parse the URL
$parts = #parse_url($url);
if(!$parts) {
$blclog->warn(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (parse_url failed)', $url);
return null; //Skip invalid URLs
};
if ( !isset($parts['scheme']) ){
//No scheme - likely a relative URL. Turn it into an absolute one.
//TODO: Also log the original URL and base URL.
$url = $this->relative2absolute($url, $base_url); //$base_url comes from $params
$blclog->info(__CLASS__ .':' . __FUNCTION__ . ' Convert relative URL to absolute. Absolute URL = "' . $url . '"');
}
//Skip invalid links (again)
if ( !$url || (strlen($url)<6) ) {
$blclog->info(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (invalid/short URL)', $url);
return null;
}
//Remove left-to-right marks. See: https://en.wikipedia.org/wiki/Left-to-right_mark
$ltrm = json_decode('"\u200E"');
$url = str_replace($ltrm, '', $url);
$text = $link['#link_text'];
//The URL is okay, create and populate a new link instance.
$instance = new blcLinkInstance();
$instance->set_parser($this);
$instance->raw_url = $raw_url;
$instance->link_text = $text;
$link_obj = new blcLink($url); //Creates or loads the link
$instance->set_link($link_obj);
return $instance;
}
If you already have a href index in your $link parameter, which should contains the URL, you could easily do this:
$blockedWord = '/thisismyunique/string';
$blockedWordPosition = strpos($link['href'], $blockedWord);
$hasBlockedWord = $blockedWordPosition !== false;
Watch out, because strpos could return 0, if the needle has found in the beginning of the haystack string.
Find out more here:
http://php.net/manual/en/function.strpos.php

Looping through CSV and parsing a JSON query using each result

So despite hours of fiddling I cannot understand why my JSON query only returns a result for the last line in the CSV/TXT files I am trying to parse.
Here is the code:
//Enter API Key Here
$api_key = 'AIzaSyB9Dq3w1HCxkS5qyELI_pZuTmdK8itOBHo';
$origin = 'RG12 1AA';
$output_type = 'json'; //xml or json
$csv_location = 'http://www.naturedock.co.uk/postcodes.csv';
//Do not edit
$base_url = 'https://maps.googleapis.com/maps/api/directions/';
$origin_url = '?origin=';
$destination_url = '&destination=';
$end_url = '&sensor=false&key=';
$page = join("",file("$csv_location"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$destination = $kw[$i];
echo $destination;
$raw_url = $base_url . $output_type . $origin_url . $origin . $destination_url . $destination . $end_url . $api_key;
$request_url = str_replace(' ', '', $raw_url);
$getJson = file_get_contents($request_url);
$routes = json_decode($getJson);
$result = $routes->routes[0]->legs[0]->distance->value;
echo $result . '<br>';
}
The result I get looks like this:
Distance by Post Code Generator v0.1 by Phil Hughes
RG12 0GA
RG12 0GB
RG12 0GC
RG12 0GD4066
Where the '4066' is the correct variable for RG12 0GD postcode but none of the others return results as you can see.
Please help.
Your
join("",file("$csv_location"));
concatenated all lines feom the file to a single line without separator. The following explode() sees no newlines any more. So you are working on one line only. count($kw) always evaluates to 1 and your loop runs only one time.

Retrieve a Get Http request in php

I need to retrieve a get http request in php and store it in a variable.
I need to execute the following:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
I know this is simple. just not able to get my head around it.
$content = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials');
Within the Open Graph protocol page on Facebook, there is an example within the documentation coded using PHP: http://developers.facebook.com/docs/opengraph/
<?php
$ogurl = "INSERT_YOUR_OG_URL_HERE";
define(FACEBOOK_APP_ID, "YOUR_APP_ID_HERE");
define(FACEBOOK_SECRET, "YOUR_SECRET_KEY_HERE");
$mymessage = "Hello World!";
$access_token_url = "https://graph.facebook.com/oauth/access_token";
$parameters = "grant_type=client_credentials&client_id=" . FACEBOOK_APP_ID ."&client_secret=" . FACEBOOK_SECRET;
$access_token = file_get_contents($access_token_url . "?" . $parameters);
$apprequest_url = "https://graph.facebook.com/feed";
$parameters = "?" . $access_token . "&message=" . urlencode($mymessage) . "&id=" . $ogurl . "&method=post";
$myurl = $apprequest_url . $parameters;
$result = file_get_contents($myurl);
// output the post id
echo "post_id" . $result;
}
?>
The key line in actually making the call being:
$result = file_get_contents($myurl);
There is also a good amount of other information about the resulting object you get back there that would be good to take a look into.
Hope this is helpful.
if ($fp = fopen('https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
// do something with the content here
// ...
} else {
// an error occured when trying to open the specified url
}
You mean something like
$client_id = $_GET['client_id'];
$client_secret = $_GET['client_secret'];
$grant_type = $_GET['grant_type'];
?
Or rather something like
$content = file_get_contents($url);
?
Use the following
$id = $_GET['client_id'];
$type = $_GET['grant_type'];
$secret = $_GET['client_secret'];
Hope this helps you

Categories