PHP session editor - php

Are there any tools out there that will let me edit the contents of my $_SESSION? I'm trying to debug a script that is dependant on session state and I'd like to just be able to change the session variables rather than have to change the database, destroy the session and recreate it. I could probably build an ad-hoc session editor given time, but I don't have time to spare at the moment.

Well the Information in $_SESSION is just stored as a serialized string on the disk. (If you don't use something like memcached session storage)
So reading in that file, unserializing it's contents, changing the appropriate values and then serializing it back should be pretty much everything you need.
If you don't want to deal with that you could set the session_id() before session_start(), then edit the values using php and then call session_write_close() to store it on disk again.
Sample script for the session id:
<?php
session_id("838c4dc18f6535cb90a9c2e0ec92bad4");
session_start();
var_dump($_SESSION);
$_SESSION["a"] = "foo";
session_write_close();
Sample script for the unserialisation (function taken from the comments on the unserialze php.net page)
<?php
session_save_path("./session");
session_start();
$_SESSION["x"] = 1;
$id = session_id();
var_dump($id);
session_write_close();
$session = file_get_contents("./session/sess_$id");
var_dump($session);
function unserialize_session_data( $serialized_string ) {
$variables = array( );
$a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
for( $i = 0; $i < count( $a ); $i = $i+2 ) {
$variables[$a[$i]] = unserialize( $a[$i+1] );
}
return( $variables );
}
var_dump(unserialize_session_data($session));
Putting it back together isn't hard ether.

To expand it slightly, just adding the ability to add new session vars:
<?php
function listData (array $data, array $parents = array ())
{
$output = '';
$parents = array_map ('htmlspecialchars', $parents);
$fieldName = $parents?
'[' . implode ('][', $parents) . ']':
'';
foreach ($data as $key => $item)
{
$isArr = is_array ($item);
$output .= $isArr?
'<li><h4>' . htmlspecialchars ($key) . '</h4>':
'<li><label>' . htmlspecialchars ($key) . '</label>: ';
$output .= $isArr?
'<ul>' . listData ($item, array_merge ($parents, array ($key))) . '</ul>':
'<input type="text" name="fields' . $fieldName . '[' . htmlspecialchars ($key) . ']" value="' . htmlspecialchars ($item) . '" />';
$output .= "</li>\n";
}
return ($output);
}
session_start ();
if ($_POST ['fields'])
{
$_SESSION = $_POST ['fields'];
session_commit ();
}
if ($_POST['newfield'])
{
$_SESSION[$_POST['newfield']] = $_POST['newfieldvalue'];
session_commit ();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Session Editor</title>
<style type="text/css">
label {
display: inline-block;
min-width: 8em;
text-align: right;
padding-right: .3em;
}
</style>
</head>
<body>
<h2>Session Editor</h2>
<form action="<?php echo ($_SERVER ['SCRIPT_NAME']); ?>" method="post">
<ul>
<?php echo (listData($_SESSION)); ?>
</ul>
<div>
<input type="submit" />
</div>
</form>
-------------------------
<form action="<?php echo ($_SERVER ['SCRIPT_NAME']); ?>" method="post">
New Session Var:<input type="text" name="newfield" /><br />
Session Var Value:<input type="text" name="newfieldvalue" />
<div>
<input type="submit" />
</div>
</form>
</body>
</html>

Source code for an extremely basic session editor (yes, found a little time to actually work on one).
<?php
function listData (array $data, array $parents = array ())
{
$output = '';
$parents = array_map ('htmlspecialchars', $parents);
$fieldName = $parents?
'[' . implode ('][', $parents) . ']':
'';
foreach ($data as $key => $item)
{
$isArr = is_array ($item);
$output .= $isArr?
'<li><h4>' . htmlspecialchars ($key) . '</h4>':
'<li><label>' . htmlspecialchars ($key) . '</label>: ';
$output .= $isArr?
'<ul>' . listData ($item, array_merge ($parents, array ($key))) . '</ul>':
'<input type="text" name="fields' . $fieldName . '[' . htmlspecialchars ($key) . ']" value="' . htmlspecialchars ($item) . '" />';
$output .= "</li>\n";
}
return ($output);
}
session_start ();
if ($_POST ['fields'])
{
$_SESSION = $_POST ['fields'];
session_commit ();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Session Editor</title>
<style type="text/css">
label {
display: inline-block;
min-width: 8em;
text-align: right;
padding-right: .3em;
}
</style>
</head>
<body>
<h2>Session Editor</h2>
<form action="<?php echo ($_SERVER ['SCRIPT_NAME']); ?>" method="post">
<ul>
<?php echo (listData ($_SESSION)); ?>
</ul>
<div>
<input type="submit" />
</div>
</form>
</body>
</html>
Obviously extremely simplistic, but it does at least allow me to edit arbitrary session data without having to write new code every time. Might work some more on this at some point to build it into a fully featured editor, but it will do for now.

any tools out there that will let me edit the contents of my $_SESSION?
$_SESSION['var']="whatever value";

var_dump( $_SESSION );
to see your session
and
$_SESSION['variabletoset'] = 'value';
to sett your session
You generally want to var_dump the session to see what it is when you debug it.

Like Col. Shrapnel mentions I would simply setup a new PHP script on the same server that looked like this:
<?php
session_start();
$_SESSION['key'] = 'value'; // repeat for every value you need to change
Then execute the script every time you need to update the session variables. Just have your app open in one browser tab and the session update script in another. Simple.
I would never bother with tampering in the session temp files myself.

You can also do it in real-time in your debug session if you are using PHPEdit

Related

How to store mulitple data from a textarea in array

I have a textarea and a submit button and on click of the button I want that all the data seperated by a new line inserted into an array.
Here is the form file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<form action="export.php" method="POST">
<textarea name="num1" placeholder="Enter Numbers You Want To See records Of....">
</textarea>
<input type="submit" name="sub">
</form>
</body>
</html>
And Here is the PHP file
<?php
include 'connect.php';
$newnum = '';
$a = array($_POST['num1']);
foreach($a as $i=>$checknum) {
$newnum = "'".$checknum."'".',';
}
$newnum = rtrim($newnum,',');
echo "$newnum";
?>
This is what I am expecting:
Input -
1111
222
333
444
55
Output - '1111','222','333','444','55'
$a = "1111\n222\n333\n444\n55";
echo $a . PHP_EOL;
/*
1111
222
333
444
55
*/
// explode("\n", $a) ->
// Explodes input by new line into following array [1111, 222, 333, 444, 55]
// fn($line) => "'$line'" ->
// anonymous function that takes one input and wraps it between ''
// Replace with function($line) {return "'$line'";} if using PHP < 7.4
// array_map ->
// takes a callback function and an array and returns a new array by applying a callback to each item
// implode(',', ...) ->
// join all elements in new array with a separator ','
$newnum = implode(',', array_map(fn($line) => "'$line'", explode("\n", $a)));
echo $newnum;
/*
'1111','222','333','444','55'
*/
Actually you could just implode them with "','" and add ' to both ends.
$newnum = "'" . implode("','", explode("\n", $a)) . "'";
Try
$newnum = '';
$a = explode("\n", $_POST['num1']);
foreach($a as $i=>$checknum) {
$newnum. = "'".$checknum."'".',';
}
$newnum = rtrim($newnum,',');
you can use :
$res = array_filter(array_map(function($value){
return trim($value);
}, explode("\n", $a)));
Even if the person add lot of spaces ou add lot of new lines, the code will work.
Regards
assume input from textarea is:
7
10
55
$textbox_string = '7'.PHP_EOL.'10'.PHP_EOL.'55';
$arr = explode(PHP_EOL, $textbox_string);
$in_nums_query_str = implode(',', $arr);
$in_nums_query_str = str_replace(PHP_EOL, '', $in_nums_query_str);
$in_nums_query_str = str_replace(",", "','", $in_nums_query_str);
$in_nums_query_str = "'" . $in_nums_query_str . "'";
echo $in_nums_query_str;
will echo
'7','10','55'

How to display data from json url using php decode?

I am not able to display data from this url using php json decode:
https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it
here is the data provider:
https://mymemory.translated.net/doc/spec.php
thanks.
What I want is to setup a form to submit words and get translation back from their API.
here is my code sample:
<?php
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
// parse the JSON
$data = json_decode($json);
// show the translation
echo $data;
?>
My guess is that you might likely want to write some for loops with if statements to display your data as you wish:
Test
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
$data = json_decode($json, true);
if (isset($data["responseData"])) {
foreach ($data["responseData"] as $key => $value) {
// This if is to only display the translatedText value //
if ($key == 'translatedText' && !is_null($value)) {
$html = $value;
} else {
continue;
}
}
} else {
echo "Something is not right!";
}
echo $html;
Output
Ciao Mondo!
<?php
$html = '
<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
';
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
$data = json_decode($json, true);
foreach ($data["responseData"] as $key => $value) {
// This if is to only display the translatedText value //
if ($key == 'translatedText' && !is_null($value)) {
$html .= '<p>' . $value . '</p>';
} else {
continue;
}
}
$html .= '
</body>
</html>';
echo $html;
?>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
<p>Ciao Mondo!</p>
</body>
After many researches I got it working this way:
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Map&langpair=en|it');
$obj = json_decode($json);
echo $obj->responseData->translatedText;
thank you all.

PHP Language Editor, Array Keys

I have found the script.
http://www.aota.net/forums/showthread.php?t=24155
My lang.php
<?php
$Lang = array(
'TEXT' => "baer",
'GRET' => "hallo",
'FACE' => "face",
'HAPY' => "happy",
'TOOL' => "tool",
);
My edit.php
<?
// edit the values of an array ($Lang["key"] = "value";) in the file below
$array_file = "lang.php";
// if POSTed, save file
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
unset($_POST['submit']); // remove the submit button from the name/value pairs
$new_array = ""; // initialize the new array string (file contents)
$is_post = true; // set flag for use below
// add each form key/value pair to the file
foreach (array_keys($_POST) as $key)
{ $new_array .= "\$Lang[\'$key\'] => \"".trim($_POST[$key])."\",\n"; }
// write over the original file, and write a backup copy with the date/time
write_file($array_file, $new_array);
write_file($array_file . date("_Y-m-d_h-ia"), $new_array);
}
// write a file
function write_file($filename, $contents)
{
if (! ($file = fopen($filename, 'w'))) { die("could not open $filename for writing"); }
if (! (fwrite($file, $contents))) { die("could not write to $filename"); }
fclose($file);
}
// read the array into $Lang[]
$file_lines = file($array_file);
$Lang = array();
foreach ($file_lines as $line)
{
list($b4_key, $key, $b4_value, $value) = explode('"', $line);
if (preg_match("/Lang/", $b4_key))
{ $Lang[$key] = $value; }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Language Editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1><?= $array_file ?></h1>
<? if (!isset($is_post)) { ?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<? } ?>
<table>
<?
// loop through the $Lang array and display the Lang value (if POSTed) or a form element
foreach ($Lang as $key => $value)
{
echo "<tr><td>$key</td><td>";
echo isset($is_post) ? "= \"$value\"": "<input type=\"text\" name=\"$key\" value=\"$value\">";
echo "</td></tr>\n";
}
?>
</table>
<? if (!isset($is_post)) { ?>
<p><input type="submit" name="submit" value="Save"></p>
</form>
<? } ?>
</body>
</html>
Unfortunately I can not read array and Keys from lang.php.
Script writer, writes:
all lines in array.txt did do set $ Bid [] will be lost.
But I want lang.php after the change save as a PHP file that would go?
I want to create a drop-down list and load array with matching keys, change key text and save.
I thank you in advance for your help!
You shouldn't read lang.php file.
You should include it.
Better way:
require_once('lang.php'); // or require_once($array_file);
and remove these lines:
// read the array into $Lang[]
$file_lines = file($array_file);
$Lang = array();
foreach ($file_lines as $line)
{
list($b4_key, $key, $b4_value, $value) = explode('"', $line);
if (preg_match("/Lang/", $b4_key))
{ $Lang[$key] = $value; }
}
# # # # # # # #
As I understand your file contents only one language, doesn't it?
If no, will be a little modifications in the code.
<?
// edit the values of an array ($Lang["key"] = "value";) in the file below
$array_file = "lang.php";
// if POSTed, save file
if (isset($_POST['submit'])) {
unset($_POST['submit']); // remove the submit button from the name/value pairs
$is_post = true; // set flag for use below
// write over the original file, and write a backup copy with the date/time
write_file($array_file, $new_array);
write_file($array_file . date("_Y-m-d_h-ia"), $new_array);
file_put_contents($array_file, serialize(array(
'timestamp' => time(), // after you can display this value in your preffered format
'data' => serialize($_POST)
)));
}
$Lang_content = #unserialize(#file_get_contents($array_file));
if (!array_key_exists('data', $Lang_content)) {
$Lang_content = array(
'timestamp' => 0, // or time()
'data' => serialize(array())
);
}
$Lang_template = array( // If you want
'TEXT' => "baer",
'GRET' => "hallo",
'FACE' => "face",
'HAPY' => "happy",
'TOOL' => "tool",
);
$Lang = array_merge(
$Lang_template,
unserialize($Lang_content['data'])
);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Language Editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1><?= $array_file ?></h1>
<? if (!isset($is_post)) { ?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<? } ?>
<table>
<?
// loop through the $Lang array and display the Lang value (if POSTed) or a form element
foreach ($Lang as $key => $value) {
echo "<tr><td>$key</td><td>";
echo isset($is_post) ? "= \"$value\"" : "<input type=\"text\" name=\"$key\" value=\"$value\">";
echo "</td></tr>\n";
}
?>
</table>
<? if (!isset($is_post)) { ?>
<p><input type="submit" name="submit" value="Save"></p>
</form>
<? } ?>
</body>
</html>

calling a function with require but variables and arrays are undefined

Why aren't my variable seen when called with require ?
function.php
<?php
function paginator(){
$links = array("index.php", "services.php", "content.php","contact_us.php" );
$trimslug = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
foreach ($links as $key => $value) {
if ($value == $trimslug ) {
$GLOBALS['$page'] = $key;
}
}
$page = $GLOBALS['$page'];
$next = $page+1;
$previous = $page-1;
}
?>
content.php
<?php
session_start();
require './functions.php';
paginator();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pagination</title>
</head>
<body>
<h2>Now on Page : <?php echo $page?></h2>
<a href="<?php echo $links[$next] ?>" >Next</a>
<br><br><br>
<a href="<?php echo $links[$previous]?>" >Previous</a>
<br>
</body>
</html>
I would like to be able to see my variables, when using the require function as this piece of code will be on every page. This might be a very noobish concept to grasp but I would really like someone to illustrate the concept properly.
This seemed to work, Thank you everyone.
<?php
$links = array("index.php", "services.php", "content.php","contact_us.php" );
$trimslug = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
$page = null;
function paginator(){
global $links,$trimslug,$next,$previous,$page;
foreach ($links as $key => $value) {
if ($value == $trimslug ) {
// $GLOBALS['$page'] = $key;
$page = $key;
}
}
$next = $page+1;
$previous = $page-1;
}
?>
The variables inside paginator are only in the scope of the function, not the php file. If you want to access them outside that function, just move those variables outside of it. Eg
$page=null;
$links=...
function paginator(){
...
}
This is because the variables are defined in the scope of the function paginator();
If you want them to be accesible in the scope of content.php, either declare them like this:
global $variable = 'value';
Or, just declare them in function.php without the need of the function & it's subsequent call in content.php.
Variables in PHP are limited to the scope of the function, unless called via an argument or by adding to the global array.
Global arrays are bad practice, just sayin.
You could always make the variables into a private class and call it as needed, though that's pretty tricky for beginners.

How to search a multidimensional array using GET

Hey guys, I've had a lot of help from everyone here and i am really appreciative! I'm trying to create a text file search engine and i think i am on the final stretch now! All i need to do now is to be able to search the multi-dimensional array i've created for a certain word submitted by a form and grabbed with GET, and return the results in highest to lowest order (TF-IDF will come later). I can perform a simple search on the content variable which is not really what i want (see in code for $new_content) but not on the $index array.
Here is my code:
<?php
$starttime = microtime();
$startarray = explode(" ", $starttime);
$starttime = $startarray[1] + $startarray[0];
if(isset($_GET['search']))
{
$searchWord = $_GET['search'];
}
else
{
$searchWord = null;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="wrapper">
<div id="searchbar">
<h1>PHP Search</h1>
<form name='searchform' id='searchform' action='<?php echo $_SERVER['PHP_SELF']; ?>' method='get'>
<input type='text' name='search' id='search' value='<?php echo $_GET['search']; ?>' />
<input type='submit' value='Search' />
</form>
<br />
<br />
</div><!-- close searchbar -->
<?php
include "commonwords.php";
$index = array();
$words = array();
// All files with a .txt extension
// Alternate way would be "/path/to/dir/*"
foreach (glob("./files/*.txt") as $filename) {
// Includes the file based on the include_path
$content = file_get_contents($filename, true);
$pat[0] = "/^\s+/";
$pat[1] = "/\s{2,}/";
$pat[2] = "/\s+\$/";
$rep[0] = "";
$rep[1] = " ";
$rep[2] = "";
$new_content = preg_replace("/[^A-Za-z0-9\s\s+]/", "", $content);
$new_content = preg_replace($pat, $rep, $new_content);
$new_content = strtolower($new_content);
preg_match_all('/\S+/',$new_content,$matches,PREG_SET_ORDER);
foreach ($matches as $match) {
if (!isset($words[$filename][$match[0]]))
$words[$filename][$match[0]]=0;
$words[$filename][$match[0]]++;
}
foreach ($commonWords as $value)
if (isset($words[$filename][$value]))
unset($words[$filename][$value]);
$results = 0;
$totalCount = count($words[$filename]);
// And another item to the list
$index[] = array(
'filename' => $filename,
'word' => $words[$filename],
'all_words_count' => $totalCount
);
}
echo '<pre>';
print_r($index);
echo '</pre>';
if(isset($_GET['search']))
{
$endtime = microtime();
$endarray = explode(" ", $endtime);
$endtime = $endarray[1] + $endarray[0];
$totaltime = $endtime - $starttime;
$totaltime = round($totaltime,5);
echo "<div id='timetaken'><p>This page loaded in $totaltime seconds.</p></div>";
}
?>
</div><!-- close wrapper -->
</body>
</html>
foreach ($index as $result)
if (array_key_exists($searchWord,$result['word']))
echo "Found ".$searchWord." in ".$result['filename']." ".$result['word'][$searchWord]." times\r\n";
As an aside, I would highly recommend only searching the files if the search term has been filled rather than searching with every refresh to the page.
Also, some other things to keep in mind:
- Make sure you declare variables before using them (such as your $pat and $rep variables, should be $pat = Array(); before using it).
- You do the right thing at the top and check for the existence of a $searchWord but keep referencing the $_GET['search']; I would advise continuing to use $searchWord and checking against is_null($searchWord) throughout the page instead of using $_GET. It's good practice to not just output those variables on the page without an integrity check.
- Also, it may be more useful to check if the $searchWord (or words) are in the $commonWords, then process the file. Could take some time off the search if there are a lot of files or big files with a lot of words. I also don't fully understand why you're storing all words when you are only looking for keywords, but if this gets too big you'll be hitting a memory limit in the near future.

Categories