fwrite put table with foreach - php

I want to make html file that while be a ip adress and insert what client do via $_SERVER
My problem is that i cant make table in that file so code is this
FTP
public static function Write($Wfile, $Wtext)
{
$open = fopen($Wfile, "w+");
fwrite($open, $Wtext);
}
File to create log
public function __construct()
{
chdir("Log");
$this->_file = $_SERVER['REMOTE_ADDR'] .".html";
if(!is_file($this->_file)){
ftpFile::Write($this->_file,$this->Standards());
}
public function Standards()
{
$html = "<html>\r\n <body>\r\n <table cellpadding='10'>";
return $html;
}
AND WHAT I WANT TO INSERT NOW
public function Set()
{
$indicesServer = array(
'PHP_SELF',
'argv',
'argc',
'GATEWAY_INTERFACE',
'SERVER_ADDR',
'SERVER_NAME',
......
foreach ($indicesServer as $arg){
return '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>';
}
so i try return, echo, print, file put content and i only get one result and that is last in my array.
ONCE Again i want to create log for user that come to my site and everthing inside $_SERVER write one time when sesion_id active and every where client go i want to insert and what $_POST insert in that file. Many of that i do only this is need to be fixed... TNX all

Your bottom code snippet doesn't work because you are attempting to return inside foreach loop: you can only return from a function once. Try this:
public function Set()
{
$indicesServer = array(
'PHP_SELF',
'argv',
'argc',
'GATEWAY_INTERFACE',
'SERVER_ADDR',
'SERVER_NAME',
......
$ret = "";
foreach ($indicesServer as $arg)
$ret .= '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>';
return $ret;
}

Related

PHP is replcing The < & > in a php statement with HTML comments

I am currently trying to create a small template engine for a project that I am working on, and I am using a system where I am replacing {$tag} with a preset tag. So say I put {username} in my template file, it will return a string which is the username. Now I want to go beyond just a simple string replacing a string. So using the same code I put
$tpl->replace('getID', '<?php echo "test"; ?>);
And it didn't work, so when I went to inspect element, I saw that it returned <!--? echo "test"; ?-->...
So now I am just trying to figure out why it returned commented code.
Here is my class file:
class template {
private $tags = [];
private $template;
public function getFile($file) {
if (file_exists($file)) {
$file = file_get_contents($file);
return $file;
} else {
return false;
}
}
public function __construct($templateFile) {
$this->template = $this->getFile($templateFile);
if (!$this->template) {
return "Error! Can't load the template file $templateFile";
}
}
public function set($tag, $value) {
$this->tags[$tag] = $value;
}
private function replaceTags() {
foreach ($this->tags as $tag => $value) {
$this->template = str_replace('{'.$tag.'}', $value, $this->template);
}
return true;
}
public function render() {
$this->replaceTags();
print($this->template);
}
}
And My index file is:
require_once 'system/class.template.php';
$tpl = new template('templates/default/main.php');
$tpl->set('username', 'Alexander');
$tpl->set('location', 'Toronto');
$tpl->set('day', 'Today');
$tpl->set('getID', '<?php echo "test"; ?>');
$tpl->render();
And my template file is:
<!DOCTYPE html>
<html>
<head></head>
<body>
{getID}
<div>
<span>User Name: {username}</span>
<span>Location: {location}</span>
<span>Day: {day}</span>
</div>
</body>
</html>
You're redeclaring PHP in a php file when there is no need to. i.e. you're trying to print <?php which is why it's messing up.
So, you can replace this:
$tpl->set('getID', '<?php echo "test"; ?>');
with this
$tpl->set('getID', 'test');
But, you obviously already know that, you're just trying to go further, the way to do this is by using php inside the set. So, as an idea, you could try this:
$tpl->set('getID', testfunction());
(You're calling testfunction here to define the 'getID' here btw)
So, now you want to write a little function to do something fancy, for the sake of this example:
function testfunction(){
$a = 'hello';
$b = 'world';
$c = $a . ' ' . $b;
return $c;
}
The above should then return hello world in place of {getID}
In reference to your comments - if you want to go one step further and start being more advanced with the return results, you can do the following:
function testfunction(){
$content = "";
foreach ($a as $b){
ob_start();
?>
<span><?php echo $b->something; ?></span>
Some link
<div>Some other html</div>
<?php
$content += ob_get_clean();
}
return $content
}

Codeigniter: Can't get session variable value from one controller to another

I have included session in autoload, and its working on all other places.
I'm having problem in retrieving session variable it return null result. While in the controller where i have set the session there it's working fine.
Here is the code where i'm setting it in else condition:
class Controller_catagory extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('generic_model');
$this->load->model('backend/model_post');
$this->load->model('backend/model_permissions');
}
public function index($param1='',$param2='')
{
$id=$this->generic_model->getAllRecords('dramas',array(
'drama_slug' => $param2 ),'drama_id','DESC');
// print_r($id);
if (!empty($id))
{
foreach ($id as $key)
{
$id = $key['drama_id'];
}
}
$data;
if (!empty($param1) && empty($param2))
{
$data["page"] = 'frontend/includes/view_alldramas';
$id = $this->generic_model->getAllRecords('channel',array('channel_slug' => $param1 ),'channel_id','DESC');
if (!empty($id))
{
foreach ($id as $key)
{
$id = $key['channel_id'];
$ch_slug= $data['ch_slug'] = $key['channel_slug'];
$this->session->set_userdata('ch_slug',$ch_slug);
}
}
$this->session->set_userdata('channel_capture',$id);
$data['dramas_pagination'] = $this->model_post->get_specific_channel_pagination(0,12,$id);
$data["get_dramas"]=$this->model_post->get_all_dramas();
$data['channels'] = $this->generic_model->getAllRecords('dramas', array('channel_fk' => $id ),'drama_id','DESC');
}
else
{
// The id is printing right result
echo $id;
// Here i'm setting session, if i retrieve here its working
$this->session->set_userdata('drama_episode',$id);
$data['episodes_pagination'] = $this->model_post->get_specific_post_pagination(0,12,$id);
$data["get_episodes"]=$this->model_post->get_all_dramas();
$data['dramas'] = $this->generic_model->getAllRecords('post',$arr = array(
'dramas_fk' => $id ),'id','DESC');
$data["page"] = 'frontend/includes/view_allposts';
}
$data['title'] = 'GLOBAL VIDEOS';
$data['heading'] = 'Dramas List';
$data["top"] = 'frontend/includes/top_home';
$this->load->view('frontend/index',$data);
}
}
}
Now here is another class where i'm trying to get the value of set session but its not retrieving the data and i'm getting empty record.
Note: i am doing the same thing with 'channel_capture' and i'm successfully getting its value
class Home extends CI_Controller {
public function __construct()
{
$data = array();
parent::__construct();
$this->load->model('backend/model_post');
$this->load->model('generic_model');
}
public function ajax_posts()
{
$start= $_GET['start'];
// it gives empty result here don't know why
$id = $this->session->userdata('drama_episode');
//prints nothing
echo "This key: ".$id;
$post_pagination=$this->model_post->get_specific_post_pagination($start, 12, $id);
var_dump($post_pagination);
$str='';
$base_url=base_url();
if (empty($post_pagination))
{
return false;
}
foreach($post_pagination as $post)
{
$str.= '<div class="col-lg-3 col-sm-6 col-md-4 epi_height" >';
$str.= '<a href='.$base_url.$post['slug'].'>';
$str.= '<img class="img-responsive" src='.$base_url.$post['thumbnail'].' alt="recent dramas" />';
$str.= $post['title'];
$str.= '</a>';
$str.= '</div>';
}
echo $str;
}
}
Try to set session before if else condition like:
$this->session->set_userdata('drama_episode',$id);
your if else goes here and then retrieve it.
Auto load session library from autoload.php as follows:
$autoload['libraries'] = array('session');
and you can use session variables wherever you like!
Or you may need to use flash explained here:
https://www.codeigniter.com/user_guide/libraries/sessions.html#flashdata
Please do these troubleshooting :-
Inside index() function add
echo $this->session->userdata('drama_episode'); die();
Now call the controller i believe URL/category.
Hope you can see the correct session value.
Inside ajax_posts() function print the entire session
print_r($_SESSION); die();
Call the URL to access the function ajax_posts()
Let me know what is the output u r getting?
====================================
Alternatively check, before you call the function ajax_posts(), are you some where deleting the session value for drama_episode ?

Use variables for more than one output? [ PHP Functions ]

I'm currently a beginner developer and have just started my first big project whilst I have spare time, What I'm trying to do is basically write variables to a html/tpl document, Which I have currently got working, Here is my code:
private function index(){
$username = 'MyUsername';
$onlineTime = 'MyOnlineTime';
$this->setParams('Username', $username); // $username Will be replaced by database queried results once completed.
}
And here is the setParams function.
function setParams($item1, $item2){
ob_start();
$theme = 'default';
include_once T . '/'.$theme.'/index.php'; // T . is defined at the beginning of the document.
if ((($html = ob_get_clean()) !== false) && (ob_start() === true))
{
echo preg_replace('~{(['.$item1.']*)}~i', ''.$item2.'', $html, 1);
}
}
And here is the coding inside the html/tpl document.
{username} has been online for {onlineTime} Hours
This is probably a very simple code for some of you but as this is my first attempt this is all I can do.
What I would like to do is have it so you can setParams as many times as you want without changing the $variable names like so:
private function index(){
$username = 'MyUsername';
$onlineTime = 'MyOnlineTime';
$this->setParams('Username',$username);
$this->setParams('OnlineTime', $onlineTime);
}
whilst keeping the setParams($item1, $item2)
But as you can imagine this just cuts the code completely. Does anyone know a solution to this problem? I've been searching all day without any real luck.
Thanks In Advance,
Ralph
I think what you need is a class with a static method;
<?php
class Params {
public static $params = array();
public static function setParam($key, $value) {
self::$params[$key] = $value;
}
public static function getParam($key) {
if (isset(self::$params[$key])) {
return self::$params[$key];
}
}
}
// Usage
// Set Username
Params::setParam("username", "JohnDoe");
Params::setParam("password", "12345");
echo Params::getParam("username");
echo Params::getParam("password");

Passing Variables from one functiion to another

I have 4 files. I am trying pass my fetch results through a function to another page. My code is below:
File actions.php
public function getAction($action, $page, Array $vars){
if(!empty($action)){
$action = strtolower($action);
$path = $page.'/'.$action.'.php';
$currentTemplate = $this->loadActionTemplate($path);
return Array($currentTemplate, $vars);
}
else{
$action = strtolower($action);
$path = $page.'/default.php';
$currentTemplate = $this->loadActionTemplate($path);
return ($currentTemplate);
}
}
File news.php(controller)
$file = VIEWS_PATH.strtolower($this->template) . '.php';
if (file_exists($file)){
$currentQuery = $newsModel->viewQuery($selectQuery,$returnAll);
include_once($file);
}
}
File news.php(Main view)
$factory = new Actions_Factory();
$factory->getAction($action, $page, $currentQuery);
File view.php(sub View)
print_r($currentQuery);
I can't get $currentQuery to print out the mysql dump on view.php but $currentQuery prints out fine on news.php. I am doing something wrong and can't figure out what it is.
Any help would be much appreciated.
Thanks in Advance
$factory->getAction($action, $page, $currentQuery);
print_r($currentQuery);
You set $currentQuery to getAction(), but this function return result if you want function affect on argument you have to use assign by reference!
Insert "&" in $var to assign variable by reference
public function getAction($action, $page, Array **&$vars**){

PHP class doesn't echo another php page at the appropriate place

Alright, I'm using a page creating class I found as below but when I want to use a php page -that again includes and uses a class file- for the content it either echoes on the top or the bottom of the page... I even tried to make the page a function() and call it at the $Content string but no use, again it echoed on the top of the page... How can i use a php page as a content in this class, or what should i change to use a php file?
Please keep in mind that I'm new to classes so feel free to assume some beginner mistakes.
<?php
class Page {
var $Title;
var $Keywords;
var $Content;
function Display( ) {
echo "<HTML>\n<HEAD>\n";
$this->DisplayTitle( );
$this->DisplayKeywords( );
echo "\n</HEAD>\n<BODY>\n";
echo $this->Content;
echo "\n</BODY>\n</HTML>\n";
}
function DisplayTitle( ) {
echo "<TITLE>" . $this->Title . "</TITLE>\n";
}
function DisplayKeywords( ) {
echo '<META NAME="keywords" CONTENT="' . $this->Keywords . '">';
}
function SetContent( $Data ) {
$this->Content = $Data;
}
}
?>
Usage:
<?php
include "page.class";
$Sample = new Page;
$Content = "<P>I want my php file's contents here.</P>";
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent( $Content );
$Sample->Display( );
?>
What if I wanted to make the content something like $Content = " < ? echo 'test'; ? >"; I know this isn't valid but what i'm trying to do is something like that or something like $Content = " output of the whateversinhere.php ";. how should I object orient another page therefore getting its contents into a string here?
You should NOT echo anything inside your class, instead the class should have a method getMarkup(), which will return a string containing the whole markup. Then you can echo that string in your view.
Additional tipps:
variables and method names start with a small letter!
title and keywords should have getters and setters too
make your variables private (private $title, etc.)
let me clean this up for you, you will notice some changes:
class Page
{
private $title = 'No Title';
private $keywords = array();
private $content = '';
public function setTitle($title)
{
$this->title = (string)$title;
}
public function addKeywords($keywords)
{
$this->keywords = array_merge($this->keywords, (func_num_args() > 1) ? func_get_args() : (array)$keywords;
}
function setContent($content)
{
$this->content = $content;
}
function appendContent($content)
{
$this->content .= $content;
}
function prependContent($content)
{
$this->content = $content . $this->content;;
}
private function display()
{
/*
* Display output here
*/
echo $this->title;
echo implode(',',str_replace(',','',$this->title));
echo $this->contents;
}
}
pretty simple usage:
$Page = new Page;
$Page->setTitle("Hello World");
$page->addKeywords("keyword1","keyword2","keyword3","keyword4");
//Content
$this->setContent("World");
$this->prependContent("Hello");
$this->appendContent(".");
//Display
$this->display();
Just got to fill in the blanks, you will learn as time goes on that you should not be using html directly within your class, and that you would split the above into several class such as Head,Body,Footer,Doctype and have a page class that brings them all together.
Use Output Control Functions.
<?php
include "page.class";
$Sample = new Page;
ob_start();
include "foobar.php";//What you want to include.
$content = ob_get_contents();
ob_end_clean();
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent($content);
$Sample->Display( );
?>

Categories