PHP Language Editor, Array Keys - php

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>

Related

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.

How to pass values from foreach to view in codeigniter

How can I loop values in controller send it to view in CodeIgniter
I have tried with below code
Controller
public function getdata()
{
$data = $this->Mdi_download_invoices->download_pdf_files(12);
foreach ($data as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output($estructure.$d->invoice_id,'F');
}
}
View
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo $d->invoice_id;
?>
</body>
</html>
But data is not printing in the view.How can I print the values??
You Can't foreach and pass the data to view.
public function getdata()
{
$result = $this->Mdi_download_invoices->download_pdf_files(12);
$data['d'] = $result;
$this->load->view('download_all_invoices/pdf',$data);
}
Note: Since you're using echo $d->invoice_id; check whether your result object (row, result)
I think you are looking for this :
<?php
public function getdata()
{
$data = $this->Mdi_download_invoices->download_pdf_files(12);
foreach ($data as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output($estructure.$d->invoice_id,'F');
$this->load->view('download_all_invoices/pdf',$d);
}
}
?>

Trying to loop through an array to return a filepath name

I'm new to PHP so please bear with me. I'm practicing coding for real situations so I mimicked a database by storing my image paths in an associate array so that I could create a function that would return the path name and thus just call the function to echo out my image.
My problem is it's only returning the last item in my array. I need the function to loop through the array for every item and return the file path so that I can store it in $images and then echo that out where I need to.
CODE:
<?php
$images = array(
array('name' => 'image_00', 'path' => 'images/image-00.jpg'),
array('name' => 'image_01', 'path' => 'images/image-01.jpg'),
array('name' => 'image_02', 'path' => 'images/image-02.jpg')
);
function returnPath($filename, $arr) {
$path = array();
foreach ($arr as $file) {
$path = $file[$filename];
}
return $path;
}
$images = returnPath('path', $images);
?>
<!DOCTYPE html>
<html>
<head>
<title>Images Project</title>
</head>
<body>
<img src="<?php echo $images; ?>"/>
</body>
</html>
The issue is that you're over-writing the $path variable in your returnPath function.
What you want is this:
foreach ($arr as $file) {
$path[] = $file[$filename];
}
Which in turn will give you an array of the paths that you can itterate over like this:
$images = returnPath('path', $images);
<body>
<?php
foreach($images as $image) {
echo '<img src="'. $image .'" />';
}
?>
</body>
I also strongly agree with koala_dev's comment. The function isn't really effective/useful.
Since you already have the $images array, just:
foreach($images as $img) {
echo $img['path'];
}
Or even make the function useful by returning formatted html <img> tags to print to the HTML DOM :-)
just read on Multi dimensional array. its very simple.
<?php
$images = array(
array('name' => 'image_00', 'path' => 'images/image-00.jpg'),
array('name' => 'image_01', 'path' => 'images/image-01.jpg'),
array('name' => 'image_02', 'path' => 'images/image-02.jpg')
);
?>
<!DOCTYPE html>
<html>
<head>
<title>Images Project</title>
</head>
<body>
<?php
for($i=0;$i<sizeof($images);$i++){ ?>
<img src="<? echo $images[$i]['path']; ?>"/>
<?php }?>
</body>
</html>

PHP session editor

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

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