emailcooke
emailcooke

Reputation: 281

PHP parse url for variables

I am building a tool that runs on my localhost that helps to put static webpages together a little faster. Security is not an issue since this is only going to run locally.

First I have an include file called components.php file with variables for page sections like this:

$slide="Pretend this is markup for a Slider";
$port="Pretend this is markup for a set of portfolio images";
$para="<p>Just another paragraph</p>";
$h1="<h1>This is a Header</h1>";

Then my url looks like this:

//only calling 3 of the 4 sections
localhost/mysite/index.php?sections=h1-slide-para

And my index file has this:

include 'components.php'

$sections =  @$_GET['sections'];
$section = explode($sections,"-");
foreach ($section as $row){
echo $row;
}

The goal here is to build the components.php file up with rows I am always using so I can quickly throw page layouts together right from the address bar of my browser. I am just not sure how to echo the variables once I explode them so that index.php contains only the markup I have called from the components.php file.

Upvotes: 0

Views: 54

Answers (3)

user2031301
user2031301

Reputation: 16

firstly instead of

$section = explode($sections, "-");

use

$section = explode("-", $sections);

and also

foreach ($section as $row){
    echo eval('return $'. $row . ';');
}

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173542

Place your strings into an array:

$sections = [
    'slide' => "Pretend this is markup for a Slider",
    'port' => "Pretend this is markup for a set of portfolio images",
    'para' => "<p>Just another paragraph</p>",
    'h1' => "<h1>This is a Header</h1>",
];

Then, reference those sections by name:

foreach (explode('-', $_GET['sections']) as $section){
    echo $sections[$section];
}

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

This should work for you:

Just use variable variables to access the variables from your components.php file (Also switch the arguments in explode(), they are the wrong way around), e.g.

$section = explode("-", $sections);

foreach ($section as $row) {
    echo $$row;
       //^^ See here the double dollar sign
}

An alternative solution would be to change your file to ini format, e.g.

slide="Pretend this is markup for a Slider"
port="Pretend this is markup for a set of portfolio images"
para="<p>Just another paragraph</p>"
h1="<h1>This is a Header</h1>"

And then get it into an array with parse_ini_file():

$arr = parse_ini_file("components.ini");
                                //^^^ Note, that you now work with an .ini file    

$sections =  @$_GET['sections'];
$section = explode("-", $sections);
foreach ($section as $row) {
    echo $arr[$row];
}

Upvotes: 2

Related Questions