getting all info in session post and get - php

I want to display all the session , post , get information of my php page (.php) in the page. How can I do that?

Ok, everybody states the obvious, but they do not mention the security risk embedded in every solution.
I beg to differ, here is my alternative:
echo "<pre>";
echo htmlspecialchars(var_export($_POST, true), ENT_QUOTES);
echo htmlspecialchars(var_export($_GET, true), ENT_QUOTES);
echo htmlspecialchars(var_export($_SESSION, true), ENT_QUOTES);
echo "</pre>";
You probably do not think about an attacker putting malicious code into your session, but you never know.
To put it different:
header("Content-type: text/plain");
var_export($_POST);
var_export($_GET);
var_export($_SESSION);
will equally work well, but beware browsers trying to sniff the content.
Another method that prints two thirds of the stuff nicely:
phpinfo(INFO_VARIABLES);
And at last: Try the <plaintext> tag. It has no closing tag for obvious reasons, because it will end the interpretation of HTML in the browser, but after it was sent, you'll only have to care about printing plain text.
echo "<plaintext>";
var_export($_POST);
var_export($_GET);
var_export($_SESSION);
var_export has an advantage above var_dump and print_r: It prints valid PHP code that is able to recreate the variable. This is true 100% for any type but objects. Objects have to implement the magic static method __set_state to be able to be recreated.

Use the below code to print / var_dump the information
For Session Is Below
<?php var_dump($_SESSION); ?>
For Post Is Below
<?php var_dump($_POST); ?>
For Get Is Below
<?php var_dump($_GET); ?>

<?php print_r($_SESSION); ?>
<?php print_r($_POST); ?>
<?php print_r($_GET); ?>

Try this :
POST
foreach ($_POST as $key => $value) {
$postData = "POST Field " . htmlspecialchars($key) . " is " . htmlspecialchars($value) . "<br>";
}
GET
foreach ($_GET as $key => $value) {
$postData = "GET Field " . htmlspecialchars($key) . " is " . htmlspecialchars($value) . "<br>";
}
SESSION
foreach ($_SESSION as $key => $value) {
$postData = "SESSION Field " . htmlspecialchars($key) . " is " . htmlspecialchars($value) . "<br>";
}

I prefer var_dump() over print_r(), as it handles objects as well.
I also like to output <pre> tags around my dump, so its easier to read in a browser, so
echo "<pre>";
var_dump($_SESSION);
var_dump($_POST);
var_dump($_GET);
echo "</pre>";

Related

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

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)

how to use urlencode( ) in my example?

