Without resorting to using regex, is there a way to do so if I saved my array into json format? I'm interesting in json only because I'm using mongodb so the output comes out in json format. I have a field called docroot which is essentially a directory path.
docroot : "secure.unstable.qa.example.com"
The only two pieces that could change depending on other factors are unstable and qa. What I'm hoping for is a way to place "markers" so that they could easily be replaced with an appropriate variable.
For example:
docroot : "secure.{STREAMS}.{ENV}.example.com"
docroot : "unsecure.{STREAMS}.{ENV}.example.com"
If the variables are guaranteed to be in some specific order (they are, according to your example), then I would advise not reinventing the wheel:
// Assuming $json contains your JSON
$streams = 'foo';
$env = 'bar';
$data = json_decode($json, TRUE);
var_dump($data['docroot']); // "secure.%s.%s.example.com"
var_dump(sprintf($data['docroot'], $streams, $env)); // "secure.foo.bar.example.com"
If the variables are not guaranteed, or you'd just like to use more descriptive placeholders, just pick some unique delimiters (some character or set of characters that is unlikely to actually appear in your data), and use str_replace().
Related
So this might be a simple question but not one I can find an answer for I have a variable that looks at a standard class object and stores the value from the various field names. Unfortunately, one of my fields is called [JOB::c_job_id]. If I use this in my variable
$jobid = ($json_data_single->response->data[0]->fieldData->JOB::c_job_id);
then it thinks the:: is a Scope Resolution Operator(::) but I just want to retrieve the data from the field, how can I do this?
Any help will be greatly appreciated.
If there is no way for you to rename that very unfortunately named key in the JSON, you can take one of the following approaches:
$json = '{"JOB::c_job_id": 453}';
$decodedAsObject = json_decode($json);
var_dump($decodedAsObject->{'JOB::c_job_id'});
$decodedAsArray = json_decode($json, true);
var_dump($decodedAsArray['JOB::c_job_id']);
The first one requires you to encase the property name in {} to make it be interpreted literally. The other is a bit more straightforward, because when you decode as an array, array keys are simple strings and there is no trouble when they contain characters or character sequences that can otherwise be interpreted as having special meaning for execution.
Live test available here.
I really not getting how to do this
From PHP Manual
Cookies names can be set as array names and will be available to your
PHP scripts as arrays but separate cookies are stored on the user's
system.
This is okay to me and I got and could use like below
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
But this method will create multiple cookies and that is I don't want
PHP manual also says
Consider explode() to set one cookie with multiple names and
values.
But I did not get how to use explode to set one cookie with multiple names and values?
Please someone explain this.
But not getting this
Cookies are nothing else than a dumb key/value storage system. It's as simple as that.
It happens that PHP offers a nifty feature on top of that: cookies whose names contain square brackets in the described format will be combined into a single array variable when reading cookies back from PHP. But that's the only exception, it doesn't affect the way cookies work and, as you've said, it's a feature you don't need.
Said that, you only need to think of the cookie value as a whiteboard where you can put anything you want, as long as it's text. And there're many PHP functions that allow you to convert exotic stuff like arrays into plain text:
serialize()
json_encode()
implode()
...
Use your imagination and you're done ;-)
Update: A little remarkāI've mentioned serialize() for completeness, but it's probably not worth the effort since it'd be very complicate to ensure you don't open the door to code injection.
Use Serialize and Unserialize
Ex :
$ckArr= array();
$ckArr['abc'] = "abc";
$ckArr['xyz'] = "xyz";
$ckArr['pqr'] = "pqr";
$ckStr= serialize($ckArr);
setcookie("mycookie", $ckStr, $time, $servername);
And you can unserialised it using :
$cookieContent = unserialize($_COOKIE['mycookie']);
print_r($cookieContent);
You can set a cookie like this:
setcookie("cookiename", "value1;value2;value3;value4");
and then use explode like so:
$a = explode(';', $_COOKIE['cookiename']);
Then you will get an array of values from a single cookie.
It is also saying you should not do this... in the following sentence of the doc.
setcookie("cookiename", serialize( array("value1", "value2", "value3") );
// next request
$a = unserialize($_COOKIE['cookiename']);
because that is unsafe as users can modify their cookies to non-array values.
What would you say is the most efficient way to get a single value out of an Array. I know what it is, I know where it is. Currently I'm doing it with:
$array = unserialize($storedArray);
$var = $array['keyOne'];
Wondering if there is a better way.
You are doing it fine, I can't think of a better way than what you are doing.
You unserialize
You get an array
You get value by specifying index
That's the way it can be done.
Wondering if there is a better way.
For the example you give with the array, I think you're fine.
If the serialized string contains data and objects you don't want to unserialize (e.g. creating objects you really don't want to have), you can use the Serialized PHP library which is a complete parser for serialized data.
It offers low-level access to serialized data statically, so you can only extract a subset of data and/or manipulate the serialized data w/o unserializing it. However that looks too much for your example as you only have an array and you don't need to filter/differ too much I guess.
Its most efficient way you can do, unserialize and get data, if you need optimize dont store all variables serialized.
Also there is always way to parse it with regexp :)
If you dont want to unseralize the whole thing (which can be costly, especially for more complex objects), you can just do a strpos and look for the features you want and extract them
Sure.
If you need a better way - DO NOT USE serialized arrays.
Serialization is just a transport format, of VERY limited use.
If you need some optimized variant - there are hundreds of them.
For example, you can pass some single scalar variable instead of whole array. And access it immediately
I, too, think the right way is to un-serialize.
But another way could be to use string operations, when you know what you want from the array:
$storedArray = 'a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";i:5;}';
# another: a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";s:3:"sdf";}
$split = explode('keyOne', $storedArray, 2);
# $split[1] contains the value and junk before and after the value
$splitagain = explode(';', $split[1], 3);
# $splitagain[1] should be the value with type information
$value = array_pop(explode(':', $splitagain[1], 3));
# $value contains the value
Now, someone up for a benchmark? ;)
Another way might be RegEx ?
This might be a basic question and I've been searching for a safe and clean way to do this. Im passing a normal string which CAN include special characters (like $ ^ % etc). How can I do this in the url? For example I have a variable called $text which In addto.php from $_GET. How do I then transfer this to more.php?
'more.php?varname='.urlencode($_GET['text']);
urlencode sounds like what you want.
(from the docs)
This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
You can pass data through an URL, it should be in the form of key/value pairs, but you shouldn't use it to pass too much data because an URL has a limit. You also should not pass sensitive information.
A key/value pair is something like this:
key=value
If you have more then one pair, you need to separate them using the & char. Here is an example:
myScript.php?color1=blue&color2=red
The string after ? is called the Query String. With PHP you can easily access those key/value pairs using the super-global $_GET. So, in myScript.php you do:
$a = $_GET['color1'];
$b = $_GET['color2'];
Now, if you are going to create a dynamic query string, you should use urlencode() at least, so any special characters will be translated to maintain a proper URL format.
Please read the following:
http://php.net/urlencode
http://php.net/manual/en/function.http-build-query.php
I had no idea to correctly form the title of this question, because I don't even know if what I'm trying to do has a name.
Let's say I've got an external file (called, for instance, settings.txt) with the following in it:
template:'xaddict';
editor:'true';
wysiwyg:'false';
These are simple name:value pairs.
I would like to have php take care of this file in such a way that I end up with php variables with the following values:
$template = 'xaddict';
$editor = 'true';
$wysiwyg = 'false';
I don't know how many of these variables I'll have.
How should i go and do this?
The data inside the file is in simple name:value pairs. No nesting, no complex data. All the names need to be converted to $name and all the values need to be converted to 'value', disregarding whether it is truly a string or not.
$settings = json_decode(file_get_contents($filename));
assuming your file is in valid JSON format. If not, you can either massage it so it is or you'll have to use a different approach.
Do you want 'true' in "editor:'true'" to be interpreted as a string or as a boolean? If sometimes string, sometimes boolean, how do you know which?
If you have "number='9'" do you want '9' interpreted as a string or an as an integer? Would '09' be a decimal number or octal? How about "number='3.14'": string or float? If sometimes one, sometimes the other, how do you know which?
If you have "'" (single quote) inside a value is it escaped? If so, how?
Is there any expectation of array data?
Etc.
Edit: This would be the simplest way, imo, to use your example input to retrieve your example data:
$file = 'test.csv';
$fp = fopen($file, 'r');
while ($line = fgetcsv($fp, 1024, ':')) {
$$line[0] = $line[1];
}
If you use JSON, you can use something like:
extract(json_decode(file_get_contents('settings.json')));
Using extract may be dangerous, so I suggest to store these settings in an array:
$settings = json_decode(file_get_contents('settings.json'));
You should read your file to an array, with the file() function, then you should cycle on it: for each line (the file() function will return an array, one line per item), check if the line is not blank, then explode() on the ":" character, trim the pieces, and put them into an array.
You will end up win an array like this:
[template] = xaddict
[editor] = true
then you can use this information.
Do not automatically convert this into local variables: it's a great way to introduce security risks, and potentially very obscure bugs (local variables obscured by those introduced by this parsing).