PHP inside PHP?

I have a php page that has HTML code in it how to make this work?

<?php
<form method="POST" name="contact_form" 
action="'<?php echo htmlentities($_SERVER['PHP_SELF']); ?>'">
?>

Remove the first <?php ?> block

<form method="POST" name="contact_form" 
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">

The form element is HTML, not PHP.

Thanks buddy by it’s a PHP page that has a ton of PHP code above the html code?

Here is the whole code:

<?php
global $headerinclude, $header, $theme, $footer, $templates;

session_start();

$errors = '';

if(isset($_POST['submit']))
{
    
    
    if(empty($_SESSION['6_letters_code'] ) ||
      strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
    {
    //Note: the captcha code is compared case insensitively.
    //if you want case sensitive match, update the check above to
    // strcmp()
        $errors .= "\n The captcha code does not match!";
    }
    
    
    $url = "{$_POST['url']}";
    if(!filter_var($url, FILTER_VALIDATE_URL))
{
    
        $errors .= "\n Please enter valid URL";
    }
    
    
    
    if(empty($errors))
    {
require("PRclass.php");
$pr = new PR();
echo "$url has Google PageRank: ". $pr->get_google_pagerank($url) ;
}
}



$template = '<html>
<head>
<title>' . $pages['name'] . '</title>
{$headerinclude}
<script type="text/javascript">
function ValidURL() {
  var str = document.getElementById("url").value;
  var pattern = new RegExp("^https?:\/\/");
  if(!pattern.test(str)) {
    alert("Please enter a valid URL.");
    return false;
  } else {
    return true;
  }
}
</script>
<script language="JavaScript" type="text/javascript">
function refreshCaptcha()
{
    var img = document.images["captchaimg"];
    img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</head>
<body>
{$header}
{$errors}

if(!empty($errors)){
echo "<p class="err">".nl2br($errors)."</p>";
}

<div class="pr_wrapper">
<form method="POST" name="contact_form" 
action="'<?php echo htmlentities($_SERVER['PHP_SELF']); ?>'">
<div>Input URL</div>
<input type="text" id="url" name="url">
<p>
<img src="captcha.php?rand='<?php echo rand(); ?>'" id='captchaimg' ><br>
<label for="message">Enter the code above here :</label><br>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Cant read the image? click <a href="javascript: refreshCaptcha();">here</a> to refresh</small>
</p>
<input type="submit" value="Submit" name="submit" onClick="return ValidURL();">
</form>
</div>


{$footer}
</body>
</html>';

$template = str_replace("\'", "'", addslashes($template));

eval("\$page = \"" . $template . "\";");

output_page($page);

?>

Split the template out into its own file.

Then use this handy function to capture the output into a variable.

function render($template, $params)
{
    extract($params);

    ob_start();
    require $template;
    $content = ob_get_clean();

    return $content;
}

Then you would say,

$page = render('yourTemplateFile.php', [
    'pages' => $pages,
    'errors' => $errors,
    // and any other values you want to pass to the template
]);
1 Like

@Jeff_Mott very appreciate your advice but my PHP knowledge is terrible I have compiled the code in the 3rd reply works everything except form and image for captcha. Could you please split for me please?

As it’s part of a string assignment, wouldn’t you just use:

... all the previous parts of the string assigment code
<form method="POST" name="contact_form" 
action="' . htmlentities($_SERVER['PHP_SELF']) . '">
... all the rest of the code

Whilst I think @Jeff_Mott’s solution is the better way to go, it may be a little too intricate for a beginner to PHP.

What we can do is use take the advice given from Jeff_Mott’s post (by taking the templating approach), but using PHP as the templating language rather than a custom templating engine. This works by dropping in and out of the <?php ?> tags and placing all non-PHP code outside of these tags. The PHP engine will only parse what’s inside of the <?php ?> tags, and so it completely ignores the HTML/JS/whatever that is outside of these tags (which simply gets sent from the web server once PHP has done its part of parsing the PHP).

So reformatting your script to use PHP as the templating language:

<?php
global $headerinclude, $header, $theme, $footer, $templates;

session_start();

$errors = '';

if(isset($_POST['submit']))
{
    if(empty($_SESSION['6_letters_code'] ) ||
        strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
    {
        //Note: the captcha code is compared case insensitively.
        //if you want case sensitive match, update the check above to
        // strcmp()
        $errors .= "\n The captcha code does not match!";
    }

    $url = "{$_POST['url']}";
    if(!filter_var($url, FILTER_VALIDATE_URL))
    {
        $errors .= "\n Please enter valid URL";
    }



    if(empty($errors))
    {
        require("PRclass.php");
        $pr = new PR();
        echo "{$url} has Google PageRank: ".$pr->get_google_pagerank($url);
    }
}
?>
<html>
    <head>
        <title><?php echo $pages['name']; ?></title>
        <?php echo $headerinclude; ?>
        <script type="text/javascript">
            function ValidURL() {
              var str = document.getElementById("url").value;
              var pattern = new RegExp("^https?:\/\/");
              if(!pattern.test(str)) {
                alert("Please enter a valid URL.");
                return false;
              } else {
                return true;
              }
            }
        </script>
        <script language="JavaScript" type="text/javascript">
            function refreshCaptcha()
            {
                var img = document.images["captchaimg"];
                img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
            }
        </script>
    </head>
    <body>
        <?php
        echo $header;

        if(!empty($errors)) {
            echo "<p class="err">".nl2br($errors)."</p>";
        }
        ?>

        <div class="pr_wrapper">
            <form method="POST" name="contact_form" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
                <div>Input URL</div>
                <input type="text" id="url" name="url">
                <p>
                    <img src="captcha.php?rand=<?php echo rand(); ?>" id="captchaimg" ><br>
                    <label for="message">Enter the code above here :</label><br>
                    <input id="6_letters_code" name="6_letters_code" type="text"><br>
                    <small>Cant read the image? click <a href="javascript: refreshCaptcha();">here</a> to refresh</small>
                </p>
                <input type="submit" value="Submit" name="submit" onClick="return ValidURL();">
            </form>
        </div>
        <?php echo $footer; ?>
    </body>
</html>