Spartan Man
Spartan Man

Reputation: 55

how do I display html code stored within a variable in php

Within my index.html page I am taking in from the user an embed link such as:

<iframe width='560' height='315' src='http://www.youtube.com/embed/GasAmUfvXJs'     frameborder='0' allowfullscreen></iframe>

This code will be passed to my PHP script which will store it in a variable and perform some validation on it. After the validation has been successful, I then tried to echo out the variable within the PHP script. But it does not display it correctly.

Here is the PHP script:

<?php

if(isset($_POST['embed']) && isset($_POST['date'])){

$embed = $_POST['embed'];
$date = $_POST['date'];

if(!empty($embed) && !empty($date)){

    echo "OK - VIDEO";
    $final = $embed;
    echo "$final";

}else{
    $final = "Try again - not empty";
    echo "$final";
}

}else{

echo "try again - not set";

} 

?>

Upvotes: 0

Views: 1579

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

If you echo out html it will get rendered by the browser, if you want to echo out the source of the html then you would use: htmlentites()

echo htmlentites($final);

If that is not what your after please explain: But it does not display it correctly.

Also: You should not output ANY html a user inputs or your script is open by design to XSS, validation is not !empty($embed) you should be taking just the youtube id of the video out of the code and building your own embed code from that.

Heres How todo that:

<?php 
if($_SERVER['REQUEST_METHOD']=='POST'){
    if(!empty($_POST['embed']) && !empty($_POST['date'])){

        if(preg_match('#http://www.youtube.com/embed/([a-zA-Z0-9_-]+)\"#',$_POST['embed'],$match)==true){

            $embed = <<<EMBEDCODE
<iframe width="640" height="360"
        src="http://www.youtube.com/embed/{$match[1]}?feature=player_embedded"
        frameborder="0" allowfullscreen>
</iframe>
EMBEDCODE;

        }else{
            $embed = "Not a real youtube embedcode! Try Again";
        }

    }else{
        $embed = "Enter youtube embedcode.";
    }
}
?>

<h1>Youtube Yada</h1>
<form method="POST" action="">
  <p>Embedcode:<textarea rows="9" name="embed" cols="44"></textarea></p>
  <p>Date:<input type="text" name="date" value="<?php echo date("F j, Y, g:i a");?>" size="20"></p>
  <p><input type="submit" value="Submit" name="B1"></p>
</form>

<?php echo(isset($embed)?$embed:null);?>

tested with:

<iframe width="560" height="315" src="http://www.youtube.com/embed/GasAmUfvXJs" frameborder="0" allowfullscreen></iframe>

Upvotes: 1

Related Questions