This is probably a very simple one to be answered...
I have a piece of code which I need to pull a certain piece of information.
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('XXXX')->toHTML();?>
For this to work I need the XXXX part to pull the result of the following query:
<?php echo $_product->getAttributeText('warranty') ?>
So the output from the above query will then be the information needed to go in to XXXX.
This markup is completely wrong below but should demonstrate the idea I am trying to achieve:
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('<?php echo $_product->getAttributeText('warranty') ?>')->toHTML();?>
You just have a redundant PHP opening <?php inside the code. You are already in PHP context so you can do that call directly.
<?php echo
$this->getLayout()->createBlock('cms/block')->setBlockId($_product->getAttributeText('warranty'))->toHTML();?>
However, this is quite complicated and difficult to debug. I would split it in several lines and use variables... remember that you can do it in that context, you are not bound to do everything in one line only :)
Maybe as simple as:
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId($_product->getAttributeText('warranty'))->toHTML();?>
If not then I would very much like to know what kind of var (array, int, string, double etc) the setBlockId function needs and what $_product->getAttributeText returns.
echo $this->getLayout()->createBlock('cms/block')->setBlockId($_product->getAttributeText('warranty'))->toHTML();?>
<?php
echo $this->getLayout()
->createBlock('cms/block')
->setBlockId($_product->getAttributeText('warranty'))
->toHTML();
?>
Related
Please help me with this problem.
<?php echo $userRow2['description']; ?>
It seems that the PHP variable is incompatible with html link :(
so I want to know what is the proper method.
TIA...
echo those variables there like the following.
<?php echo $userRow2['description']; ?>
Please use a template engine for these kinds of things...
Use one of:
smarty
twig
mustache
php-view
These will brighten up your day and remove the complexity out of your html files
You can also pass all your GET params in an associative array, and use:
http_build_query($params)
so:
or in your way:
<?php echo $userRow2['description']; ?>
You can also build html/php mix with heredoc:
http://www.hackingwithphp.com/2/6/3/heredoc
it seems that the php variable is incompatible with html link
Well, PHP runs server-side. HTML is client-side. So there's no way for client-side code to interpret PHP variables.
You need to enclose server-side code in <?php ?> tags in order for it to execute on the server (like you already do elsewhere). Otherwise the server just treats it as any other HTML and returns it to the browser. Something like this:
<?php echo $userRow2['description']; ?>
As you can see, that gets a bit messy. But you can put the whole thing in one echo statement:
echo "$userRow2[description]";
Notice how the double-quotes needed to be escaped in that one, but since the whole thing was a double-quoted string the variables contained therein would expand to their values.
There are readability pros and cons either way, so it's up to you how you want to present it.
you should use this
<?php echo $userRow2['description']; ?>
or
<?=$userRow2['description']?>
You can also use Here Doc Syntax
<?php
//test variables
$inst_id = 1;
$description = "Test 1";
$eof = <<<EOF
$description
EOF;
//test output
echo $eof;
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
Twice now that I have asked and was responded that I should separate PHP from HTML in codes as much as possible. Instead of using:
<?php
echo "<p>The value of x is $valuex greater.</p>";
?>
That I should use:
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Is there any difference I should know other than the format?
One of the unique things about PHP is that it serves the purpose of both a server-side language and a templating language. Ideally, your code would be separated into controllers and views, where your controllers are pure PHP (without any HTML) and your views are mostly HTML (with minimal PHP). When you're writing a controller, PHP is just like any other server-side language. But when you're writing a view, PHP becomes a templating language, in which case HTML should rule.
Another good reason to separate the two is syntax highlighting. In your first example, most editors wouldn't realize that the text within the string is actually HTML, so they wouldn't know to apply syntax highlighting. This means your code will likely be harder to read than it could be, making life difficult for subsequent developers.
The difference is:
<?php $valuex = 6; ?>
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Here you need to echo only php variable part.
<?php
echo "<p>The value of x is $valuex greater.</p>";
?>
Here you need to echo whole part.
You need echo in second one,
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Or simply,
<p>The value of x is <?=$valuex ?> greater.</p>
Read: What's the best way to separate PHP Code and HTML?. Also read Escaping From HTML.
The output will be the same in both cases.
The first example is PHP outputting HTML code
The second example is HTML code with PHP inside it
The "Ideal" example is this:
<p>The value of x is <?=$valuex?> greater.</p>
On the first one change the syntax like
<?php
echo "<p>The value of x is ".$valuex." greater.</p>";
?>
and in the second one change to echo the value like
<p>The value of x is <?php echo $valuex; ?> greater.</p>
But both the notations are same,and work same
The reason for this is that frankly you'll want to always be as flexible as possible. However, mixing your php with html means that your php-core is mixed up with your template, thus you'll have an a lot harder time maintaining, altering & providing different templates/languages etc. Thus always keep it apart.
It's much easier to maintain your code, both HTML and PHP, when separating them.
I'm quite new here. I'm trying to make a blog/journal site that allows users to post their own journal. I'm still quite reluctant on making it because I am really afraid of malicious code injections.
So here's a sample code:
<?php
$test = "<b>blah</b>"; //User input from SQL
echo "$test";
?>
What will come out is just the word "blah" in bold right? What I was trying to achieve was to echo "<b>blah</b>" instead. I don't want people to put some PHP codes that can actually mess up my whole web page. Please keep in mind that the variable $test is actually a MYSQL query, so that variable will be needed as an example. I know you can do echo '$test'; but it just comes out as "$test" instead. I feel like pulling my hair out I can't figure it out yet.
The second solution I know of is the htmlspecialchars(); function, but I want the strings to display as what I typed, not the converted ones...
Is there any way I can do that?
I think the OP wants the HTML itself to be output to the page, and not have the tags stripped. To achieve this, you can run the string first through htmlentities()
$test = '<b>blah</b>';
echo htmlentities($test);
This will output:
<b>blah</b>
Which will render in the page as
<b>blah</b>
Echo don't execute PHP code from string. This is impossible and this is not security hole in your code.
You can use a template engine like Twig for exemple.
If htmlspecialchars(); is not the one you are looking for, try the header() option.
header('Content-type: text/plain');
When you are gonna give <b>Hi</b> to a browser, it will be displayed in Bold and not the text be returned. But you can try this way, outputting it inside a <textarea></textarea>.
Or the other way is to use htmlentities():
<?php
$test = "<b>blah</b>"; //User input from SQL
echo htmlentities("$test");
?>
What I want to do is pull html and PHP code out from a database and then execute it. So for example I may have:
<?php
$test = <<<END
<p> <?php
echo time();
?> </p>
END;
echo $test;
?>
What I want is to get $test to print
<p> 12:00PM </p> //right
instead of printing:
<p> <?php echo time(); ?> </p> //wrong
as occurs when I use the echo function.
Please do not tell me how to do the same thing with JavaScript or other work around. Instead stick to the question and remember the example is just an example to demonstrate my problem. The actual code is much more complicated.
I have looked at Javascript string variable that contains PHP code but none of the answers work.
Thanks,
Brett
I would strongly recommend against doing what you're asking to do. There are a number of very good reasons for this.
The answer to the question, as others have said, is to use eval(). However, eval() has several major issues with it.
Firstly, to follow-up from the comments on the question, code run through it is executed significantly slower than regular PHP code. Although PHP is a scripted language, it does have optimisations to make run faster. None of these optimisations work for an eval block, because the scripting engine can't know what the code will look like until it actually runs it.
Not only that, but loading the code from the database will also be slower than loading it from a file using a regular include() statement.
Secondly, eval() is one of the biggest security headaches you can have. An eval() statement will run any PHP code it is given, which means that an attacker can manipulate the code will be able to do anything on your server. In short, a single eval() statement in your code can turn a minor hack into a catastrophic one.
One alternative solution that doesn't involve changing your concept too much would be to save the PHP code to a file rather than the DB. This would allow you to simple include() it at the appropriate time, and would eliminate the speed issues discussed above. You could still use the DB to store it if you wished, and have it export to a cache file using a cron job or similar, or you could just save it directly to the file.
However, this solution wouldn't necessarily eliminate the security risks. You would still be running effectively arbitrary code, which would still mean that a hacker could do a lot of damage with a relatively simple hack.
I would therefore recommend re-thinking why you need to allow user-input PHP code to be entered into your software.
You can use eval() for this
$test = <<<END
<p> <?php
echo time();
?> </p>
END;
ob_start();
eval("?>$test");
$result = ob_get_clean();
Something like this might be useful...
<?php echo writedata($code_to_parse); ?>
<?php
function writedata($data){
if(substr($data,0,2)=="?>"){
eval($data);
// eval will run & echo the code immediately, so return an empty $code
$code="";
}else{
$code="$data";
}
return $code;
}
?>
Now you can handle either plain html & mixed php/html with one function call.
Sample data:
?>Bonjour. The time now is <?php echo $timenow; ?> in Paris.
<div class="bluebox">Perfect day for swimming</div>
There are some side effects using eval(), remember it will execute as soon as to call it, so can sometimes have unexpected results.
I asked another question about HTML and PHP separation as I have seen references to it on tutorial and examples pages but I found that separation of HTML and PHP it something different than what people are actually commenting on and I think that is PHP modes.
That is breaking out of PHP or not. Should It be done? Is it important?
Is it just a matter of preference to echo my HTML output or should I break out to display it?
Example:
<?php
echo '<html'>;
?>
vs.
<?php
dostuff();
?>
<html>
<?
morestuff();
?>
I assume by "breaking out" you mean:
<?php foo(); ?>
test
<?php bar(); ?>
as opposed to
<?php
foo();
echo("test");
bar();
?>
Well, one advantage of the first solution is that your layout is still more or less readable in HTML editors. Also, it separates layout and logic, at least more than the other variant. It is probably also slightly faster than the second option because no strings need to be parsed and echo'ed. On the flipside, having tons and tons of individual PHP-blocks can really be hard to read because things that are semantically related are suddenly split. You can, of course, also combine both approaches.
I think the bottom line here is that as soon as you need to do so much formatting and echo'ing that the logic of your program becomes really obscured, you should consider using a 'real' template engine.
I think it depends on the situation.
how many lines do you want to echo to the browser?
do the lines contain $variable values? $array values?
do you loop trough a dataset? etc etc.
To me, it is more reable to just echo the lines most of the time.
<?php
if ( check($something) ) {
echo "Some variable is: $something<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
can be more readable than:
<?php
if ( check($something) ) {
?>
Some variable is: <?php echo $something; ?><br/>
<?php
} else {
?>
Some variable is something else!<br/>
<?php
}
?>
and with some IDEs (or stackoverflow.com syntaxhighlighting for example), it can even be more readable to use:
<?php
if ( check($something) ) {
echo 'Some variable is: '.$something."<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
In summary:
PHP offers you a lot of options to send content to your client.
The 'best method' differs from case tot case.
Choose the method that is most readable/maintainable and use it consistently.
If by breaking out you mean this sort of thing:
<?php
if($somecondition) {
?>
<!-- Some HTML -->
<?php
}
?>
Then yes, breaking out is better in most cases as it is more readable (many IDES highlight HTML syntax, and cannot do so if it is withing a string when being echo() ed)