I've got two files, like these two:
<?php
session_start();
class test{
public function login($code){
$app = JFactory::getApplication('site');
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(array('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('code') . " = " . $db->quote($code));
$db->setQuery($query);//execute query
$results = $db->loadObjectList();//get results
if ($results[0] != null) {
$this->createSession($results[0]);
header("refresh:2;url=second_file.php");
}
return json_encode($results);
}
public function createSession($LoginInfo){
$_SESSION['userId']=$LoginInfo->id;
}
}
?>
and another php file like this:
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<?php
echo $_SESSION['userId'];
?>
</body>
</html>
In the second page seems like that there is no information inside the session and i'm unable to get "userId" parameter.
PS: the first class php file is called by another php file where there is something like this:
require_once('test.class.php');
$mainframe = new test
if ($_GET['code']!=null) echo $mainframe->login($_GET['code']);
Where am I doing wrong? thanks.
PPS: All those file are hosted inside altervista.org and there is Joomla CMS installed.
Related
I have a problem. I writed OOP in php, but it does not work. It gives me blank result. I putted screenshots of my code and result of that code above. Please analyse these codes and help me, how I can solve it. By the way my php version is 5.3. I can upgrade or downgrade it if it is important. Thanks.
index.php
<?php include('class_library.php'); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OOP ilk dersim)</title>
</head>
<body>
<?php
$phpders = new adam();
$padisah = new adam();
//----------
$phpders -> set_ad('NurlanXp 1');
$padisah -> set_ad('NurlanXp 2');
//------------
echo "PhpDersden gelen: ".$phpders -> get_ad;
echo "<br>Padisahdan gelen: ".$padisah -> get_ad;
?>
</body>
</html>
class_library.php
<?php
class adam{
var $ad;
function set_ad($yeni_ad){
$this -> ad = $yeni_ad;
}
function get_ad(){
return $this -> ad;
}
}
?>
index.php, class_library.php and the result of the code. Screenshots.
All documents in the same folder.
You seems using $padisah -> get_ad but your adam class doesn't have any getter metod so you have to use like
$padisah -> get_ad();
You can find working example on https://eval.in/591811
In Turkish: get_ad kısmının sonunda parantez açıp, kapatırsan sorun çözülür. Adam class'ının içerisinde getter metodu yok. Yukarıda verdiğim linkte sonundaki parantezle sorunun çözüldüğünü görebilirsin.
this is Your class:
<?php
class adam {
private $ad;
public function get_ad() {
return $this->ad;
}
public function set_ad($ad) {
$this->ad = $ad;
return $this;
}
}
and inside of code:
$phpders = new adam();
$padishah = new adam();
$phpders->set_ad('NurlanXP 1');
$padishah->set_ad('NurlanXP 2');
and usage of get_ad:
echo 'phpdersden gelen: '.$phpders->get_ad().'<br/>';
echo 'padishahdan gelen: '.$padishah->get_ad().'<br/>';
(After solving the issue mentioned by "num8er" - calling method with () ...)
Try to give an absolute include path
<?php include('/complete/path/to/class_library.php'); ?>
or set an appropriate include path set_include_path() before. You can use $_SERVER['DOCUMENT_ROOT'] as a base to build a path.
I am trying to reuse the same class instance across my files as so:
index.php
<?php
session_start();
// session_set_cookie_params(time()-199999);
// print_r($_SESSION);
// $page = array();
include('inc/functions_inc.php');
include_once('inc/functions_users.php');
$db = new DB_funcs();
// print_r($_SESSION);
// $page['description']='';
$get_page = trim(htmlspecialchars(isset($_GET['page']) ? $_GET['page'] : ''));
if($get_page !='') {
if(file_exists('pages/'.$get_page.'.php')) {
include_once('pages/'.$get_page.'.php');
}else{
include_once('pages/404.php');
}
}else{
(empty($_SESSION['logged_in'])) ? $page['description'] = users_login_form() : $page['description'] = 'Welcome , '.$_SESSION['logged_in']['username'].'! Sign out';
}
// print_r($_SESSION)
// echo '<script>alert("asd");</script>';
// var_dump($page['description']);
?>
<html>
<head>
</head>
<body>
<?= $page['description'];?>
</body>
</html>
so my variable $db instantiates and stores my class object and i am trying to reuse it across other pages such as:
login.php
<?php
include_once('inc/functions_users.php');
// var_dump($db);
$user = $db->db_getPost('username');
$pass = $db->db_getPost('password');
$page['description'] = user_login($db,$user,$pass);
now in the login.php I have included a pointer to the class object so i can use it among the functions of the included functions_users.php file.
My question is: Do I have to do this with all my functions? Assign a pointer variable to the class? Or is there a more 'lazy' way then I am already trying to achieve?
I usually use Smarty template engine, so i separate database quesries and other logic from HTML template files, then assign received in PHP variable into Smarty via their function $smarty->assign('variableName', 'variableValue'); then display correct template file with HTML markup, and then i can use within that template my assigned variables.
But how correctly it will be done with .php file tempaltes, without Smarty?
For example, i use that construction:
_handlers/Handler_Show.php
$arData = $db->getAll('SELECT .....');
include_once '_template/home.php';
_template/home.php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item) { ?>
<h2><?=$item['title']?></h2>
<?php } ?>
...
</body>
</html>
It's work. But i heard that it's not the best idea to do that.
So is this approach correct? Or maybe there's other way to organize it?
Give me advice, pelase.
Including templates in such a manner like in your example is not best idea because of template code is executed in the same namespace in which it is included. In your case template has access to database connection and other variables which should be separated from view.
In order to avoid this you can create class Template:
Template.php
<?php
class Template
{
private $tplPath;
private $tplData = array();
public function __construct($tplPath)
{
$this->tplPath = $tplPath;
}
public function __set($varName, $value)
{
$this->tplData[$varName] = $value;
}
public function render()
{
extract($this->tplData);
ob_start();
require($this->tplPath);
return ob_get_clean();
}
}
_handlers/Handler_Show.php
<?php
// some code, including Template class file, connecting to db etc..
$tpl = new Template('_template/home.php');
$tpl->arData = $db->getAll('SELECT .....');
echo $tpl->render();
_template/home.php
<?php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item): ?>
<h2><?=$item['title']?></h2>
<?php endforeach; ?>
...
</body>
</html>
As of now template hasn't access to global namespace. Of course it is still possible to use global keyword,
or access template object private data (using $this variable), but this is much better solution than
including templates directly.
You can look at existing template system source code, for example plates.
I am working in yii framework.I am getting stuck at a point where I have to call a function inside controller in yii framework from core php file. Actually I am going to create html
snapshot.
my folder structure is
seoPravin--
--protected
--modules
--kp
--Dnycontentcategoriescontroller.php
--DnycontentvisitstatController.php
--themes
--start.php (This is my customized file)
--index.php
1) Code of start.php file :--
<!DOCTYPE HTML>
<html>
<head>
<?php
if (!empty($_REQUEST['_escaped_fragment_']))
{
$yii=dirname(__FILE__).'/yii_1.8/framework/yii.php';
require_once($yii);
$escapeFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapeFragment);
include 'protected/components/Controller.php';
include 'protected/modules/'.$arr[0].'/controllers/'.$arr[1].'Controller.php';
echo DnycontentcategoriesController::actiongetDnyContent(); //gettting error at this point
?>
</head>
<body>
<?php
//echo "<br> ".$obj->actiongetDnyContent();
}
?>
</body>
</html>
2) yii side controller function : This function work for normal but when I am calling using escaped_fragment it gives error
public static function actiongetDnyContent()
{
if (!empty($_REQUEST['_escaped_fragment_']))//code inside if statement not working
{
$escapedFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapedFragment);
$contentTitleId=end($arr);
$model = new Dnycontentvisitstat(); //Error got at this line
}
else //Below code is working properly
{
$dependency = new CDbCacheDependency('SELECT MAX(createDateTime) FROM dnycontent');
$content = new Dnycontent();
$content->contentTitleId = $_GET['contentTitleId'];
$content = $content->cache(2592000,$dependency)->getContent();
$userId=105;
$ipAddress=Yii::app()->request->userHostAddress;
echo "{\"contents\":[".CJSON::encode($content)."]} ";
$model = new Dnycontentvisitstat();
$model->save($_GET['contentTitleId'], $userId, $ipAddress);
}
}
error:
Fatal error: Class 'Dnycontentvisitstat' not found in
C:\wamp\www\seoPravin\protected\modules\KnowledgePortal\controllers\DnycontentcategoriesController.php
on line 289
code is working for normal url but not working for _esaped_fragment
It is a very bad practice but you can do a HTTP self request, like this:
include("http://{$_SERVER['HTTP_HOST']}/path/?r=controller/action&_param={$_GET['param']}");
Check http://www.php.net/manual/en/function.include.php to see how to enable HTTP includes.
Hi I'm trying to make my own simple template system kind of thing
and I'm just learning about classes so I'm trying to do it with classes and objects.
it works if i put this in top of every document:
$template = new Includes('name', 'path');
$include = new Includes('name', 'path');
but it feels like it shouldn't be necessary, and its not that pretty.
This is how my code is arranged right now :
index.php:
<?php
require_once 'class_include.php';
$template->loadTemplate('body');
body.php:
<?php require_once 'class_include.php'; ?>
<head>
<?php $template->loadTemplate('head'); ?>
</head>
<body>
<?php
$template->loadTemplate('sidepanel');
$template->loadTemplate('content');
?>
</body>
class_include.php:
class Includes {
public function loadTemplate($name, $path = 'template'){
require_once "$path/$name.php";
}
public function loadInc($name, $path = 'inc'){
require_once '$path/$name' . '.php';
}
}
$template = new Includes('name', 'path');
$include = new Includes('name', 'path');
error message:
( ! ) Fatal error: Call to a member function loadTemplate() on a non-object in C:\wamp\www\project\template\body.php
( ! ) Notice: Undefined variable: template in C:\wamp\www\project\template\body.php
Thanks for any help you can provide!
Think that in your code, you should use static methods instead of objects.
index.php
<?php
require_once 'class_include.php';
Includes::loadTemplate('body');
body.php
<head>
<?php Includes::loadTemplate('head'); ?>
</head>
<body>
<?php
Includes::loadTemplate('sidepanel');
Includes::loadTemplate('content');
?>
</body>
class_includes.php
class Includes {
public static function loadTemplate($name, $path = 'template'){
require_once "$path/$name.php";
}
public static function loadInc($name, $path = 'inc'){
require_once '$path/$name' . '.php';
}
}