1

I have the following shortcode:

// Add Shortcode
function custom_shortcode_phptest() {

  function generatePassword($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$pass = '';
for ($i = 0; $i < $length; $i++) {
$pass .= $characters[rand(0, $charactersLength - 1)];
}
return $pass;
}

$password = generatePassword();

$data = time();

$test = '/home/blablabla/public_html/ot/docs/test/' . $password . '.txt';
$file = fopen($test,"w");
fwrite($file,$data);
fclose($file);
echo 'Your pass is ' . $password . ' and it is valid for 3 days.';

}
add_shortcode( 'phptest', 'custom_shortcode_phptest' );

It will generate a password and save it in a file. But when I use [phptest] shortcode in email, sent from Wordpress admin panel it doesn't work. Is it okay to use function inside function in php shortcode?

  • 1
    have you tried to return rather than to echo the message? – Samuel Elh Aug 31 '16 at 14:54
  • 1
    Yeee, you saved me! Please make it an answer so I can mark it answered :)) – File_Submit Aug 31 '16 at 14:58
  • @File_Submit Posted the updated code for anyone else who may run into a similar issue. You can click the checkbox next to the answer to set your question as resolved. – Ethan Jinks O'Sullivan Sep 1 '16 at 14:15
  • Storing passwords as file names under public html? That's sounds rather unsecure, specifically if the directory listings is enabled by change! – birgire Sep 1 '16 at 14:18
3

Per the comment under the OP's question, below is the solution by using a return instead of an echo:

add_shortcode( 'phptest', 'custom_shortcode_phptest' );
function custom_shortcode_phptest() { // Add Shortcode

    function generatePassword( $length = 6 ) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen( $characters );
        $pass = '';
        for ( $i = 0; $i < $length; $i++ ) {
            $pass .= $characters[rand( 0, $charactersLength - 1 )];
        }
        return $pass;
    }

    $password = generatePassword();

    $data = time();

    $test = '/home/blablabla/public_html/ot/docs/test/' . $password . '.txt';
    $file = fopen( $test, "w" );
    fwrite( $file, $data );
    fclose( $file );
    return 'Your pass is ' . $password . ' and it is valid for 3 days.';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.