Better way to do this in PHP - php

I currently have my htaccess file set to remove the file type so
www.example.com/home.php
would become,
www.example.com/home
I need to compare the url with one that I have saved in the database, I do this by,
if ($_SERVER['QUERY_STRING']) {
$pageURL = str_replace('.php', '?', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . $_SERVER['QUERY_STRING']);
}
else {
$pageURL = substr('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'], 0, -4);
}
When I save the url in the database it gets saved as the current page url after the htaccess file has removed the .php, it is inserted using jquery ajax.
When I come to compare it, I need this to make it match in php as php doesn't take into account the htaccess changes.
Is there a better way to do this?

You can do:
$pageURL = rtrim($_SERVER['REQUEST_URI'], '.php');
This would give your url with .php removed whenever it appears at the end of the url.

Look into the parse_url() function. You can use it to parse the URL into parts then modify the path component (e.g. remove .php). Then you can rebuild the URL from those parts using the http_build_url() function.

Seems to me that combining John's suggestion above of using parse_url() along with using pathinfo() would be best -- trimming, truncation with substr, etc. isn't always as elegant as pathinfo().

Related

php get URL of current file directory

Might be an easy question for you, but I'm breaking my head over this one.
I have a php file that needs to know it's current directory url to be able to link to something relative to itself.
For example, currently I know to get the current directory path instead of the url. When I use this I get the path:
realpath(__DIR__)
result:
/Applications/MAMP/htdocs/mysite/dir1/dir2/dir3
But this would be my desired result:
http://localhost:8888/dir1/dir2/dir3
Note that this is not the location of the current page. The page calls a file from "http://localhost:8888/dir1/dir2/dir3/myfile.php"
And "myfile.php" has the script from above.
-- edit to elaborate more details --
Thanks for your answers. But I get that I need to add more detail.
http://localhost:8888/index.php calls: "http://localhost:8888/dir1/dir2/dir3/myfile.php"
"myfile.php" needs to know it's place in the universe :) "Where am I"
"myfile.php" should know it's url location is "http://localhost:8888/dir1/dir2/dir3/"
Use echo $_SERVER['PHP_SELF'];
For example if the URL is http://localhost/~andy/test.php
The output would be:
/~andy/test.php
That's enough to generate a relative URL.
If you want the directory your current script is running in - without the filename - use:
echo dirname($_SERVER['PHP_SELF']);
In the case above that will give you /~andy (without test.php at the end). See http://php.net/manual/en/function.dirname.php
Please note that echo getcwd(); is not what you want, based on your question. That gives you the location on the filesystem/server (not the URL) that your script is running from. The directory the script is located in on the servers filesystem, and the URL, are 2 completely different things.
There is also a function to parse URL's built in to PHP: http://php.net/manual/en/function.parse-url.php
If your URL is like this: https://localhost.com/this/is/a/url
$_SERVER['DOCUMENT_ROOT'] - gives system path [/var/www/html/this/is/a/url]
$_SERVER['PHP_SELF'] - gives the route of the current file (after the domain name) [/this/is/a/url]
$_SERVER['SERVER_NAME'] - gives the domain name [localhost.com]
$_SERVER['HTTP_REFERER'] - gives the correct HTTP(S) protocol and domain name. [https://localhost.com]
If you would like to get the full url, you can do something like:
echo $_SERVER['HTTP_REFERER'] . $_SERVER['PHP_SELF'];
However, I do believe in this case, that all you need is the relative path.. and in that case you should only need to use $_SERVER['PHP_SELF'];
I've found a solution here:
https://stackoverflow.com/a/1240574/7295693
This is the code I'll now be useing:
function get_current_file_url($Protocol='http://') {
return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(__DIR__));
}
Based on your question, I believe this will get you what your want:
$_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], "/"));
Reference:
$_SERVER['HTTP_HOST'] - In your case this would return: http://localhost:8888
$_SERVER['REQUEST_URI'] - In your case this would return: /dir1/dir2/dir3/myfile.php
With the added substr() and strrpos() methods, you can strip the _myfile.php` off of the end to get the desired result:
http://localhost:8888/dir1/dir2/dir3

The $_GET at # (example.com/#dfsqf) [duplicate]

Is there a way to get the entire URL used to request the current page, including the anchor (the text after the # - I may be using the wrong word), in included pages?
i.e. page foo.php is included in bar.php. If I use your solution in foo.php, I need it to say bar.php?blarg=a#example.
No, I am afraid not, since the hash (the string including the #) never gets passed to the server, it is solely a behavioural property of the browser. The $_SERVER['REQUEST_URI'] variable will contain the rest however.
If you really need to know what the hash is, you will have to use the document.location.hash JavaScript property, which contains the contents of the hash (you could then insert it in a form, or send it to the server with an ajax request).
// find out the domain:
$domain = $_SERVER['HTTP_HOST'];
// find out the path to the current file:
$path = $_SERVER['SCRIPT_NAME'];
// find out the QueryString:
$queryString = $_SERVER['QUERY_STRING'];
// put it all together:
$url = "http://" . $domain . $path . "?" . $queryString;
echo $url;
// An alternative way is to use REQUEST_URI instead of both
// SCRIPT_NAME and QUERY_STRING, if you don't need them seperate:
$url = "http://" . $domain . $_SERVER['REQUEST_URI'];
echo $url;
You can't - you'll have to write the value of the hash to a cookie via Javascript to send it to the server on the subsequent request.
You can pass up the full URL, including the anchor (the part after the #), using a Javascript onload function that sends that URL to an Ajax endpoint.
This example show's full URL request with port or https
function curPageURL() {
$pageURL = 'http';
if(isset($_SERVER["HTTPS"]))
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
usage : echo curPageURL();
It is true that you can't pass hash data to server. but sometimes what you want is get some url with '#blablabla' from the server, like when you share link to someone with '#', but the site need to login. below is another way to think, maybe not vary detailed.
First, sometimes you want to share your link with '#',like:
www.so.com#lala
First, you can change your url use javascript and pass some data with '?' and '#' at the same time, like:
www.so.com?foo=lala&&flag=hash#lala
then, as the '#' nerver pass to the server, but you can get the data from $_GET[''],like:
if($_GET['flag'] === 'hash'){
// base url
$_SESSION['url'] = strtok('http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"],"?");
// hash data
$_SESSION['hash'] = $_GET['foo'];
}
then, you can do everything with the '#' data, if you want to pass it to client, you can:
$url = $_SESSION['url']."#".$_SESSION['hash'];
header("Location:".$url);
At last, the url is back
Syntax Error is right.
And what I'd like to do is intercept the #foo from the call dosomething.org/page.php#foo and act as if I'd found a dosomething.org/page.php?x=foo call. Yes, this may function on the client but it's theoretically available at the server.
Why do I want this? Because people have old links stashed in their emails and I want to handle them differently.
You can pass the anchor using rawurlencode funcion.
Basically you just need to do something like this:
bar.php?blarg=a<?php echo rawurlencode('#blahblahblah')?>

php url redirect to home page

Well, I don't know if I made a title properly but I've got a lil php script out there and I am wondering if there might be possibility when user go to this url:
siteurl.com/index.php?token=J55OSGTTk3W7mRcuq54006w7ROv
to get automatically only /index.php without the content that he copy/pasted in this case
?token=J55OSGTTk3W7mRcuq54006w7ROv
Hope it is possible. Cheers.
Yes. Issue a Location header and use parse_url() to get the parts you need.
$url = "http://siteurl.com/index.php?token=J55OSGTTk3W7mRcuq54006w7ROv";
$parsed = parse_url($url);
$redirect = $parsed["scheme"] . "://" . $parsed["host"] . $parsed["path"];
header("Location: $redirect");
Maybe explode($url,"?")[0]. If there's no question mark, then it should return an array of length one. If there is, you'll only get everything before the '?'.

Doing a URL re-write while using PHP GET method

When I click on a comment section for a given entry on a site I have, the URL looks like this:
http://www...com/.../comments/index.php?submission=Portugal%20Crushes%20North%20Korea&submissionid=62&url=nytimes.com/2010/06/22/sports/soccer/22portugalgame.html?hpw&countcomments=3&submittor=johnjohn12&submissiondate=2010-06-21%2019:00:07&dispurl=nytimes.com
I want to make it look like this URL:
http://www...com/.../comments/Portugal-Crushes-North-Korea-62
I understand that this involves adding rules to the .htaccess file. I have two questions:
Since I am using the GET method in PHP, the ugly URL has a bunch of variables appended to it. I don't want all of these variables to appear in the clean URL. Is it possible to only include a few of the variables in the clean URL but still have a rule directing it to an ugly URL with all of the variables?
Once I have the .htaccess rules written, do I go back and change the links in the source code to direct to the clean URLs? If so, how do I do this using the GET method when the clean URL does not have all of the variables that I want to pass along?
Thanks in advance,
John
I'm not sure why you need all that data in the URL. You should be storing things like the submission title, its date and author in a database and then refer to it with an ID. That way, your URLs will be shorter and prettier:
http://www.example.org/article.php?id=1
http://www.example.org/article/1/
You can accomplish this with a simple RewriteRule in your .htaccess file, like so:
RewriteEngine On
RewriteRule ^articles/([0-9]+)/ article.php?id=$1
No, you can not leave variables out and expect them to be passed anyway. If you do this, the information is no longer in the URL, so you don't have a way to get it.
You can use post instead of get if you want to pass variables without them showing up in the URL.
I join the word of Sjoerd, but there are a lot of ways how you can rewrite your url like you want to!
Apache and (IIS too) supports url-s like this one: http://example.com/index.php/my-rewritten-url_62
function URISegment($segment)
{
$uri_array = explode('/',$_SERVER['REQUEST_URI']);
$uri_count = count($uri_array);
$returning_uri = array();
for($i = 0;$i<$uri_count;$i++)
{
if(empty($uri_array[$i]) || $uri_array[$i] == "index.php")
unset($uri_array[$i]);
else
array_push($returning_uri,$uri_array[$i]);
}
if($segment < count($returning_uri))
return $returning_uri[$segment];
else
return false;
}
This works, but you need to define the base url too, and this needs to be called at the beginning of the file, and implemented at every image, script, etc. call.
function BaseURL()
{
if(isset($_SERVER['HTTP_HOST']))
{
$base = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
$base .= '://'. $_SERVER['HTTP_HOST'];
$base .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
}
else
{
$base = 'http://localhost/';
}
return $base;
}
After this you can use instead of this:
// http://example.com/?MyKey=Some-data
$MyKey = $_GET['MyKey']; //which is the first item
echo $MyKey;
// results: Some-data
This:
// http://example.com/?MyKey=Some-data
$MyKey = URISegment(0);
echo $MyKey;
// results: Some-data
You've got the same result by each one.
PS:
I like this solution because I can mix url types as I need them like:
example.com/index.php/index/evaled-article?some=db-stored&code=snipplet
And of course you can rewrite your url like FRKT said :)
And of course, if you want to hide the index.php you need to use mod_rewrite, because there's no way

Converting a filepath to a url securely and reliably

I'm using php and I have the following code to convert an absolute path to a url.
function make_url($path, $secure = false){
return (!$secure ? 'http://' : 'https://').str_replace($_SERVER['DOCUMENT_ROOT'], $_SERVER['HTTP_HOST'], $path);
}
My question is basically, is there a better way to do this in terms of security / reliability that is portable between locations and servers?
The HTTP_HOST variable is not a reliable or secure value as it is also being sent by the client. So be sure to validate its value before using it.
I don't think security is going to be effected, simply because this is a url, being printed to a browser... the worst that can happen is exposing the full directory path to the file, and potentially creating a broken link.
As a little side note, if this is being printed in a HTML document, I presume you are passing the output though something like htmlentities... just in-case the input $path contains something like a [script] tag (XSS).
To make this a little more reliable though, I wouldn't recommend matching on 'DOCUMENT_ROOT', as sometimes its either not set, or won't match (e.g. when Apache rewrite rules start getting in the way).
If I was to re-write it, I would simply ensure that 'HTTP_HOST' is always printed...
function make_url($path, $secure = false){
return (!$secure ? 'http://' : 'https://').$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $path);
}
... and if possible, update the calling code so that it just passes the path, so I don't need to even consider removing the 'DOCUMENT_ROOT' (i.e. what happens if the path does not match the 'DOCUMENT_ROOT')...
function make_url($path, $secure = false){
return (!$secure ? 'http://' : 'https://').$_SERVER['HTTP_HOST'].$path;
}
Which does leave the question... why have this function?
On my websites, I simply have a variable defined at the beggining of script execution which sets:
$GLOBALS['webDomain'] = 'http://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
$GLOBALS['webDomainSSL'] = $GLOBALS['webDomain'];
Where I use GLOBALS so it can be accessed anywhere (e.g. in functions)... but you may also want to consider making a constant (define), if you know this value won't change (I sometimes change these values later in a site wide configuration file, for example, if I have an HTTPS/SSL certificate for the website).
I think this is the wrong approach.
URLs in a HTML support relative locations. That is, you can do link to refer to a page that has the same path in its URL as the corrent page. You can also do link to provide a full path to the same website. These two tricks mean your website code doesn't really need to know where it is to provide working URLs.
That said, you might need some tricks so you can have one website on http://www.example.com/dev/site.php and another on http://www.example.com/testing/site.php. You'll need some code to figure out which directory prefix is being used, but you can use a configuration value to do that. By which I mean a value that belongs to that (sub-)site's configuration, not the version-controlled code!

Categories