PHP: Generate HTML as plaintext and put in a textbox issue - php

refering as previous question here HTML Generator: Convert HTML to PlainText and put in a textbox using PHP
Now i got some problems even if the reply produce the expected result.
I got these 3 pages:
Page1.php
// This page contain two columns, one for the form that take the
variables, and other one that contain the iframe that must to display the plaintext
Page2.php
// Cutted code that take $_GET variables and store in $_SESSION
$html = file_get_contents('page3.php');
echo '<textarea readonly style="border:none;resize:none" rows="50" cols="116" value="'. $html .'"></textarea>';
Page3.php
// This is the file page3.php that must to be in plaintext, but first
it must take the variables from $_SESSION and complete the code
Now I get the plain text file but the variables aren't passed since i've stored them in session. i got $var instead of the value.
And the textbox displays only half of the file, not showing the <link> and the whole <style> tags.

<textarea> does not have value.
You need to echo that variable inside the tags.
$html = "Text here";
echo '<textarea readonly style="border:none;resize:none" rows="50" cols="116">'. $html .'</textarea>';
"it must take the variables from $_SESSION and complete the code"
Also note that you are using sessions. Make sure the session was started having session_start(); at the top of that page and for any other pages that may be using sessions.
It is required.
http://php.net/manual/en/function.session-start.php
Example:
session_start();
if(isset($_SESSION['var'])){
$_SESSION['var'] = "var";
}
else{
echo "Session is not set.";
}
N.B.: Make sure you are not outputting before header.
Consult the following on Stack if you get a headers sent notice/warning:
How to fix "Headers already sent" error in PHP
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Test example which proved successful, echoing var inside <textarea>:
<?php
session_start();
if(isset($_SESSION['var'])){
$_SESSION['var'] = "var";
$var = $_SESSION['var'];
}
else{
echo "Session is not set.";
}
// $html = "Text here";
$html = $var;
echo '<textarea readonly style="border:none;resize:none" rows="50" cols="116">'. $html .'</textarea>';
Edit:
Base yourself on the following model to assign GET arrays to sessions arrays.
<?php
session_start();
$_GET ['lb1'] = "lb1";
$lb1 = $_GET ['lb1'];
$_GET ['lb1'] = $_SESSION["lb1"];
$_SESSION["lb1"] = $lb1;
//echo "Hey LB1 " . $lb1;
$lb1_session = $lb1;
$_GET ['lb2'] = "lb2";
$lb2 = $_GET ['lb2'];
$_GET ['lb2'] = $_SESSION["lb2"];
$_SESSION["lb2"] = $lb2;
//echo "Hey LB2" . $lb2;
$lb2_session = $lb2;
$html = $lb1_session . "\n". $lb2_session;
echo '<textarea readonly style="border:none;resize:none" rows="50" cols="116">'. $html .'</textarea>';
?>
Check GET sessions
check_get_sessions.php
<?php
session_start();
if(isset($_SESSION['lb1'])){
$lb1_session = $_SESSION['lb1'];
echo $lb1_session;
}
if(isset($_SESSION['lb2'])){
$lb2_session = $_SESSION['lb2'];
echo $lb2_session;
}
$html = $lb1_session . "\n". $lb2_session;
echo '<textarea readonly style="border:none;resize:none" rows="50" cols="116">'. $html .'</textarea>';
That's the best I can offer you.
Doing $html = $lb1_session . "\n". $lb2_session; you can use "\n" as seperators between each variable to be echo'd. Or, <br> if you want; the choice is yours.
The above assigns the $html variable to chained variables. You can add the others that may need to be added $lb3, $lb4, $lb5 etc.
Good luck! (buon fortunato)

Related

Echo / printr inside variable

I have inside a php file a variable called $html which is gathering lots of information like this:
$html .= something;
$html .= something else;
etc
and in another file its being echoed like this:
echo $this->html;
What i need is at first file that $html .= is used to echo something like this:
echo '<pre>';
echo 'printr($this->cart)';
echo '</pre>';
But i need those 3 lines to be included in $html variable in order to be echoed at second file through: echo $this->html;
Any ideas?
Thank you in advance
use var_export() function for including your array in to $html variable
In php file just assign what you want to assign to $html variable then you can print it anywhere by it's variable name .
for example :
$html="";
$html .="your text";
$html .="any dynamic values";
then echo this like
echo $html;
if you are using function then simply call a function and pass your all code within function then called function from anywhere.

