a function for creating shortname style variables in PHP - php

I'm just learning PHP, and I'm sure I'm not the first person to try something like this, but maybe because I didn't know what to call it, I couldn't find any other examples or questions on here or from a search on google.
I wanted to create a function which takes two parameters and uses them to create all the short style variables I'll be using later in my script.
My problem is where normally the syntax to create a short variable is something like:
$var = $_METHOD['var'];
but I'm trying to do this using variables and don't know how to get the syntax right. Here's my code:
<?php
session_start();
function shortnames($some_vars, $type) {
for ($i = 0; $i<(count($some_vars)); $i++) {
$$some_vars[$i] = $_$type['$some_vars[$i]'];
echo $$some_vars[$i].' = '.$some_vars[$i].'<br />';
}
}
$post_vars = array(lastname,firstname,payment);
$session_vars = array(sessiontxt,province,city,venue,regfee);
shortnames($session_vars,session);
shortnames($post_vars,post);
?>
Thanks for helping a beginner!!

Related

Alternative for eval() -PHP

i am trying to implement URL mapping in PHP. I have a json file which stores the url and functions which is to execute when that link is requested. I was using eval() but then i came across this
Kepp the following Quote in mind:
If eval() is the answer, you're almost certainly asking the wrong
question. -- Rasmus Lerdorf, BDFL of PHP
now i am thinking is their any other(better) way to do it.
My json file looks like this.
{
"bw/":"main()",
"bw/login":"login()"
}
and my loadPage function look like this.
function loadPage($url){ //$url = 'bw/'
$str = file_get_contents('urls.json');
$this->link = json_decode($str, true);
$url = ltrim($url,"/");
$key = $this->link[$url];
eval("$key;");
}
EDIT:
i defined $this->link in my code
A slight tweak to your JSON to allow you to call the function dynamically would make it easier, just remove the brackets so it would look like...
{
"bw/":"main",
"bw/login":"login"
}
and then call it using...
function loadPage($url){ //$url = 'bw/'
$url = ltrim($url,"/");
$key = $this->link[$url];
$key();
}
A little better way is changing eval() to:
if (function_exists($key)) {
return $key();
}
return default();
and you might create a function "default" to show an error 404 or default page when function doesn't exists.

How to get variables from a different PHP file without executing the code?

