Score:-3

How can I embed PHP code in HTML?

ml flag

I want to execute few curl commands from my Drupal site using PHP.

Idea is to create a custom content type that accepts php code. I understood from the internet I have to create a file "node--page.tpl.php" and add the below code in this file.

  1. Will this actually work?
  2. If yes, at which path should I place node--page.tpl.php file?

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <Relavent Tags/>
    <title>My Page</title>
</head>
<body>
 <h3 style="text-align:center;">Heading</h3>

    <?php
$url = "Service Endpoint";

// Initializing curl
$curl = curl_init();

// Sending GET request to reqres.in
// server to get JSON data
curl_setopt($curl, CURLOPT_URL, $url);

// Telling curl to store JSON
// data in a variable instead
// of dumping on screen
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);    
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

// Executing curl
$response = curl_exec($curl);

// Checking if any error occurs
// during request or not
if($e = curl_error($curl)) {
    echo $e;
} else {
    
    // Decoding JSON data
    $decodedData = json_decode($response, true);
        
    // Outputting JSON data in
    // Decoded form


   print_r($decodedData);
    
}

// Closing curl
curl_close($curl);
?>

</body>
</html>
No Sssweat avatar
ua flag
.tpl.php files are for Drupal 7. Drupal 9 uses .html.twig for template files which cannot execute PHP code.
apaderno avatar
us flag
Even on Drupal 7, adding that code in a template file would be a bad idea.
Score:1
id flag

In answer to the questions you asked: No this will not work. Drupal 9 uses the Twig templating engine. You cannot execute arbitrary PHP code in Twig. Instead you should write a Drupal module.

Reddy Rohit avatar
ml flag
Can you please help with the documentation to create a custom for this scenario?
id flag
The rules of this site forbid asking about tutorials, documentation, modules, themes, or distributions you need to find or you ask us to recommend or suggest.
Score:0
gb flag

As mentioned, the module route is preferred. Pasting PHP code into content type presents a security risk and should be avoided at all costs.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.