Get Array from PHP file and use in another PHP file

So i am having trouble getting an array from one PHP file to another.
In my first file (file1.php) i got following code:
print_r($order->delivery);
It will get visible when using echo of course, and it outputs the right things. It gives me an array with order information. Now i got another PHP file I need to use this information in.
What i tried so far is including file1.php to file2.php and then echo the array... But the result is empty.
require_once('path/file1.php');
echo print_r($order->delivery);
And i tried echo my array directly in file1.php adding a div like this
echo "<div id='test'>" . print_r($order->delivery, true) . "</div>";
And then getting the inner HTMl of the div with DOM
$dom = new DOMDocument();
$dom->loadHTML("mypageurl");
$xpath = new DOMXPath($dom);
$divContent = $xpath->query('//div[id="test"]');
if($divContent->length > 0) {
$node = $divContent->item(0);
echo "{$node->nodeName} - {$node->nodeValue}";
}
else {
// empty result set
}
Well... none of it works. Any suggestions?
You have to set a variable or something, not echoing it.
file1.php:
$delivery = $order->delivery;
file2.php
include('path/file1.php');
echo "<div id='test'>" . (isset($delivery['firstname']) ? $delivery['firstname'] : '') . "</div>";
Or you use the $object directly if it is set in file1.php
file2.php
include('path/file1.php');
echo "<div id='test'>" . (isset($order->delivery['firstname']) ? $order->delivery['firstname'] : '') . "</div>";
You can do this by using $_SESSION or $_COOKIE, See here for more detail; PHP Pass variable to next page
Be careful at the variable scope. See this link: http://php.net/manual/en/language.variables.scope.php
And try this code please:
require_once('path/file1.php');
global $order;
print_r($order->delivery);
Defining $order as global should fix your issue.
You could return an array in a file and use it in another like this:
<?php
/* File1.php */
return array(
0,1,2,3
);
-
<?php
/* File2.php */
var_dump(require_once('File1.php'));

Echo entire pre-compiled php page

