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.
}
?>
Related
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).
Im currently trying to get a link:
<a href='?p=bid?Sale_ID=$Sale_ID'>BID</a>
to work but I keep getting a "Page you are requesting doesn´t exist" message, this page works if i use this link:
<a href='include/bid.php?Sale_ID=$Sale_ID'>BID</a>
this leads me to believe that my problem lies with the isset im using to include pages on link:
<?php
if (isset($_GET['p']) && $_GET['p'] != "") {
$p = $_GET['p'];
if (file_exists('include/'.$p.'.php')) {
#include ('include/'.$p.'.php');
} elseif (!file_exists('include/'.$p.'.php')) {
echo 'Page you are requesting doesn´t exist<br><br>';
}
} else {
#include ('include/login-form.php');
}
?>
Ive tried adding another isset replacing p with q which just throws my pages in to dissaray.
So my question is, is there a way around this?
Thanks
You have two question marks here:
?p=bid?Sale_ID=$Sale_ID
Multiple querystring parameters are separated by ampersand:
?p=bid&Sale_ID=$Sale_ID
The query string you show: ?p=bid?Sale_ID=$Sale_ID is not valid. The structure of a URL with a string is:
filename.extension?first_parameter=first_value&second_parameter=second_value
So, if you want p to indicate which page:
?p=bid&Sale_ID=$Sale_ID
.. use the ampersand (&) to separate your query string values.
Also, please note that the approach you are using to include a file is insecure. What if I sent this:
?p=../../.htpasswd&Sale_ID=0
An attacker could use this method to output the contents of files that you do not wish to expose to the public. Make sure you are checking the value of this variable more carefully before blinding including the file.
I also wants to warn you against using the error suppressor (#). Errors are your friends! You want to know exactly what happens in your code, using the error suppressor prevents critical problems from being brought to your attention. Really -- never, ever use the error suppressor. Instead of #include, use include
I suggest something more like this:
$file_exists = false;
$page = false;
if (
isset($_GET['p']) &&
strlen(trim($_GET['p'])) > 0
){
$page = preg_replace("/[^a-zA-Z0-9 ]/", "", $_GET['p']);
$page = str_replace(" ", "-", $page);
$file_exists = file_exists('include/'.$page.'.php');
if ($file_exists) {
include ('include/'.$page.'.php');
} else {
$page = false;
echo 'Page you are requesting doesn´t exist<br><br>';
}
}
if (!$file_exists ||$page === false)
include ('include/login-form.php');
The first part of the code ensures that the query string value exists and has some content. Then it cleans out any non-alphanumeric characters (this helps prevent exploitation). Then, we check to see if it exists, storing that result in a variable so we can use it again.
If the page exists, the file is included. If not, a "page not found" message is output, and the login form file is included. If no page is specified in the query string, the login form file is included.
Documentation
$_GET - http://php.net/manual/en/reserved.variables.get.php
Query string on Wikipedia - http://en.wikipedia.org/wiki/Query_string
Exploiting PHP File Inclusion - an article about security when using include and $_GET - http://websec.wordpress.com/2010/02/22/exploiting-php-file-inclusion-overview/
preg_replace - http://php.net/manual/en/function.preg-replace.php
str_replace - http://php.net/manual/en/function.str-replace.php
?p=bid "redirects" to your default file, usually index.php. You want it to work in bid.php.
You can set the default file in apache with:
DirectoryIndex index.php bid.php
The other problem is you use multiple ? signs.
?p=bid&Sale_ID=$Sale_ID would work a lot better
Keep in mind that file_exists does not use the include path, so you should be doing this:
if (file_exists( get_include_path() . 'include/'.$p.'.php')) {
More info:
http://ca2.php.net/manual/en/function.file-exists.php
How would one go about using php include() with GET paramters on the end of the included path?
IE:
include("/home/site/public_html/script.php?id=5");
How would one go about using php include() with GET paramters on the end of the included path?
You could write into $_GET:
$_GET["id"] = 5; // Don't do this at home!
include(".....");
but that feels kludgy and wrong. If at all possible, make the included file accept normal variables:
$id = 5;
include("....."); // included file handles `$id`
You don't, include loads files via the local filesystem.
If you really wanted to, you could just do this, which would have the same result.
<?php
$_GET['id'] = 5;
include "/home/site/public_html/script.php";
?>
but then you might as well just define the variable and include it
<?php
$id = 5;
include "/home/site/public_html/script.php";
?>
and reference the variable as $id inside script.php.
Well you could use:
include("http://localhost/include/that/thing.php?id=554&y=16");
But that's very seldomly useful.
It might be possible to write a stream wrapper for that, so it becomes possible for local scripts too.
include("withvars:./include/that/thing.php?id=554");
I'm not aware if such a solution exists yet.
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.
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.