Universal Navigation Bar PHP (Multiple Directories) - php

So I've been using StackOverflow for programming related topics for over 5 years and never once considered registering as 9/10 times I come on, I find what I am looking for. This time, I've trawled the internet, the suggestions from stack overflow, and I can't find the answer, so here I am.
I'm looking to #include a navigation bar to make it universally accessible no matter what page the user is on. The problem is, I have multiple directories, /login
/register
/profile
The list goes on, of course for things such as CSS files, navigation and JS files. I don't want to constantly have to define the href to be '../' or '../../' of a file. That is an insane amount of maintenance for what soon will be a vast directory of PHP files.
The problem I'm having is trying to calculate how I can detect which directory the user is in via the #include file, and if they wish to return home for example, ensuring the correct amount of change directories occur.
I hope I'm making sense here.
I believe I may require the use of $_SERVER but I'm genuinely stuck on even providing code I've attempted to work on. I'm not expecting a hand out, but more an explanation.
Thanks
This is my first attempt, it works to a degree but it's dependent on the page I originally tested the code on. The echo's is simply to see what is going on myself in the background.
This is incredibly easy to perfect using the Laravel framework but doing it normally for some reason I've struggled with it.
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'index.php';
$folder = $uri;
$folder = "/Folder1/Folder2/Folder3/Folder4/Folder5";
echo substr_count($folder, "/");
echo '<br>' . $folder . '<br>';
$EndLoop = substr_count($folder, "/");
$String = '';
for($Loop = 1; $Loop < $EndLoop; $Loop ++)
{
echo $Loop;
$String = '../' . $String;
echo '<br>';
echo $String;
}
EDIT 2:
I've just worked this which typically works.. I realized when using a
Sign Up
Was routing it to host/directory_currently_in/signup/
So what I have done is this
<?php $host = $_SERVER['HTTP_HOST'];
//further down
echo 'Sign Up';
Because the signup directory is in the root directory and the individual may be 3 directories further in than the root, I had to try find a way to root them right back up 2 or 3 folders back into the sign up directory.
Using http:// and linking to the host has done this for me. Any suggestions on improvements?

Try something along the lines of:
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/common/header.php";
include_once($path);
?>
That way you are always referring to the base and then building the folder structure from there.

Related

PHP: Get current directory index file name

I must not be phrasing this question right because I couldn't find an answer to this but surely it's been asked before. How do I get the current filename from a URL if it's the directory's index file?
I.e. This will get index.html if I'm on www.example.com/index.html
$url = basename($_SERVER['REQUEST_URI']);
But that won't work if i'm on www.example.com. The only thing I've come up with so far is something like this:
$url = basename($_SERVER['REQUEST_URI']);
if($url == "") {
$filename = "index.html";
}
But that's obviously a bad solution because I may actually be on index.htm or index.php. Is there a way to determine this accurately?
$_SERVER['SCRIPT_FILENAME'] will determine the full path of the currently executing PHP file. And $_SERVER['SCRIPT_NAME'] returns just the file name.
This is one of the other methods.
$url = basename($_SERVER['REQUEST_URI']);
$urlArray = explode("/",$url));
$urlArray = array_reverse($urlArray);
echo $urlArray[0];
Unfortunately, the $_SERVER array entries may not always be available by your server. Some may be omitted, some not. With a little testing though, you can easily find out what your server will output for these entries. On my servers (usually Apache) I find that $_SERVER['DOCUMENT_ROOT'] usually gets me the base of the URI I'm after. This also works well for me in the production environment I work on (XAMPP). As my URI will have a localhost root. I have seen people encourage DOCUMENT_ROOT before in this situation. You can read all about the $_SERVER array here.
In this example, I get the following results:
echo $_SERVER['DOCUMENT_ROOT'] ; // outputs http://example.com
If you are working in a production environment this is very helpful because you won't have to modify your URL's when you go live:
echo $_SERVER['DOCUMENT_ROOT'] ; // outputs C:/xampp/htdocs/example
'DOCUMENT_ROOT' The document root directory under which the current
script is executing, as defined in the server's configuration file.
You could find the last occurrence of the slash / using strrchr() and simply extract the rest using substr(). The optional parameter in substr() tells where to begin. With one we skip the slash /. If you want to keep it, just set the parameter to 0.
echo substr( strrchr( "http://example.com/index.html" , "/" ) , 1 ) ; // outputs index.html
EDIT: Considering that not every server will provide $_SERVER with entities, my approach might be more reliable. That is, if the URL you pass to strrchr() is reliable. In either case, make sure you test the different outputs from $_SERVER, or your paths you provide.