I am trying to loop through all the php files listed in an array called $articleContents and extract the variables $articleTitle and $heroImage from each.
So far I have the following code:
$articleContents = array("article1.php", "article2.php"); // array of all file names
$articleInfo = [];
$size = count($articleContents);
for ($x = 0; $x <= $size; $x++) {
ob_start();
if (require_once('../articles/'.$articleContents[$x])) {
ob_end_clean();
$entry = array($articleContents[$x],$articleTitle,$heroImage);
array_push($articlesInfo, $entry);
}
The problem is, the php files visited in the loop have html, and I can't keep it from executing. I would like to get variables from each of these files without executing the html inside each one.
Also, the variables $articleTitle and $heroImage also exist at the top of the php file I'm working in, so I need to make sure the script knows I'm calling the variables in the external file and not the current one.
If this is not possible, can you please recommend an alternative method?
Thanks!
Don't do this.
Your PHP scripts should be for your application, not for your data. For your data, if you want to keep it file-based, use a separate file.
There are plenty of formats to choose from. JSON is quite popular. You can use PHP's built-in serialization as well, which has support for more PHP-native types but is not as portable to other frameworks.
A little hacky but seems to works:
$result = eval(
'return (function() {?>' .
file_get_contents('your_article.php') .
'return [\'articleTitle\' => $articleTitle, \'heroImage\' => $heroImage];})();'
);
Where your_article.php is something like:
<?php
$articleTitle = 'hola';
$heroImage = 'como te va';
The values are returned in the $result array.
Explanation:
Build a string of php code where the code in your article scripts are wrapped inside a function that returns an array with the values you want.
function() {
//code of your article.php
return ['articleTitle' => $articleTitle, 'heroImage' => $heroImage];
}
Maybe you must do some adaptations to the strings due <?php ?> tags placements.
Anyway, this stuff is ugly. I'm very sure that it can be refactored in some way.
Your problem (probably) comes down to using parentheses with require. See the example and note here.
Instead, format your code like this
$articlesInfo = []; // watch your spelling here
foreach ($articleContents as $file) {
ob_start();
if (require '../articles/' . $file) { // note, no parentheses around the path
$articlesInfo[] = [
$file,
$articleTitle,
$heroImage
];
}
ob_end_clean();
}
Update: I've tested this and it works just fine.

How to make a php variable based on two variable that vary

So i have this code, $value2 is an array of values that I edit.
I have .txt document for each of the variable in the array.. for exemple
sometext_AA.txt
sometext_BB.txt
I currently have over 50 text files, and it make a BIG BIG BIG php files because i have the following code made for each of the files for exemple sometext_AA.txt...
I would like to make one script(the following) so that one script will work for all of my $value2(I do not delete the old texts files when the value are changed so i am unable to just make script to read all different text file, it has to be done that it read the active $value2 and process them...
I am not even sure if I am on the good way but i really hope someone can help me out.
Thank you!
$value2 = array("AA","BB","CC");
foreach($value2 as $value3) {
foreach($random1_' .$value3' as $random2_' .$value3') {
$random3_' .$value3' = 'sometext_.$value3'.txt;
$random4_' .$value3' = json_encode(file_get_contents($random3_' .$value3'));
echo $random4_' .$value3';
}
}
This is a exemple of current text i have in my file, I have a very big php file, and, id like a code to make it simple
foreach($random1_AA as $random2_AA) {
$random3_AA = 'sometext_AA.txt;
$random4_AA = json_encode(file_get_contents($random3_AA));
echo $random4_AA;
}
foreach($random1_BB as $random2_BB) {
$random3_BB = 'sometext_BB.txt;
$random4_BB = json_encode(file_get_contents($random3_BB));
echo $random4_BB;
}
foreach($random1_CC as $random2_CC) {
$random3_CC = 'sometext_CC.txt;
$random4_CC = json_encode(file_get_contents($random3_CC));
echo $random4_CC;
}
foreach($random1_DD as $random2_DD) {
$random3_DD = 'sometext_DD.txt;
$random4_DD = json_encode(file_get_contents($random3_DD));
echo $random4_DD;
}
I think that this is what you are looking for, using the $var_{$var_in_var} syntax that PHP allows (so you can include a variable in a variable name).
$value2 = array("AA","BB","CC");
foreach($value2 as $value3) {
foreach($random1_{$value3} as $random2_{$value3}) {
$random3_{$value3} = 'sometext_'.$value3.'.txt';
$random4_{$value3} = json_encode(file_get_contents($random3_{$value3}));
echo $random4_{$value3};
}
}
However, I stongly advise you to consider the following points in order to make your code maintainable:
Use appropriate variable names representing the real content of each variable (you shoud never use "value1", "value2", etc. as the name tells nothing about the variable content).
Don't use variables in variable names unless absolutely necessary, which is not your case. You can use arrays, which are better suited for doing that.
In fact, I don't even know what $random1_XX and $random2_XX are supposed to be. I don't see you defining them in the code sample you posted.
Here is an example of how clear and concise you code may be if you use my advice and if all you need to read all the files and print them in JSON format (which is the only thing the program sample you posted would be doing after corrections).
$file_codes = array('AA', 'BB', 'CC');
foreach($file_codes as $file_code) {
echo json_encode(file_get_contents('sometext_'.$file_code.'.txt'));
}
Of course, if you have anything else in your program (maybe some code using the variables $random3_XX and $random4_XX?), I cannot guess what it is so I can't really offer you help to optimize this code.

Using arrays with strings with a while loop

I am writing some code to create fields automatically, which will save me a load of time. I have got most of my code working, but I have came across one error with the code, which is preventing me from achieving my final goal.
The code is as follows:
while ($i <= $numFields) {
$type = "\$field{$i}_Data['type']";
$name = "\$field{$i}_Data['name']";
$placeholder = "\$field{$i}_Data['placeholder']";
$value = "\$field{$i}_Data['value']";
echo '<input type="'.$type.'" name="'.$name.'" placeholder="'.$placeholder.'" value="'.$value.'">';
$i++;
}
The $numFields variable is defined at the top of my script, and I have worked out that it is something to do with how I am setting the variables $type, $name etc.
The end result is to create inputs depending on properties set in variables at the top of the script, The only issue I am having is with the settings of the variables, as said above.
If any extra code/information is needed, feel free to ask.
Thank you.
NOTE - There is no physical PHP error, it's purely an error with this:
"\$field{$i}_Data['value']";
There are a few ways we could write this one out, but they are all extensions of variable expansion and/or variable-variables.
Basically, we just need to put the variable name in a string and then use that string as the variable (much like you're currently doing with $i inside the string):
$type = ${"field{$i}_Data"}['type'];
$name = ${"field{$i}_Data"}['name'];
// ...
However, if you don't mind an extra variable, this can be written more cleanly by saving it like so:
$data = ${"field{$i}_Data"};
$type = $data['type'];
$name = $data['name'];
// ...

How to use a PHP object as an array

I have a heard time figuring out how to use a class as an array. This response helped me a bit on the way; but it doesn't work.
I have a class like this one:
class body_text
{
// class body_text's attributes
var $position;
var $content;
}
And I want to use it as an array:
$body_text_id = 0;
while ($row['page'] <> "")
{
$body_text[$body_text_id] -> position = trim($row["page"]);
$body_text[$body_text_id] -> content = trim($row["text");
$body_text_id++;
}
Now, it seems I would need to use this for my class
class body_text_class extends ArrayObject
and use this then:
$body_text = new body_text_class();
But that doesn't work.
I am sure there is a simple answer to this... but I can't find it. Thanks for any hints!
EDIT: Added another line in the loop to make it clearer. Sorry!
My aim: I get back many bits of text and its position within a website from a first query ("$row['page']"), and I want to store these in a variable for later use.
Hard to follow the code but you are just showing an array of objects:
for($i=0; $i<10; $i++) {
$body_text[$i] = new body_text;
$body_text[$i]->position = 'something';
}
print_r($body_text);

Categories