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.
Related
This question already has answers here:
extract image src from text?
(3 answers)
Closed 9 years ago.
"Consider this as example and extract the image name from this string"(this part is also included as a question".
<img src='http://www.example.com/Imagename.jpg' height='400px' width='600px'>
------->
work on the material provided above along with the sentence ... i hav combination of string and tag ... and i want to extract only the filename from all these stuff .
How to do this ?
You can use a simple regex to get it from the string, or use SimpleXMLElement
Example
<?php
$input = "<img src='http://www.example.com/Imagename.jpg' height='400px' width='600px' />";
$element= new SimpleXMLElement($input);
var_dump(basename((string) $element->attributes()->src));
Will output the desired result: string 'Imagename.jpg' (length=13)
Example using regular expression (i recommend use DOM or SimpleXMLElement like i've posted), but, if you want a simpler way like using a simple regex, you can do that:
<?php
preg_match("/src='(?P<url>([^']*?))'/", $input, $matches);
$filename = isset($matches['url']) ? basename($matches['url']) : null;
var_dump($filename);
It will produce the same output.
And a full example if you want scrap all HTML, you can do that:
<?php
$html = <<<HTML
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
</head>
<body>
lalala
<img src='http://www.example.com/Imagename.jpg' height='400px' width='600px' />
</body>
</html>
HTML;
function withEachImage ($html, callable $callback) {
libxml_use_internal_errors(true);
$document = new DOMDocument();
$document->loadHTML($html);
foreach ($document->getElementsByTagName('img') as $img) {
call_user_func_array($callback, array($img->getAttribute('src')));
}
}
withEachImage($html, function ($src) {
echo basename($src);
});
There are a number of ways to go about doing this, assuming that the image filename could change, or you may alternate between " and ', this is how i would do it;
function getFileName($myImage){
$myArray = explode(" ",$myImage);
$subArray = explode("/",$myArray[1]);
return substr($subArray[count($subArray)-1],0,-1);
}
$source = "<img src='http://www.example.com/Imagename.jpg' height='400px' width='600px'>";
$myImg = getFileName($source);
print $myImg;
Code has been tested and works
Output: Imagename.jpg
you could even make it check for 'src' so it doesnt matter what order the parameters are in:
function getFileName($myImage){
$myArray = explode(" ",$myImage);
$useKey = 0;
foreach($myArray as $key => $value){
if(substr($value,0,3)=="src"){
$useKey = $key;
}
}
$subArray = explode("/",$myArray[$useKey]);
return substr($subArray[count($subArray)-1],0,-1);
}
$source = "<img height='400px' src='http://www.example.com/Imagename.jpg' width='600px'>";
$myImg = getFileName($source);
print $myImg;
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>
I built a simple PHP spellchecker and suggestions application that uses PHP's similar_text() and levenshtein() functions to compare words from a dictionary that is loaded into an array.
How it works: First I load the contents of the dictionary into an
array.
I split the user's input into words and spell check each of the
words.
I spell check by checking if the word is in the array that is the
dictionary.
If it is, then I echo a congratulations message and move on.
If not, I iterate through the dictionary-array comparing each word, in the dictionary-array, with the assumed misspelling.
If the inputted word, in lower-case and without punctuation, is 90%
or more similar to a word in the dictionary array, then I copy that
word from the dictionary array into an array of suggestions.
If no suggestions were found using the 90% or higher similarity
comparison, then I use levenshtein() to do a more liberal comparison
and add suggestions to the suggestions array.
Then I iterate through the suggestions array and echo each
suggestion.
I noticed that this is running slowly. Slow enough to notice. And I was wondering how I could improve the speed and efficiency of this spell checker.
Any and all changes, improvements, suggestions, and code are welcome and appreciated.
Here is the code (for syntax highlighted code, please visit here):
<?php
function addTo($line) {
return strtolower(trim($line));
}
$words = array_map('addTo', file('dictionary.txt'));
$words = array_unique($words);
function checkSpelling($input, $words) {
$suggestions = array();
if (in_array($input, $words)) {
echo "you spelled the word right!";
}
else {
foreach($words as $word) {
$percentageSimilarity = 0.0;
$input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
similar_text(strtolower(trim($input)), strtolower(trim($word)), $percentageSimilarity);
if ($percentageSimilarity >= 90 && $percentageSimilarity<100) {
if(!in_array($suggestions)){
array_push($suggestions, $word);
}
}
}
if (empty($suggestions)) {
foreach($words as $word) {
$input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
$levenshtein = levenshtein(strtolower(trim($input)), strtolower(trim($word)));
if ($levenshtein <= 2 && $levenshtein>0) {
if(!in_array($suggestions)) {
array_push($suggestions, $word);
}
}
}
}
echo "Looks like you spelled that wrong. Here are some suggestions: <br />";
foreach($suggestions as $suggestion) {
echo "<br />".$suggestion."<br />";
}
}
}
if (isset($_GET['check'])) {
$input = trim($_GET['check']);
$sentence = '';
if (stripos($input, ' ') !== false) {
$sentence = explode(' ', $input);
foreach($sentence as $item){
checkSpelling($item, $words);
}
}
else {
checkSpelling($input, $words);
}
}
?>
<!Doctype HTMl>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Spell Check</title>
</head>
<body>
<form method="get">
<input type="text" name="check" autocomplete="off" autofocus />
</form>
</body>
</html>
Levenshtein over a large list will be pretty processor intensive. Right now if you mistyped refridgerator it would calculate the edit distance to cat dog and pimple.
Too pare the list down before going into the levenstein loop you could match against a precalculated metaphone or soundex key for each of your dictionary entries. This would give you a much shorter list of likely suggestions then you could use levenshtein and similar_text as a means of rank the short list of matches.
Another thing that may help you out is to cache your results. I would venture to guess that most of the misspellings are going to be common.
The following implementation doesn't deal with the paring of the data effectively but it should give you some guidelines on how to dodge the levenshtein distance against the entire dictionary for each word.
First thing you are going to want to do is append the metaphone results to each of your word entries.
This would be a servicable way to do that
<?php
$dict = fopen("dictionary-orig.txt", "r");
$keyedDict = fopen("dictionary.txt", "w");
while ($line = fgets($dict)){
$line = trim(strtolower($line));
fputcsv($keyedDict, array($line,metaphone($line)));
}
fclose($dict);
fclose($keyedDict);
?>
Along with this you are going to need something that can read the dictionary into an array
<?php
function readDictionary($file){
$dict = fopen($file, "r");
$words = array();
while($line = fgetcsv($dict)){
$words[$line[0]] = $line[1];
}
return $words;
}
function checkSpelling($input, $words){
if(array_key_exists($input, $words)){
return;
}
else {
// sanatize the input
$input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
// get the metaphone key for the input
$inputkey = metaphone($input);
echo $inputkey."<br/>";
$suggestions = array();
foreach($words as $word => $key){
// get the similarity between the keys
$percentageSimilarity = 0;
similar_text($key, $inputkey, $percentageSimilarity);
if($percentageSimilarity > 90){
$suggestions[] = array($word, levenshtein($input, $word));
}
}
// rank the suggestions
usort($suggestions, "rankSuggestions");
return $suggestions;
}
}
if(isset($_GET['check'])){
$words = readDictionary("dictionary.txt");
$input = trim($_GET['check']);
$sentence='';
$sentence = explode(' ', $input);
print "Searching Words ".implode(",", $sentence);
foreach($sentence as $item){
$suggestionsArray = checkSpelling($item, $words);
if (is_array($suggestionsArray)){
echo $item, " not found, maybe you meant";
var_dump($suggestionsArray);
} else {
echo "found $item";
}
}
}
function rankSuggestions($a, $b){
return $a[1]-$b[1];
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Spell Check</title>
</head>
<body>
<form method="get">
<input type="text" name="check" autocomplete="off" autofocus />
</form>
</body>
</html>
The simplest way to do actual paring of the data would be to split your dictionary into multiple files partitioned by something like the first character in the string. Something along the lines for dict.a.txt, dict.b.txt, dict.c.txt etc.
Okay, so my question is pretty simple. I hope the answer is too.
Let's say I have the following php string:
<!DOCTYPE html>
<html>
<head>
<title>test file</title>
</head>
<body>
<div id="dynamicContent">
<myTag>PART_ONE</myTag>
<myTag>PART_TWO </myTag>
<myTag> PART_THREE</myTag>
<myTag> PART_FOUR </myTag>
</div>
</body>
</html>
Let's say this is $content.
Now, you can see I have 4 custom tags (myTag) with one word content. (PART_ONE, PART_TWO, etc.)
I want to replace those 4 with 4 different strings. Those latter 4 strings are in an array:
$replace = array("PartOne", "PartTwo", "PartThree", "PartFour");
I did this but it doesn't work succesfully:
$content = preg_replace("/<myTag>(.*?)<\/myTag>/s", $replace, $content);
So, I want to search for myTags (it finds 4) and replace it with one entry of the array. The first occurrence should be replaced by $replace[0], the second by $replace[1], etc.
Then, it will return the "new" content as a string (not as an array) so I can use it for further parsing.
How should I realize this?
Something like the following should work:
$replace = array("PartOne", "PartTwo", "PartThree", "PartFour");
if (preg_match_all("/(<myTag>)(.*?)(<\/myTag>)/s", $content, $matches)) {
for ($i = 0; $i < count($matches[0]); $i++) {
$content = str_replace($matches[0][$i], $matches[1][$i] . $replace[$i] . $matches[3][$i], $content);
}
}
One approach would be to loop over each element in the array you want to replace with; replace the words myTag with myDoneTag or something for each one you finished, so you find the next one. Then you can always put back myTag at the end, and you have your string:
for(ii=0; ii<4; ii++) {
$content = preg_replace("/<myTag>.*<\/myTag>/s", "<myDoneTag>".$replace[ii]."<\/myDoneTag>", $content, 1);
}
$content = preg_replace("/myDoneTag/s", "myTag", $content);
With regexes, you could something like this:
$replaces = array('foo','bar','foz','bax');
$callback = function($match) use ($replaces) {
static $counter = 0;
$return = $replaces[$counter % count($replaces)];
$counter++;
return $return;
};
var_dump(preg_replace_callback('/a/',$callback, 'a a a a a '));
But really, when searching for tags in html or xml, you want a parser:
$html = '<!DOCTYPE html>
<html>
<head>
<title>test file</title>
</head>
<body>
<div id="dynamicContent">
<myTag>PART_ONE</myTag>
<myTag>PART_TWO </myTag>
<myTag> PART_THREE</myTag>
<myTag> PART_FOUR </myTag>
</div>
</body>
</html>';
$d = new DOMDocument();
$d->loadHTML($html);
$counter = 0;
foreach($d->getElementsByTagName('mytag') as $node){
$node->nodeValue = $replaces[$counter++ % count($replaces)];
}
echo $d->saveHTML();
This should be the syntax you're looking for:
$patterns = array('/PART_ONE/', '/PART_TWO/', '/PART_THREE/', '/PART_FOUR/');
$replaces = array('part one', 'part two', 'part three', 'part four');
preg_replace($patterns, $replaces, $text);
But be warned, these are run sequentially so if the text for 'PART_ONE` contains the text 'PART_TWO' that will be subsequently replaced.
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