PHP path starting /

In HTML you can set your href to "/folder/page" and the starting / would go to the root-directory of your web application (meaning it would start at www.yoursite.com) and move on from there.
Now, in PHP, can i do this? I am having a problem, since i have a file, that ALWAYS needs to start at the root, and then go a folder down. I can't use relative paths, since it will be included in other pages and of thus, i wouldn't know how many layers to go up before i was in the root directory.
I tried using "$_SESSION['DOCUMENT_ROOT']" but that gives me an address too far up the directory tree. For example (on a test site) i have this URL:
http://localhost:8888/kasseNet-BitBucet/
And i want THAT to be my root. Currently it's something like "Applications/Mamp/htdocs".
How can i achieve this? Obviously i could use an absolute path for this, but then it wouldn't be easy for me to launch it, since i would have to change it to not be on a localhost environment.
I have been googling my ass off, but i can't seem to find the right fit. It should be an easy task to accomplish.
For completeness sake, here is my structure:
(assuming we are in "root" - the localhost htdocs/site folder)
- Login
*Authenticate.php
*login.php
- Other
*test.php
- default.php
Now, both "default.php" and "test.php" will include the authenticate.php. The authenticate.php will redirect to the login.php. Now, the problem is that if i include it in the default.php, my path in the Authenticate.php file to the login.php would be "Login/Authenticate.php". BUT, if i include it in the test.php, i would have to do "../Login/Authenticate.php". This illustrates the problem, and it only gets worse as the structure grows.
As you can imagine, it is for a login script where i include the authenticate file, that will redirect to the login page if the user is not logged in. All the examples i've found though, just uses a flat structure with no extra directories, so they don't have that problem.
Hoping for some help, been stuck for days thinking of a solution xD
Thank you in advance.
Best Regards
/JBJ
Use this to get the root URL and append whatever you want after it.
$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
If your path is something like http://localhost:8888/kasseNet-BitBucet/path1/path2/index.php you have to define kasseNet-BitBucet as your root directory. PHP cannot undrestand that kasseNet-BitBucet is your root directory and path1 for example is not.
So:
$my_root_dir = 'kasseNet-BitBucet';
$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/' . $my_root_dir;

Wildcard Subdomain with .htaccess and php

Spent the better part of a day trying to get my head around this and finally need to ask for some help.
I have a bunch of folders which i want to make into subdomains. I have followed the tutorial below and have set up a wildcard redirect in my DNS in step 1 and edited my virualhost in step2. This seems to have gone to plan.
However i am unsure of the logic behind step 3. How does the code below allow me to display content from a folder in a subdomain? i cant figure out what logic i am supposed to try and code - i think i am clearly missing something obvious here.
$serverhost = explode('.',$_SERVER["HTTP_HOST"]);
$sub = $serverhost[0];
if ($sub = "www") {
$sub = "";
}
(text from tutorial)
OK, here's what's taking place. You insert this code in your main php
file and what it does is check to see if the subdomain portion of the
domain (ie: thishere.yourdomain.com) is www. If so, it just nulls
$sub, otherwise, $sub will contain your subdomain keyword. Now, you
can check if ($sub > "") and take appropriate action with your code if
a subdomain exists, to display a page based on that value.
(tutorial link)
http://www.wiredstudios.com/php-programming/setting-up-wildcard-dns-for-subdomains-on-cpanel.html
Thanks in advance.
mmhh well, in fact, this code only permit you to get what subdomain is called.
So if you want to display the content of the folder corresponding to your subdomain, you have to scan your directory, then check if the folder called by subdomain exists, and then include script from this folder.
A simple way to do it is :
$scan = scandir('.'); // scan the current directory
if( in_array($sub, $scan) && is_dir($sub) ){
require( $sub.'/yourscript.php');
}
But this mean that your whole appication is designed in function of the $sub value, each include, each file prefixing etc ...

