Pinkie
Pinkie

Reputation: 10256

Expressionengine tags inside php

In expressionengine with php parse enabled,

if i do the following, it works and i get the username displayed. logged in user is admin. So it echos out admin.

<?php
  $x = '{username}';
  echo $x;
?>

However if i do the following and use the{username} tag insde mkdir() function, then it doesn't work. The directory created will have the name {username} instead of admin. Why is this happening.

<?php
  $x = '{username}';
  mkdir($x);
?>

Upvotes: 1

Views: 3738

Answers (4)

Niels
Niels

Reputation: 1

You may need to set 'PHP Parsing Stage' to 'output' in the preferences of your template in the CP Template Manager, because then PHP executes after expression engine rendered the ee tags.

Upvotes: 0

Derek Hogue
Derek Hogue

Reputation: 4564

I'd suggest writing a quick plugin that accepts the logged-in username as a parameter, then does your mkdir() work within the plugin.

class Make_directory
{
    var return_data = '';

    function __construct()
    {
        $this->EE =& get_instance();
        $username = $this->EE->TMPL->fetch_param('username', FALSE);

        if($username != FALSE)
        {
            $dir = mkdir(escapeshellarg($username));
        }

        $this->return_data = $dir;
}

There's more to the plugin, but that's the guts of it. Then call it like {exp:make_directory username="{logged_in_username}"}.

Upvotes: 2

mjec
mjec

Reputation: 1817

Expression engine is a templating engine. It almost certainly buffers output then replaces it, which is why this will work with echo but not functions.

I'm not an expert in EE, but something like this might work:

$name = get_instance()->TMPL->fetch_param('username', '');
mkdir(escapeshellarg($name));

The point is you need to get the return of EE interpreting that, rather than just passing the raw text.

You can also use ob_start() to capture the output if you can't easily get EE's return. For example:

function mkdir_obcb($dir) {
    mkdir(escapeshellarg($dir));
    return '';
}

ob_start('mkdir_obcb');
echo '{username}';
ob_end_clean();

Note also my use of escapeshellarg() to reduce the risk of attack.

Upvotes: 1

Crimsonfox
Crimsonfox

Reputation: 422

Is it possible you have it set up so your PHP is being parsed before the EE tags? Not only do you need to set to allow php parsing but what order it happens in as well.

http://expressionengine.com/user_guide/templates/php_templates.html

Upvotes: 0

Related Questions