This question already has answers here:
How can I combine two strings together in PHP?
(19 answers)
Closed 6 years ago.
So I'm trying to design a website that will allow the user to input data to design a tower. When it comes to the dimensions of basic parts of the tower (the height, width, and depth), I want to present them in a H x W x D format (i.e. 3 x 2 x 2). Trouble is, I'm having problems with concatenation in the PHP file for the second page of the website where everything's displayed.
Here's what my code looks like so far:
<!DOCTYPE html>
<html>
<head>
<title>Results for tower design</title>
</head>
<body>
Pillar base shape: <?php echo $_POST["tBase"]; ?><br>
Pillar dimensions: <?php echo ($_POST["tHeight"];)." x ".($_POST["tWidth"];)." x ".($_POST["tDepth"];) ?><br>
</body>
</html>
It's highly possible that I might be making a common beginner error. If so, I want to know where I went wrong and how to avoid it.
You have some extra semicolons in improper places. A semicolon indicates the end of a PHP statement. You should not use them in the middle of building a string.
($_POST["tHeight"];)
Remove them and make sure you sanitize your output (or you'll be open to XSS attacks)
htmlspecialchars($_POST["tHeight"])." x ".htmlspecialchars($_POST["tWidth"])." x ".htmlspecialchars($_POST["tDepth"])
Running this, would have thrown you: Parse error: syntax error, unexpected ';' in...
Use error reporting during testing.
http://php.net/manual/en/function.error-reporting.php
Plus, make sure your POST arrays contain values and that your form uses a post method with matching named attributes.
Fun fact, you can have it all showed as a single line:
Pillar dimensions: <?php echo "{$_POST["tHeight"]} x {$_POST["tWidth"]} x {$_POST["tDepth"]}"; ?>
Every echo that is wrapped with double quotes can have variable been echoed just wrapping with {}.
Remove semicolumns
<?php echo ($_POST["tHeight"] ." x ".$_POST["tWidth"] ." x ".$_POST["tDepth"]); ?>
Related
This question already has an answer here:
Difference in accessing arrays in PHP 5.3 and 5.4 or some configuration mismatch?
(1 answer)
Closed 6 years ago.
I a, trying output photo, but can't.
when i write this
echo "<p>Name: <b>".$rows['photo']."</b></p>";
it say:
img/car.jpg
but i need a image, so I write
echo '<p><img src=img/$rows['photo']/></b></p>';
it say
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';'
Try this:
echo "<p><img src=img/$rows['photo']/></b></p>";
or
echo '<p><img src=img/'.$rows['photo'].'/></b></p>';
This is correct string manipulation to get what you want:
echo "<p><img src=\"{$rows['photo']}\" /></p>";
Use "" as string wrapper to inject variables using curly braces notation.
Also if you have $rows['photo'] = img/car.jpg you will not need extra img/ in src attribute.
And i removed </b> tag, since there was no opening tag for it.
if you want to display the image fetch the image in the separate file and use that file path in the img tag
<img src="fetch_image.php?id='.$id.'"/>
$id is a primary key value
The fail is caused by the bad syntax. If we can assume that $rows['photo'] holds a filename within /img directory then you should use it like this:
double quotes here and at the end
↓
echo "<p><img src='img/{$rows['photo']}'/></b></p>";
↑ ↑
curly braces to distinguish variables in a string
Here's a manual that you need to read in order to understand how it works http://php.net/manual/en/language.types.string.php
And last but not least - you have a possible XSS attack vector here because you don't escape value of $rows['photo']. That means that if a value of photo can be changed by user then user could put, for example this string: image.jpg' onclick='window.location="my.fishing.website.com"; - that is being the most simple form of this kind of attack (he could also steal cookie values or any other sensitive data).
To mitigate this kind of security hole you need to escape values, which can be influenced by user in any way, with htmlspecialchars() function. Or even better use templating engine that would it for you: http://www.phptherightway.com/#templating
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
So I'm trying to define $picurl1 so that it uses the value in $pic1. So in the end I want it to be:
<img src="./pictures/{definition of pic1}.png">
Right now I use this php code:
$pic1 = '<script src="pic.js"></script>';
$picurl1 = '<img src="./pictures/' + $pic1 + '.png'">';
Sorry if I'm not being very clear. I don't really know how to explain it. I hope you understand.
In other words, please tell me what I should change $picurl1 to.
By the way the script comes up with a random picture name without the '.png'.
Thanks in advance.
For starters, you're using the wrong operator to concatenate strings in PHP. I think you mean this:
$picurl1 = '<img src="./pictures/' . $pic1 . '.png'">';
More to the point, what is "definition of pic1"? Do you mean that the code in pic.js will randomly choose a file name, and you want its result to be the URL used in the img tag?
The problem you're encountering, then, is that PHP runs on the server while JavaScript runs on the client. So your PHP code can't use the result of pic.js because it won't have a result until the browser runs it, after the PHP code is done.
So you need to get that result client-side in JavaScript code.
How does pic.js create that result? That is, is there a function in pic.js? For now I'm going to assume there is, and I'm going to assume that function is called something like getFileName. (Just for the purpose of this example.)
After you included the JavaScript code, and after the img tag is in the document, you can call that function and set the src of the img tag to its results. To help us identify the img tag, let's give it an id:
<img src="default.gif" id="theImage" alt="This is a dynamic image" />
(I gave it a default value for the src since an empty value is invalid. I also have it an alt value for completeness.) To change its src value to the result of a function, you'd do something like the following:
document.getElementById('theImage').src = getFileName();
Remember, this is all client-side code. The only way you can use the "result" in PHP code is if the calculation is done in PHP, not in JavaScript.
You must consider that all the server side codes are executed before the client side codes (javascript, html, css , ...). so your code does not make any sense , you can not embed an undefined code inside another code that is executing sooner.
if your js code must return some thing, so remove php codes and simply use HTML instead
I tested this successfully:
$picName = "greenButterfly7"; //note no spaces inbetween green and butterfly
$picurl1 = "<img src='./pictures/" . $picName . ".png'>";
echo $picurl1;
or in pure HTML form:
<img src='pictures/greenButterfly7.png'>
or in embedded form (PHP inside HTML):
<img src='pictures/<?php echo $picName; ?>.png'>
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 am attempting to get two fields to display inline.
Specifically, I need the Locator, and the Body fields to display inline.
My Locator simply states the location of a post in plain text.
i.e. "Duluth, MN - "
My Body is the story.
i.e. "Are strange things happening in your house? Lights turning off and on by themselves? Or are you hearing voices in the basement?"
I'm attempting to display them inline but am having the hardest time.
i.e. "Duluth, MN - Are strange things happening in your house? Lights turning off and on by themselves? Or are you hearing voices in the basement?"
They need to be two separate fields for use in a Geo Locator.
I use the Display Suite module, and from my web searches I have found that it is possible to use the custom Code Field option to pull the data by Token, or PHP $entity.
I can get it working just fine with both Token, and PHP $entity, but cannot figure out how to get them to be inline?
i.e My Result is always:
"Duluth, MN -
Are strange things happening in your house? Lights turning off and on by themselves? Or are you hearing voices in the basement?"
I'm sure I'm missing something easy, and/or just overlooking something.
Here is the code I've used:
Works! Tokens!
[node:field-locator] - [node:body]
Works! PHP!
<?php print
$entity->field_locator['und'][0]['value'];
?>
Doesn't Work!? PHP!
<?php print
$entity->field_locator['und'][0]['value'];
" - ";
$entity->body['und'][0]['value'];
?>
Works! PHP!
<?php print
$entity->field_locator['und'][0]['value'];
?>
<?php print
" - ";
?>
<?php print
$entity->body['und'][0]['value'];
?>
If you want to concatenate two strings in php, you have to use the "." operator. So, for printing many variables on the same line, you have to concatenate them:
<?php print $entity->field_locator['und'][0]['value'] ." - " . $entity->body['und'][0]['value'];
?>
I hope it help!
Is there any difference between the following 2?
1 separate php code from html
<html>
<body>
<?php // php code 1 ... ?>
<div> ... </div>
<?php // php code 2 ... ?>
<div> ... </div>
<?php // php code 3 ... ?>
</body>
</html>
2 everything inside php
<?php
echo "<html>";
ehco "<body>";
// php code 1 ...
echo "<div> ... </div>";
// php code 2 ...
echo "<div> ... </div>";
// php code 3 ...
echo "</body>";
echo "</html>";
?>
Which is faster?
It is not the way to increase the speed. If you are not satisfied with your app performance - take profiler and find the slowest part. After that - optimize that slowest part.
The way "I optimize the things that it is easy to optimize" is always the worst.
The first one is faster because interpreter will take care only about the code inside the tags.
The second one should not be use, double quotes are interpreted to see if there is a variable inside. You should always use simple quote when you don't want string to be interpreted.
The usual usage is what you listed in the first form, although in some cases, such as a helper function to generate <a href="..." ... >link word</a>, then you will generate HTML inside PHP code. Or if you have a function that generates a table, or an ul with many li printed out with data from inside an array or hash.
Whatever performance difference you'll find is moot and academic. Choose the first form. The second form isn't future-proof. A simple change in the layout of the HTML page will require a software engineer. The first will just require a creative designer.
With an opcode cache installed on the server (see: APC, eAccelerator), it doesn't matter either way, as the page only has to be interpreted the first time it's accessed.
Performance:
Perhaps the 2nd example would be slightly slower because it does more function calls & also when a string is inside double quotes then the interpreter will look for variables to substitute and escape sequences, eg. \n
PHP blocks also need to be parsed. This may be irrelevant is your script is pre-compiled / running on an accelerator.
Formatting:
1st example will produce HTML code automatically formatted with indentation.
The 2nd example will produce code that's all on one line. Not really an issue as this can be corrected.
Readability:
Perhaps the first example is more readable. Eg. IDE can highlight syntax for HTML and separately for PHP
Others:
2nd example would probably be more preferred choice if the code is in a framework and markup gets extracted in to smaller function(s), sub-classed, etc?