I'm having trouble with accessing the session in an external .php script located in webroot.
Thought I'd write a function getSession() in one of my controllers and try to call it in the .php file.
So in steps:
I have file.php
In a controller I have a function getSession().
How to call the controllers function in the file.php?
Thank you.
EDIT
Meanwhile I fixed my bug, but still am curious how this is done and want other stack users to find a good answer to this so:
Its exactly like this:
In UsersController I have a function:
public function getSession() {
return $_SESSION['Auth']['User']['user_id'];
}
That I want to let's say print (for example) like this: print_r(Users.getSession) in the file test.php located in webroot/uploadify/test.php.
This file is not a class, but if it is required, then it shall be :)
#CaboOne: Maybe your answer was correct, I just wasnt sure what code to call (and enter) where :)
Supposed I have the following php file in webroot folder:
<?php
class TestingClass {
function getName(){
return "Test";
}
}
?>
I would do the following:
// This would bring you to your /webroot folder
include $_SERVER['DOCUMENT_ROOT'].'/another_file.php';
// Initializing the class
$example = new TestingClass;
// Call a function from the initialized class
$a_value = $example->getName();
// If you want to use $a_value in the view, you can then set
$this->set('a_value', $a_value);
Related
I have a php class that uses "include" to load some html and php from a file. Within that file I want to access the class object that included the file, but I keep getting "Fatal error: Call to a member function makeSizesSelect() on a non-object ..."
I've tried both include and require, I've tried declaring globals, I've tried everything I can think of and everything I've so far found on SO. Nothing seems to allow the file I include to have php code access the object that included it.
Any ideas?
Here's a few snippets ...
The class file:
class cdf {
public $version = 001;
public function cdf_shortcode( $atts,$content )
{
$this->slog( 2,"shortcode() case: show" );
require( 'templates/container.php' );
}
}
And the required file container.php contains the following (amongst other stuff):
<?php
echo "version = ".$this->version;
?>
I then try to use the object:
$cdf = new cdf();
$cdf->cdf_shortcode( null, null);
The line $this->slog( 2,"shortcode() case: show" ) works. It runs that function (which I haven't included in this snippet) just fine. But then the file I require (or include) cannot use $this to access the object. I'm at a loss. :-(
All I want to do is access within the included file, the variables and methods in the class that included the file ...
Sorry, some added information. I'm not sure if this makes any difference. The code above is all part of a WordPress plugin.
Curious issue with a curious solution. I finally found the answer over here:
Possible to access $this from include()'d file in PHP class?
I tried all the obvious solutions this poster tried (globals, casting to another variable, etc) with the same lack of success. Turns out, just changing the file extension from .php to .tmpl fixed the issue, and my included file can now access the object that included it. Weird. (Of course, the downside now is that my IDE doesn't colour my code for me. :-( )
Thanks for your suggestions guys.
In the file you included you need to instantiate the class.
<?php
$yourClass = new cdf();
echo "version = ".$yourClass->version;
?>
When you want to access a function in a class, you need to instantiate the class first otherwise you wont have access to anything inside of it.
Also make sure the file you are including wont be included anywhere else where the class cdf doesn't exist because that will result in an error.
The variable $this can only access methods, variables, etc. only if they are in the same object.
Update based on your answer that seems to have worked:
Example.php
<?php
echo $this->returnString();
echo $this->randomVariable;
File.php
<?php
class IncludedClass
{
public $randomVariable = 123;
public function returnString()
{
return "some random string";
}
public function meh()
{
require_once('Example.php');
}
}
$meh = new IncludedClass();
$meh->meh();
I have a controller which have a function test(). I want to make this function inaccessible when access by the URL and I can't make private or protected because I want the same function to used by other controllers.
How can I achieve this, any suggestions?
If the function file is brought in by include or require functions to the controller file then you could have something like this at the start of your function file:
defined("CONTROLLER") or die();
Then, before the include function calls the function file in, use:
define("CONTROLLER", true);
That way, the function file is killed by the die() command when accessed directly but runs as normal on any page you specifically included it in.
I have a problem with classes which cannot be found in PHP.
The first thing I do is 'require_once' a file which 'require_once's all other files. When loading, no problems are showed. But when I start calling my function (Users::verificate();) I get the following error:
Fatal error: Class 'Users' not found in /Applications/XAMPP/xamppfiles/htdocs/sparks/dashboard.php on line 4
To test I've added a simple class with a function which only outputs a string with the echo method. This works so the problem has to be with this class. A MySql function which I call like this just works.
$mySql = new MySql();
$mySql->executeQuery('...');
The simple class has static a static function which I call like this (Oh, this works):
simple::launch();
In the Users class I'm calling non static functions from the MySql class from a static function. Can this be the problem?
Like another question here on SO suggested the problem isn't in using short php opening tags instead of the traditional php opening tag.
Even a little hint may help me :). Thanks for your time!
Edit:
I've added some relevant code from the User class. This is basically what it all looks like:
<?php
class Users {
public static function authenticate($email, $password) {
$mySql = new MySql();
$mySqlResult = $mySql->executeQuery("selectUser", [$email]);
...
}
public static function isAdmin() {
if ($_SESSION['isAdmin']) {
return true;
}
return false;
}
...
}
Edit 2:
I'm trying to show the flow:
From dashboard.php this are the first code lines:
<?php
require_once('code/init.php');
simple::launch();
if (!Users::verify()) {
header("Location: index.php");
}
?>
simple::launch(); is the code I used to test. This executes well. From this on the init.php file looks like this:
<?php
session_start();
require_once('simple.php');
require_once('MySql.php');
require_once('Users.php');
require_once('Projects.php');
The file names are correct as I get a visible error when these are wrong.
dashboard.php exists in the root. From there is a folder called 'code' which contains all these files.
#MbRostami gave the advice in a comment to use the 'get_required_files()' function to see which files are included. It turns out that the wrong files were loaded.
Root
| dashboard.php
| users.php
|- code
| Users.php
| init.php
In the init.php file the Users.php file (both files are in the code folder) was required. But for some reason the users.php file from the root was loaded. Some strange behaviour imho. Ahwell, that's something to investigate during the christmas days.
Problem is solved! Thanks!
I have a function inside of a view function inside of a model class in the model.php file that looks like this
function sqlToUnix($date){
$YMDThenHMS = explode(" ", $date);
$YMD = explode("-", $YMDThenHMS[0]);
$HMS = explode(":", $YMDThenHMS[1]);
$UnixTime = mktime($HMS[0], $HMS[1], $HMS[2], $YMD[1], $YMD[2], $YMD[0]);
return $UnixTime;
}
The problem is, when it returns $UnixTime, The return value is usable inside the model controller specific view function but it won't render my view (stops script propogation)
Is there a place where I can build functions like this up for use ANYWHERE in ANY Controller?
Such as the function time() built into PHP itself, I want to be able to use sqlToUnix anywhere
If you want to call this function from anywhere, i.e. in models, controllers, views, behaviors, components and helpers, you can put it in your app/config/bootstrap.php file. That's what it's for. Once the it's available globally simply as sqlToUnix();
For your specific function, are you sure there are no builtin functions which return your UnixTime format?
Is there a place where I can build functions like this up for use ANYWHERE in ANY Controller?
class MyHelpers
{
public static function sqlToUnix($SQLDate)
{
// code
return $result;
}
}
// call me this way, anywhere:
$result = MyHelpers::sqlToUnix($SQLDate);
You can write a function is bootstrap.php (although you'd do better to include another PHP file from bootstrap.php instead).
I normally have any extra functions or configuration in a file within the /app/config directory and include it with in my bootstrap.php file:
require_once(APP.'config'.DS.'my_file_of_whizzy_functions.php');
The function will then be available throughout your CakePHP app.
Aside from that, does strtotime($sqlDate); not convert a SQL time to a unix timestamp?
You can access this function via your controller and pass it into the view:
//Controller
//inside a controller action
{
$TIMESTAMP = $this->Model->sql2unix($this->Model->getTimestamp());
$this->set('timestampe',$TIMESTAMP);
// or does this even do not work?
}
otherwise you can create a component
//inside the component // inside of a component method
{
$MODEL = loadModel('ModelName');
$return = $MODEL->sql2unix($MODEL->getTimestamp());
return $return;
}
It is nearly "not important" where to place your code, you just have to follow cakephp's folder/class/helper/method/component structure.
Read the manual part about components or helpers and you'll understand everything instantly.
I was able to fix the problem by storing the function in the appController.php and called the function when need be using
$this->sqlToUnix($SQLDate);
Sorry about asking the question but I just remembered the appController when I posted this ><
I am stumped right now. In my last post about this question the answer was to use a singleton to make sure an object is only initiated 1 time but I am having the opposite problem.
If I have a file called index.php and then I include these files into it, class1.php, class2.php, class3.php, class4.php.
In index.php I will have,
<?PHP
$session = new Session();
require_once '/includes/class1php';
require_once '/includes/class2.php';
require_once '/includes/class3.php';
require_once '/includes/class4.php';
?>
then in all 4 of the test files I will try to access a method called get() from the session class, assume the session class file is already included into the index.php page as well.
Now if I try to use...
$testvar = $session->get($var1);
in any of the test class files I will get this error
Fatal error: Call to a member function get() on a non-object
the only way the code works without an error is if I use
$session = new Session();
in every file.
How can I fix/avoid having to initaite the class in every file when it is already initated in the index.php file?
the goal is to let me initiate a class in 1 file like index.php and then include the class files into that page, the catch is most of the classes use methods from other classes so would be nice if I didn't have to initiate every class in every file
Without seeing the code it's hard to tell, but I think I can make some assumptions. correct me if I'm wrong:
EDIT: So post your source so we can stop speculating
1) The files you are including are class files. in other words, they contain something like:
class a
{
function a(){}
function b()
{
}
}
2) You aren't trying to execute code in the class files, at load time, but at some later time by instantiating them
i.e.
require("class.a.php");
$myA = new a();
$a->b();
If you are trying to reference your session variable inside those classes, then you have a scope issue. A variable declared outside a class definition can't be used inside the class, unless it is declared as a global var inside the class.
class a
{
function a(){}
function willFail()
{
$session->doSomething(); //fails
}
function b()
{
global $session;
$session->doSomething(); //succeeds
}
}
Even then, you probably don't want to do that, but instead you should pass in your session as a variable if the class needs access to it:
class a
{
function a(){}
function b($session)
{
$session->doSomething(); // yay!
}
}
You could have a base class they all all extend from
Example
class test1 extends Base {
public function doSomething() {
$this->session->get('something');
}
}
class Base {
protected session;
public function __construct() {
$this->session = new Session();
}
}
You're kind of thinking about it backwards. Any file that will use the session object will need to include the file containing that class definition. The alternative is to use __autoload to pull the class in:
function __autoload($classname)
{
if ($classname == 'Session')
{
include_once 'Session.php';
}
}
EDIT : you'll need to put the file containing that autoload into every file that will use it.