How to get the full URL of a Drupal page? - php

I need to be grabbing the URL of the current page in a Drupal site. It doesn't matter what content type it is - can be any type of node.
I am NOT looking for the path to theme, or the base url, or Drupal's get_destination. I'm looking for a function or variable that will give me the following in full:
http://example.com/node/number
Either with or without (more likely) the http://.

drupal_get_destination() has some internal code that points at the correct place to getthe current internal path. To translate that path into an absolute URL, the url() function should do the trick. If the 'absolute' option is passed in it will generate the full URL, not just the internal path. It will also swap in any path aliases for the current path as well.
$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));

This is what I found to be useful
global $base_root;
$base_root . request_uri();
Returns query strings and it's what's used in core: page_set_cache()

You can also do it this way:
$current_url = 'http://' .$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
It's a bit faster.

Try the following:
url($_GET['q'], array('absolute' => true));

This method all is old method, in drupal 7 we can get it very simple
current_path()
http://example.com/node/306 returns "node/306".
http://example.com/drupalfolder/node/306 returns "node/306" while base_path() returns "/drupalfolder/".
http://example.com/path/alias (which is a path alias for node/306) returns "node/306" as opposed to the path alias.
and another function with tiny difference
request_path()
http://example.com/node/306 returns "node/306".
http://example.com/drupalfolder/node/306 returns "node/306" while base_path() returns "/drupalfolder/".
http://example.com/path/alias (which is a path alias for node/306) returns "path/alias" as opposed to the internal path.
http://example.com/index.php returns an empty string (meaning: front page).
http://example.com/index.php?page=1 returns an empty string.

I find using tokens pretty clean.
It is integrated into core in Drupal 7.
<?php print token_replace('[current-page:url]'); ?>

The following is more Drupal-ish:
url(current_path(), array('absolute' => true));

For Drupal 8 you can do this :
$url = 'YOUR_URL';
$url = \Drupal\Core\Url::fromUserInput('/' . $url, array('absolute' => 'true'))->toString();