I checked php.net and read a few examples of how urlencode( ) works but somehow I just can't get it right. Can someone give me a hand?
it'll be a lot to example so hopefully my brief example would make sense.
I have a page called 2.php and it was called to show some contents of a .txt file choosen in 1.php.
I am told to make a link for 3.php and the link should look something like /3?filename=a.txt
with filename as GET parameter name and Ensure GET parameter value is urlencoded using the urlencode( ) function.
but I'm confused how and where I should put urlencode() to make it work.
I'll paste my 2.php code here...I simplified the codes a bit...
<?php
$fileContents = file("./aaa/" . $_GET["course"] . ".txt");
echo "<table border=\"1\">";
foreach($fileContents as $row)
{
echo "<tr>";
$contents = preg_split("/,/", $row);
foreach($contents as $eachline)
{
echo "<td>";
if(!(preg_match("/#/", $eachline)))
{
echo trim(ucfirst($eachline));
}
else
{
echo trim(strtolower($eachline));
}
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
echo "<a href='./1.php'>Choose another txt file</a><br/>";
echo "or<br/>";
echo "<a href='.3.php?'>Work with this txt file</a>";
?>
BUT…the 3.php option must have a query string appended to it: the name of the text file that was selected in 1, so instead of ./3.php, the url should be something such as ./3?filename=asdf.txt
Use “filename” as the GET parameter name. Ensure the GET parameter value is urlencoded using the urlencode( ) function.
but I'm just not sure how to get it to work....
You can wrap the part that should be url encoded in the function within the string:
$url = 'http://www.google.com?q=' . urlencode($search);
OR in html
http://www.google.com?q=<?php echo urlencode($search); ?>
Where . is the concatenation of 2 outputs.

Including php variable in header()

I'm still learning php and I still haven't figured out when to use ' or ". I'm guessing thats the problem with this code. It redirects me to the right page but the $loc variable isn't carried over.
<?php header("Location: roomdata.php?loc=$loc"); ?>
on the page that has the header() commaned I also have an include command...
<?php include 'include/globalscripts.php'; ?>
and in the globalscripts.php is...
<?php if( isset($_GET['loc']))?>
<?php $loc = $_GET["loc"];?>
I would personally use:
<?php
header('Location: roomdata.php?loc='.$loc);
?>
<?php if( isset($_GET['loc']))?>
<?php $loc = $_GET["loc"];?>
TRY
<?php
if( isset($_GET['loc'])){
$loc = $_GET["loc"];
}
?>
Your code should work, are you sure $loc is defined at this point?
Regarding ' and ":
$value = "derp";
echo "the value is:\t$value";
//output: the value is: derp
echo 'the value is:\t$value';
//output: the value is:\t$value

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');

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Is there a Shortcut for
echo "<pre>";
print_r($myarray);
echo "</pre>";
It is really annoying typing those just to get a readable format of an array.
This is the shortest:
echo '<pre>',print_r($arr,1),'</pre>';
The closing tag can also be omitted.
Nope, you'd just have to create your own function:
function printr($data) {
echo "<pre>";
print_r($data);
echo "</pre>";
}
Apparantly, in 2018, people are still coming back to this question. The above would not be my current answer. I'd say: teach your editor to do it for you. I have a whole bunch of debug shortcuts, but my most used is vardd which expands to: var_dump(__FILE__ . ':' . __LINE__, $VAR$);die();
You can configure this in PHPStorm as a live template.
You can set the second parameter of print_r to true to get the output returned rather than directly printed:
$output = print_r($myarray, true);
You can use this to fit everything into one echo (don’t forget htmlspecialchars if you want to print it into HTML):
echo "<pre>", htmlspecialchars(print_r($myarray, true)), "</pre>";
If you then put this into a custom function, it is just as easy as using print_r:
function printr($a) {
echo "<pre>", htmlspecialchars(print_r($a, true)), "</pre>";
}
Probably not helpful, but if the array is the only thing that you'll be displaying, you could always set
header('Content-type: text/plain');
echo '<pre>' . print_r( $myarray, true ) . '</pre>';
From the PHP.net print_r() docs:
When [the second] parameter is set to TRUE, print_r() will return the information rather than print it.
teach your editor to do it-
after writing "pr_" tab i get exactly
print("<pre>");
print_r($);
print("</pre>");
with the cursor just after the $
i did it on textmate by adding this snippet:
print("<pre>");
print_r(\$${1:});
print("</pre>");
If you use VS CODE, you can use :
Ctrl + Shift + P -> Configure User Snippets -> PHP -> Enter
After that you can input code to file php.json :
"Show variable user want to see": {
"prefix": "pre_",
"body": [
"echo '<pre>';",
"print_r($variable);",
"echo '</pre>';"
],
"description": "Show variable user want to see"
}
After that you save file php.json, then you return to the first file with any extension .php and input pre_ -> Enter
Done, I hope it helps.
If you are using XDebug simply use
var_dump($variable);
This will dump the variable like print_r does - but nicely formatted and in a <pre>.
(If you don't use XDebug then var_dump will be as badly formated as print_r without <pre>.)
echo "<pre/>"; print_r($array);
Both old and accepted, however, I'll just leave this here:
function dump(){
echo (php_sapi_name() !== 'cli') ? '<pre>' : '';
foreach(func_get_args() as $arg){
echo preg_replace('#\n{2,}#', "\n", print_r($arg, true));
}
echo (php_sapi_name() !== 'cli') ? '</pre>' : '';
}
Takes an arbitrary number of arguments, and wraps each in <pre> for CGI requests. In CLI requests it skips the <pre> tag generation for clean output.
dump(array('foo'), array('bar', 'zip'));
/*
CGI request CLI request
<pre> Array
Array (
( [0] => foo
[0] => foo )
) Array
</pre> (
<pre> [0] => bar
Array [1] => zip
( )
[0] => bar
[0] => zip
)
</pre>
I just add function pr() to the global scope of my project.
For example, you can define the following function to global.inc (if you have) which will be included into your index.php of your site. Or you can directly define this function at the top of index.php of root directory.
function pr($obj)
{
echo "<pre>";
print_r ($obj);
echo "</pre>";
}
Just write
print_r($myarray); //it will display you content of an array $myarray
exit(); //it will not execute further codes after displaying your array
Maybe you can build a function / static class Method that does exactly that. I use Kohana which has a nice function called:
Kohana::Debug
That will do what you want. That's reduces it to only one line. A simple function will look like
function debug($input) {
echo "<pre>";
print_r($input);
echo "</pre>";
}
function printr($data)
{
echo "<pre>";
print_r($data);
echo "</pre>";
}
And call your function on the page you need, don't forget to include the file where you put your function in for example: functions.php
include('functions.php');
printr($data);
I would go for closing the php tag and then output the <pre></pre> as html, so PHP doesn't have to process it before echoing it:
?>
<pre><?=print_r($arr,1)?></pre>
<?php
That should also be faster (not notable for this short piece) in general. Using can be used as shortcode for PHP code.
<?php
$people = array(
"maurice"=> array("name"=>"Andrew",
"age"=>40,
"gender"=>"male"),
"muteti" => array("name"=>"Francisca",
"age"=>30,
"gender"=>"Female")
);
'<pre>'.
print_r($people).
'</pre>';
/*foreach ($people as $key => $value) {
echo "<h2><strong>$key</strong></h2><br>";
foreach ($value as $values) {
echo $values."<br>";;
}
}*/
//echo $people['maurice']['name'];
?>
I generally like to create my own function as has been stated above. However I like to add a few things to it so that if I accidentally leave in debugging code I can quickly find it in the code base. Maybe this will help someone else out.
function _pr($d) {
echo "<div style='border: 1px solid#ccc; padding: 10px;'>";
echo '<strong>' . debug_backtrace()[0]['file'] . ' ' . debug_backtrace()[0]['line'] . '</strong>';
echo "</div>";
echo '<pre>';
if(is_array($d)) {
print_r($d);
} else if(is_object($d)) {
var_dump($d);
}
echo '</pre>';
}
You can create Shortcut key in Sublime Text Editor using Preferences -> Key Bindings
Now add below code on right-side of Key Bindings within square bracket []
{
"keys": ["ctrl+shift+c"],
"command": "insert_snippet",
"args": { "contents": "echo \"<pre>\";\nprint_r(${0:\\$variable_to_debug});\necho \"</pre>\";\ndie();\n" }
}
Enjoy your ctrl+shift+c shortcut as a Pretty Print of PHP.
Download AutoHotKey program from the official website: [https://www.autohotkey.com/]
After Installation process, right click in any folder and you will get as the following image: https://i.stack.imgur.com/n2Rwz.png
Select AutoHotKey Script file, open it with notePad or any text editor Write the following in the file:
::Your_Shortcut::echo '<pre>';var_dump();echo '</pre>';exit();
the first ::Your_Shortcut means the shortcut you want, I choose for example vard.
Save the file.
Double-click on the file to run it, after that your shortcut is ready.
You can test it by write your shortcut and click space.
For more simpler way
echo ""; print_r($test); exit();

Categories