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
Related
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.
I need to catch the loginsession from a joomla webpage and call that from a website a wrote which lies on a different server.
This is what i tried:
if (!defined('_JEXEC'))
{
define( '_JEXEC', 1 );
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
}
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
$app = JFactory::getApplication('site');
$user = JFactory::getUser();
$groups = $user->groups;
if($user->id)
{
if (isset($groups[7]) or isset($groups[8]))
{
echo $user->username;
}
else
{
echo 'false';
}
}
else
{
echo 'false';
}
I uploaded this into the root folder of the joomla site. If I call it via browser it works perfectly. It returns the username when i'm logged in and returns false when i'm logged out.
If I call it from the php Page it returns false
$siteText= file_get_contents ("http://examplejoomlasite.org/miniphpscript.php");
Is there any other chance to catch the joomla loginsession on another page?
The problem is that your call is a server request. Means it looks like for the miniphpscript if you would open a browser on your server it doesn't know anything about browser session on your local computer.
You should use a better HTTP library like Guzzle http://guzzlephp.org, which comes with cookie support. You have then to log in trough Guzzle first and save the cookie as file. On all your subsequent requests to the miniphpscript you need to use that cookie then.
After going through your question again and again I concluded that you need user integration on both the servers. that means you can know the user data in another server.
Go for jfusion to have common user in both the websites; provided both are php based. Link to JFusion is http://www.jfusion.org/feature/what-is-jfusion . If your system is based on any of the listed frameworks like dokuwiki, phpbb3 forum, kayako support OR joomla itself, then you can easily integrate it. Also if you have any other framework with which you want user integration then you can create a jfusion plugin. Jfusion works seamlessly with the frameworks i stated above.
You can check their documentation to create your custom JFusion Plugin http://www.jfusion.org/docs/doku.php?id=dev;intro
An easy way to do this is to develop a small webservice on your server that will just update a table in your database with authentications on the Joomla website.
Then, you will need to develop a small Joomla plugin which is triggered on authentication that will call the webservice and update it the login information.
I have no idea if I worded that question correctly, but I worded it very carefully. So, basically here's the thing. I have two directories on my local machine.
/server/core/
and
/server/clients/
The "core" is what handles all of the data processing, this is done so that if I ever need to update my application then I will just have to update the "core" and all of the "clients" that include and call functions that are located in the "core" will be updated automatically. I believe the term for this is a "Dynamic website".
So, basically here's the thing.. I'm using very basic sessions for the time being just to start learning, but I will definately change things around once I'm at a more advanced level. Currently on my "core" i have the following code located in login.php
if(canLogin) {
if(!isset($_SESSION)){session_start();};
$_SESSION['email'] = $email;
header('Location: index.php');
}
Which will load the 'index.php' which is located on the "client" directory. Here's how I have this done.
The following code is located in /server/core/
function createIndex($SQLConnection, $SQLConfig, $PDOConnection) {
global $action;
global $days;
if(!isset($_SESSION)){session_start();}
if(empty($_SESSION['email']))
{
createLogin($PDOConnection, $SQLConfig);
}
}
The following code is located in /server/clients/
<?php
$Configuration = include_once 'inc/Configuration.php';
include_once 'inc/Connection.php';
include_once '/opt/lampp/htdocs/eDashboard2/core/index.php';
createIndex($NormalConnection, $Configuration, $PDOConnection);
?>
Which generates the Index.php file on the core and relays the website back using echos. Please ignore the multiple SQL Connections as it was for testing and will be removed.
So basically, what the problem is, is that the session isn't being saved, or... rather, if I had to guess the session is being stored on /server/core/ and not on /server/clients/
The end-result is that the user is always asked to log in, instead of being able to continue onto the website like they can in the "Client-Only" version of this. (( The client only version was just a static website like you would normally see, the dynamic approach is something I took upon myself to attempt to learn just for the experience ))
How can I make this so the session will be stored for the person logging in.
Use session_set_cookie_params to set the directory to the parent directory:
<?php
$params = session_get_cookie_params();
session_set_cookie_params($params['lifetime'], '/server');
If the sessions also have to exist between subdomains of your domain, you need an additional parameter:
session_set_cookie_params($params['lifetime'], '/server', '.website.com');
I have a question about "link control system" in PHP. The idea is to make script that could make different links than original - something like friendly links with .htaccess. In .htaccess make rule to redirect all traffic to script file - for example linkprocessor.php then in this file should be some conditions, mysql connect and pattern grabber from database(friendlyurl and originalurl columns). So if we write full address - example.com/defined-address it will redirect us(but not change address) to linkprocessor.php and then script is checking if /defined-address is in database, if is it will include certain(based on friendlyurl) originalurl file. Is that script would be optimal? That script could prevent from "hackers".
Example:
example.com/defined-address -> linkprocessor.php -> SELECT originalurl from table WHERE friendlyurl = /defined-address -> include originalurl
=> can be written incoherently but its hard to explain that precisely
What you are asking about here is the Front Controller pattern http://en.wikipedia.org/wiki/Front_controller.
There are various ways to implement it, using a sql database to map URI strings to files to include is a valid way to do it, but might be overkill. The same information could probably be hard coded in a php array.
The standard way to prevent hackers is to only allow whitelisted files to be included. In your case you are using an explicit map to determine which page to include, so it is not an issue.
Some code to get you started:
<?php
$map = array('/home' => 'included_1', '/details' => 'included_2' ... )
if (array_key_exists($_SERVER['REQUEST_URI'], $map)) {
include $map[$_SERVER['REQUEST_URI']]
}
else {
// Send a 404 response
}
What you're looking for is the Front End Controller design pattern.
You described the basic method for solving this, which is to redirect all incoming requests (minus requests for static content such as images, CSS files and JS files) to a single file. Generally this file is the index.php file in the site's root directory, but can be any file.
You can accomplish this redirection using .htaccess on Apache servers or web.config on IIS servers. For .htaccess you can google mod_rewrite and get a load of information that will help you along.
Once you have all of the requests being directed to your Front End Controller, you need to determine what the request is asking for. You can inspect PHP's $_SERVER['REQUEST_URI'] to see what the request is, and handle it accordingly.
The most extensible solutions to this problem that I've seen rely on controllers (classes) being in a specific location and 'static' files being in a separate location. Doing something like the following would make it trivially easy to extend the requests that your site will respond to:
/**
I am assuming at this point that the variable $request is an array
representing the current request. For example, if the request is for:
http://www.example.com/dir/page, $request will contain two entries,
'dir' and 'page'
**/
if(file_exists('/controllers/' . $request[0] . '.php')) {
require_once '/controllers/' . $request[0] . '.php';
$controller = new $request[0]();
$controller->dispatch($request);
} else if(file_exists( '/static/'.$request[0] . '.php')) {
require_once '/static/' . $request[0] . '.php';
} else
throw new Exception('404', 404);
The above is more pseudo-code than actual code, I won't guarantee that it will actually run but the idea is there.
To add another controller to your system, you would simply write a class, make sure that it has a dispatch method, and put it in the proper location.
I have a form in a template which is posted to a PHP script. This script sets some variables in the $_SESSION array, then redirects back to the same page using the standard:
header("Location: index.php?page=enquiry-form");
The problem is that whenever the page loads after refirection, the session only contains the following three variables:
cmsuserkey
cms_admin_user_id
cms_admin_username
...all of mine have disappeared.
I'm calling session_start(); in my php script
I've set the config option: $config['use_smarty_php_tags'] = true;
The user doesn't need to be logged in to use the form (in fact the site doesn't use logins at all).
Can anyone suggest anything I'm not doing/doing wrong?
Thanks,
Rich
I had the same problem once and fixed it by addin exit() after the redirection to save the session:
header("Location: index.php?page=enquiry-form");
exit();
I've had a similar problem (though I wanted to use data from the CMS Made Simple session in another php-file). For me the cause was the following (as stated in my comment on the question):
CMS Made Simple (CMS from now on) does makes its own session name. This means that when you run session_start() in a separate php-file, it will not have the same session name. Therefore, the php-file won't be able to access CMS's session data, and CMS won't be able to access the php-file's session data.
The solution logically follows from the cause, you need them both to use the same session name.
CMS sets its session name in include.php which should be in the app's root folder.
$dirname = dirname(__FILE__);
...
$session_key = substr(md5($dirname), 0, 8);
#Setup session with different id and start it
#session_name('CMSSESSID' . $session_key);
So, in your php file you will need to do the following (before calling session_start();):
//Substitute the string $dirname for the result of __FILE__ in **include.php**!!!
$dirname = '/data/web/somefolder/someotherfolder/'
$session_key = substr(md5($dirname), 0, 8);
#session_name('CMSSESSID' . $session_key);
//Now you can call session_start();
Doing this lets your php-file access CMS's Session. If you use any plugins that put essential data in the session, you'll want to be careful not to erase any of that data.
NOTE: I use CMS version 1.8.2, this solution may not work if you use a different version.