Drupal - get user id in non-drupal script

im making an applicaiton (PHP), which will run on same server and same website as a Drupal installation. The think im trying to do is to get user id of user, who is currently logged in at Drupal (i never worked with Drupal before). I want just that id.
Does anyone know, where can i find that id (is it somewhere in the $_SESSION variable?)
Im using Drupal 6, PHP 5.3.
Update :
Sorry, I thought I understood what you wanted, but after re-reading your subject line, I'm thinking you want something a little different. Are you wanting to make a php script like test.php in the Drupal folder and access the Drupal user ID (based on cookie/session/etc)? In order to do that, you'll need to "bootstrap" Drupal first. Here is a function I've created to bootstrap Drupal (7) for maintenance scripts I create.
There may be a "better" way to do it, but it's what works for me.
function bootstrapDrupal($cDomain)
{
$cDir = getcwd();
//SETS DRUPAL BASE DIR
define('DRUPAL_ROOT', '/www/dev');
//DRUPAL FAILS TO LOAD SOME FILES IF NOT AT BASE
chdir(DRUPAL_ROOT);
//ATTEMPT TO DECIDE IF PHP IS RUNNING VIA CMDLINE
if (isset($GLOBALS['PHP_SELF']))
{
//WHATEVER SITE YOUR SCRIPT IS FOR. HELPS SET DB.
$_SERVER['HTTP_HOST'] = $cDomain;
//SCRIPT ADDITIONALLY NEEDS TO BE SET FOR THE REDIRECT
$_SERVER['SCRIPT_NAME'] = $GLOBALS['PHP_SELF'];
//FORWARD SLASH IS IMPORTANT
if (substr($_SERVER['SCRIPT_NAME'], 0, 1) != '/')
{
$_SERVER['SCRIPT_NAME'] = '/' . $_SERVER['SCRIPT_NAME'];
}
//NEEDED TO SUPRESS BOOTSTAP ACCESS ERRORS - ANY IP WILL WORK
$_SERVER['REMOTE_ADDR'] = '192.168.0.1';
}
//LOADS DRUPAL BOOTSTRAP CODE
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
//EXECUTES BOOTSTRAP
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
//LOADS DRUPAL COMMON FUNCTIONS
require_once DRUPAL_ROOT . '/includes/common.inc';
//BACK TO STARTING DIRECTORY
chdir($cDir);
}
Original Answer :
In Drupal you can access the User ID via :
$GLOBALS['user']->uid
or
global $user;
$user->uid

Include safety

<?php
if (preg_match('/^[a-z0-9]+$/', $_GET['page'])) {
$page = realpath('includes/'.$_GET['page'].'.php');
$tpl = realpath('templates/'.$_GET['page'].'.html');
if ($page && $tpl) {
include $page;
include $tpl;
} else {
// log error!
}
} else {
// log error!
}
?>
How safe would you say this is?
Gumbo here on Stack Overflow wrote it.
Dynamic Include Safety
I wanna hear your opinions.
cheers
My first thought isn't about safety, but about why in the world would you do that?
I'd say it's pretty safe. Just don't allow anything to write to those folders. PHP files are traditionally inside the web root of a server which is dangerous to start with. It would be better to place the files being loaded to an area that's absolutely inaccessible to the outside given a configuration error or a .htaccess file going missing.
you including your own code. how safe is it?
I could see some potential issues there, especially if the 'page' variable contained '..' or other such things that could allow them to see something they weren't supposed to be able to see.
I do something similar on a few sites of mine, but I would first check 'page' to make sure it references one of a set of allowed pages.

Categories