Maybe what you want is just plain old predefined variables.
Consider trying
$_SERVER['REQUEST_URI'']
Or read more here.

Related

Php get value of part of url

I have a url (as below). I'd like to get the value of "2". How can I get that?
http://domain.com/site1/index.php/page/2
What you're looking for is a combination of pathinfo and parseurl:
pathinfo(parseurl($url)['path'])['filename'];
pathinfo will break the path into well-defined parts, of which filename is that last part you're looking for (2). If you're looking instaed for the absolute location in the path, you may want to split the path on / and simply get the value at index 3.
We can test this like so:
<?php
$url = "http://domain.com/site1/index.php/page/2";
$value=pathinfo(parse_url($url)['path'])['filename'];
echo $value."\n";
And then on the command line:
$ php url.php
2
I use nathaniel fords example but if you run into a problem where files are named '2.html' some servers will load those even though you have '2'.
You can also do this.
home.php?page=2 as the web address
home.php
<?php
// check to see if $page is set
$page = $POST[page];
$page = preg_replace('/\D/', '', $page);
if(!isset($page)){
query page two stuff or what you need.
}
?>

Yii2 - Get an app URL without params

I have no idea how to get a full url to my app web folder in Yii2.
The following rules:
<?=Yii::$app->getUrlManager()->getBaseUrl();?><br>
<?=Yii::$app->homeUrl;?><br>
<?=Yii::$app->getHomeUrl();?><br>
<?=Yii::$app->request->url;?><br>
<?=Yii::$app->request->absoluteUrl;?><br>
<?=Yii::$app->request->baseUrl;?><br>
<?=Yii::$app->request->scriptUrl;?><br>
<?=Url::to();?><br>
<?=Url::to(['site/index']);?><br>
<?=Url::base();?><br>
<?=Url::home();?><br>
<?=Yii::$app->getUrlManager()->getBaseUrl();?><br>
returns:
/yiiapp/web
/yiiapp/web/
/yiiapp/web/
/yiiapp/web/en/reset-password-request
http://website.com/yiiapp/web/en/reset-password-request
/yiiapp/web
/yiiapp/web/index.php
/yiiapp/web/en/reset-password-request
/yiiapp/web/site/index
/yiiapp/web
/yiiapp/web/
/yiiapp/web
when I need to get the (absoluteUrl is the closest one here):
http://website.com/yiiapp/web
I could probably combine one of the results with some $_SERVER var… but is it a solution?
I realize this post is quite old but I want to answer it anyway.
To get a full URL to your app web folder in Yii2 you can try these three options:
Url::to('#web/', ''); returns //website.com/yiiapp/web/
Url::to('#web/', true); returns http://website.com/yiiapp/web/
Url::to('#web/', 'https'); returns https://website.com/yiiapp/web/
You can use Yii::$app->getUrlManager()->createAbsoluteUrl() method or yii\helpers\Url::toRoute() to generate absolute urls. yii\helpers\Url::to() also can be used look at the documentation. E.g. <?=Url::to(['site/index'], true);?> should output http://website.com/yiiapp/web/site/index. If you need to get root url to your app, try \yii\helpers\Url::to('/', true);
There are multiple ways to achieve this, but probably the most clean way to get base URL of your app is to use Url::base():
Url::base(true);
Most of methods in Url helper allows to you specify $scheme argument - you should use it if you want to create absolute URL (with domain).
The URI scheme to use in the returned base URL:
false (default): returning the base URL without host info.
true: returning an absolute base URL whose scheme is the same as that in yii\web\UrlManager::$hostInfo.
string: returning an absolute base URL with the specified scheme (either http, https or empty string for protocol-relative URL).

What's wrong with this include statement?

This function is returning the content of the file rather the result of fetch_link_settings_overide() within it.
The issue is not with the overide function as after the initial error I commented out my modification just to be sure it wasn't something I had done there.
function fetch_link_settings(){
include( plugins_url()."/plugin-child/plugin_overrides.php");
return fetch_link_settings_override();
}
Adding the content of the derived function plugin-child/plugin_overrides.php as we are not getting anywhere currently.
function fetch_link_settings_override(){
global $post;
// If the destination url is set by the user, use that. Otherwise, use the permalink
$destination_url = get_post_meta($post->ID, '_promo_slider_url', true);
// ASAdd additional place to look in the case of the post being via the PODS advert track
if( ! $destination_url )
$destination_url = get_post_meta($post->ID, 'okd_advert_link', true);
if( ! $destination_url )
$destination_url = get_permalink($post->ID);
// If the target attribute is set by the user, use that. Otherwise, set it to _self
$target = get_post_meta($post->ID, '_promo_slider_target', true);
if( ! $target ) $target = '_self';
// Setup the disable links variable
$disable_links = get_post_meta($post->ID, '_promo_slider_disable_links', true);
return compact('destination_url', 'target', 'disable_links');
}
You write this:
include( plugins_url()."/plugin-child/plugin_overides.php");
Why is plugins_url() there? The include function is strictly based on the file system:
The `include` statement includes and evaluates the specified file.
As explained in the WordPress docs, the plugins_url() would give you the full web URL which is 100% different than the file system WordPress is installed on:
Retrieves the absolute URL to the plugins directory (without the
trailing slash) or, when using the $path argument, to a specific file
under that directory.
So perhaps it should be like this:
include("/plugin-child/plugin_overides.php");
Or perhaps you need the plugin_dir_path()?
include(plugin_dir_path( __FILE__ ) . "/plugin-child/plugin_overides.php");
But that seems wrong. Where would /plugin-child/plugin_overides.php? Try doing this:
include("/full/path/to/wordpress/and/this/plugin-child/plugin_overides.php");
Just replace /full/path/to/wordpress/and/this/ with the actual file system path to /plugin-child/plugin_overides.php.
EDIT: Since the original poster is persistent in using plugins_url() despite all of the suggestions otherwise, here is my detailed response:
…you said “you cannot load raw functions via a URL with include” well
this is not relevant because even if I add $some_var = 'smith'; as the
first statement in the included file, it is not visible in the
function using the include.
Apologies. Functions, classes, strings, constants… Just about anything that you want to be raw, unprocessed PHP will simply not be passed via an http:// or https:// URL because Apache will parse the PHP instructions & simply return the output of that file and not the raw, unprocessed contents of the PHP in that file.
Additionally the original poster contents the following:
You can’t help me because what you are saying does not make sense or
you are not explaining yourself adequately. Look at these examples:
include realpath(dirname(FILE) . "/" . "relative_path");
include("data://text/plain;base64,".base64_encode($content));
include("data://text/plain,".urlencode($content));
All taken from the official PHP documentation. They all use
functions returning components that are concatenated with the rest of
the url. I also tried this typing the filepath explicitly and the
result is the same.
The examples cited are as follows:
include realpath(dirname(FILE) . "/" . "relative_path");
This is a filesystem level include which is the most common way PHP files are included into other files.
include("data://text/plain;base64,".base64_encode($content));
include("data://text/plain,".urlencode($content));
These are both data URLs. Not http or https. So again when you use plugins_url() what you are getting is a full http:// or https:// URL in which Apache parses the PHP instructions & simply return the output of that file and not the raw, unprocessed contents of the PHP in that file. Or as very clearly explained in the PHP documentation you are linking to; emphasis mine:
If "URL include wrappers" are enabled in PHP, you can specify the file
to be included using a URL (via HTTP or other supported wrapper - see
Supported Protocols and Wrappers for a list of protocols) instead of a
local pathname. If the target server interprets the target file as PHP
code, variables may be passed to the included file using a URL request
string as used with HTTP GET. This is not strictly speaking the same
thing as including the file and having it inherit the parent file's
variable scope; the script is actually being run on the remote server
and the result is then being included into the local script.
Going back to your example, you say now the contents of plugin_overides.php is $some_var = 'smith';. How exactly? If it is a PHP file like this:
<?php
$some_var = 'smith';
?>
When you call that file via a URL generated by the following code:
include(plugins_url() . "/plugin-child/plugin_overrides.php");
Assuming your website is http://some.cool.website/ the you are basically making a call like this:
http://some.cool.website/plugin-child/plugin_overides.php
So the output of plugin_overides.php would be 100% blank. If you wanted to get output of that file, you could do the following:
<?php
$some_var = 'smith';
echo $some_var;
?>
And that would return smith. Meaning the absolute ONLY output you would get from that call is pure text. Nothing else.
Now I see you actually have posted the contents of plugin_overides.php. My example explanation above is still apt, but still a basic question. This is your function; just the interface & return for example:
function fetch_link_settings_override(){
// Other code removed. Just a structural illustration for now.
return compact('destination_url', 'target', 'disable_links');
}
Do you actually call fetch_link_settings_override() in plugin_overides.php when it runs? Well, if that function does not run, then there is 100% no way you will ever get any output. But assuming good faith, look at your return statement here:
return compact('destination_url', 'target', 'disable_links');
If you are returning compact, then you are returning an array. You cannot simply return a bare array as a URL call like this http://some.cool.website/plugin-child/plugin_overides.php. The output at most would be simply the word Array.
If the goal is to take that array & do something, then you should use json_encode in fetch_link_settings_override and then use json_decode on the receiving side of that. So the return statement would be something like this:
return json_encode(compact('destination_url', 'target', 'disable_links'));

Using URL as a condition on php

I want to show on my site an element depending on my site's url.
Currently i have the following code:
<?php
if(URL matches)
{
echo $something;
}
else
{
echo $otherthing;
}
?>
I wanted to know how do I get the URL on the if condition, because I need to have only one php archive to show on many diferent pages
EDIT: The solution provided by Rixhers Ajazi doesnt work for me, when i use ur code i get the same URI for both of my pages, so the if sentence always goes by the else side, is any way to get the exact string u can see on the browser to the PHP code
http://img339.imageshack.us/img339/5774/sinttulocbe.png
This is the place where it changes but, the URL i get on both sides is equal, im a little bit confused
To get the URL, use:
$url = http://$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Use following syntax with URL
http://mysite.com/index.php?var1=val&var2=val
Now you can get the values of variables in your $_GET variable and use in if condition like
if($_GET['var1'])
You can do so by using the $_SERVER method like so :
$url = $_SERVER['PHP_SELF']; or $url = $_SERVER['SERVER_NAME'];
Read up on this more here
if($url == 'WHATEVER')
{
echo $something;
}
else
{
echo $otherthing;
}
?>
You can use different variables, e.g., $_SERVER["PHP_SELF"], or $_SERVER["REQUEST_URI"]. The first one contains the path after the server name and until a possible ? in the URL (the part with the GET parameters is excluded). The second one contains also the GET parameters. You can also retrieve the hostname used to connect to the server (in case you have a virtual host situation) using $_SERVER["HTTP_HOST"]. Therefore by concatenating all these you can reconstruct the full URL (if you really need it, maybe the script name is enough).

parsing an url for crawler

i am writting an small crawler that extract some 5 to 10 sites while getting the links i am getting some urls like this
../tets/index.html
if it is /test/index.html we can add with base url http://www.example.com/test/index.html
what can i do for this kind of urls.
Url like these are relative urls . ".." means "parent directory", whereas "." simply means "this directory", as in bash.
For instance, if you are looking at this page : http://www.someserver/test/foo/bar.html , and there is an url like this in it : "../baz/foobar.html", it will in fact point to http://www.someserver/test/baz/foobar.html I think. Just test.
Use dirname() to get base directoy, remove the .. using substr() and append it there. Like this:
<?php
$url = "../tets/index.html";
$currentURL = "http://example.com/somedir/anotherdir";
echo dirname($currentURL).substr($url, 2);
?>
This outputs:
http://example.com/somedir/tets/index.html
Take a look into this URL Normalization Wikipedia page.

Categories