For example if I had the script:
<?php
$page = "My Page";
echo "<title>" . $page . "</title>";
require_once('header.php');
require_once('content.php');
require_once('footer.php');
?>
Is there something I can add to the bottom of that page to show the entire pre-compiled php?
I want to literally echo the php code, and not compile it.
So in my browser I would see the following in code form...
// stuff from main php
$page = "My Page";
echo "<title>" . $page . "</title>";
// stuff from require_once('header.php');
$hello = "Welcome to my site!";
$name = "Bob";
echo "<div>" . $hello . " " . $name . "</div>";
// stuff from require_once('content.php');
echo "<div>Some kool content!!!!!</div>";
// stuff from require_once('footer.php');
$footerbox = "<div>Footer</div>";
echo $footerbox;
Is this possible?
There's no way to do it native to PHP, but you could try to hack it if you just wanted something extremely simplistic and non-robust:
<?php
$php = file_get_contents($_GET['file']);
$php = preg_replace_callback('#^\s*(?:require|include)(?:_once)?\((["\'])(?P<file>[^\\1]+)\\1\);\s*$#m', function($matches) {
$contents = file_get_contents($matches['file']);
return preg_replace('#<\?php(.+?)(?:\?>)?#s', '\\1', $contents);
}, $php);
echo '<pre>', htmlentities($php), '</pre>';
Notes:
Warning: Allowing arbitrary file parsing like I've done with the fist line is a security hole. Do your own authentication, path restricting, etc.
This is not recursive (though it wouldn't take much more work to make it so), so it won't handle included files within other included files and so on.
The regex matching is not robust, and very simplistic.
The included files are assumed to be statically named, within strings. Things like include($foo); or include(__DIR__ . '/foo.php'); will not work.
Disclaimer: Essentially, to do this right, you need to actually parse the PHP code. I only offer the above because it was an interesting problem and I was bored.
echo '$page = "My Page";';
echo 'echo "<title>" . $page . "</title>";';
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');
For clarity I'd put the title generation in it's own file, then just use a series of echo file_get_contents()...
echo file_get_contents('title.php');
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');

PHP $_server name and uri

Hi I'm trying to get a piece of html to only show on the main page which is http://www.domain.com/ ... I wrote the code below but it doesn't work the HTML is showing regardless of the page, am I missing something
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
?>
<div style="margin:0 auto;">
<div style="float:left">
<?php endif; ?>
First of all - please change
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
into
$hweb = 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$hweb may be initialized somewhere before.
Second:
As long as you request 'http://www.domain.com/somename.php' your if condition will never get executed. REQUEST_URI will always hold '/somename.php' except you use some url rewriting.
Third:
Make sure all calls go to 'http://www.domain.com' and not to 'http://domain.com'. Subdomain configurtaions sometimes are very complicated.
At the risk of getting it wrong again..
Why not initialize a variable in the main file before including the header
<?php
$mainfile = true;
?>
then in the header
<?php
if ($mainfile===true)
....
This way the main file can be called anything and be placed anywhere.
Solution 1:
If the above code is written inside 'http://www.domain.com/index.php' file then it may work fine.
Solution 2:
else make sure that $hewb is set with null value earlier b4 this code so that ".=" would not add extra value b4 'http...'.
Now
$hweb = '';
echo $hweb .= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
That is because the the HTML is inline in the php file but outside of the PHP tags. You can simply echo the HTML inside the if.
if ($hweb == 'http://www.domain.com/')
{
echo '<div style="margin:0 auto;">';
echo '<div style="float:left">';
}
or if you have lots of HTML you could do it like this
<?php
ob_start();
?>
<html>
<body>
<p>This HTML only be echoed </p>
</body>
</html>
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
{
ob_end_flush();
}
else
{
ob_end_clean(); // Probably not needed
}
?>

Storing an html page into a php variable [duplicate]

This question already has answers here:
HTML into PHP Variable (HTML outside PHP code)
(7 answers)
Closed 4 years ago.
Hi i'd like to store a dinamically generated(with php) html code into a variable and be able to send it as a reply to an ajax request.
Let's say i randomly generate a table like:
<?php
$c=count($services);
?>
<table>
<?php
for($i=0; $i<$c; $i++){
echo "<tr>";
echo "<td>".$services_global[$i][service] ."</td>";
echo "<td>".$services_global[$i][amount]."</td>";
echo "<td>€ ".$services_global[$i][unit_price].",00</td>";
echo "<td>€ ".$services_global[$i][service_price].",00</td>";
echo "<td>".$services_global[$i][service_vat].",00%</td>";
echo "</tr>";
}
?>
</table>
I need to store all the generated html code(and the rest) and echo it as a json encoded variable like:
$error='none';
$result = array('teh_html' => $html, 'error' => $error);
$result_json = json_encode($result);
echo $result_json;
I could maybe generate an html file and then read it with:
ob_start();
//all my php generation code and stuff
file_put_contents('./tmp/invoice.html', ob_get_contents());
$html = file_get_contents('./tmp/invoice.html');
But it sounds just wrong and since i don't really need to generate the code but only send it to my main page as a reply to an ajax request it would be a waste of resources.
Any suggestions?
You don't have to store it in a file, you can just use the proper output buffering function
// turn output buffering on
ob_start();
// normal output
echo "<h1>hello world!</h1>";
// store buffer to variable and turn output buffering offer
$html = ob_get_clean();
// recall the buffered content
echo $html; //=> <h1>hello world!</h1>
More about ob_get_clean()
if the data is so much expensive to regenerate then I would suggest you to use memcached.
Otherwise I would go regenerate it every-time or cache it on the frontend.
for($i=0;$i<=5;$i++)
{
ob_start();
$store_var = $store_var.getdata($i); // put here your recursive function name
ob_get_clean();
}
function getdata($i)
{
?>
<h1>
<?php
echo $i;
?>
</h1>
<?php
ob_get_contents();
}

Categories