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
Related
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"]); ?>
I'm trying to redirect to another php page from sql server fetch array with WHILE loop.
All records are fetched well, but i want to add to the table "delete" link to every fetched record.
I tried the code below separatedly and it works just fine.
The problem is because the code is inside PHP tag and i'm confused with all of the ' ' signs.
while compailing the code below i just can't see nothing (without the "delete" line everything is OK):
while ( $record = sqlsrv_fetch_array($rs, SQLSRV_FETCH_NUMERIC) )
{
$o .= '<tr><td><center>'.$record [0].'</center></td><td><center>'.$record [1].'</center></td>
<td><center>'.$record [2].'</center></td><td><center>'.$record [3].'</center></td>
<td><center>'.$record [4].'</center></td><td><center>'.$record [5].'</center></td>
<td><center>'.$record [6].'</center></td><td><center>'.$record [7].'</center></td>
<td>**<a href="JavaScript:if(confirm('delete record?')==true)
{window.location='phpSQLServerDeleteRecord.php?EventID=<?php echo $record[0];';}">delete</a>**
</tr>';
}
$o .= '</tbody></table>';
echo $o;
Thanks a lot for your help!
The use of single-quotes is creating a syntax error:
'</center></td><td>**<a href="JavaScript:if(confirm('delete record?')==true)
{window.location='phpSQLServerDeleteRecord.php?EventID=<?php echo $record[0];';}">delete</a>**
</tr>'
Since the server-side string literal began with a single quote, as soon as the string contains a single-quote then the PHP engine will interpret that as the end of the string, which then results in a couple of syntax errors here as things intended to be part of the string are interpreted as code.
There are a couple of ways to go about this. One quick fix would be to "escape" the single-quotes which are meant to be part of the string rather than a boundary of the string:
'</center></td><td>**<a href="JavaScript:if(confirm(\'delete record?\')==true)
{window.location=\'phpSQLServerDeleteRecord.php?EventID=<?php echo $record[0];\';}">delete</a>**
</tr>'
Of course, there's still the error that now PHP code (the echo statement) is being emitted as part of a string. You can terminate the string boundaries around that and concatenate the value to the string like any other string concatenation:
'</center></td><td>**<a href="JavaScript:if(confirm(\'delete record?\')==true)
{window.location=\'phpSQLServerDeleteRecord.php?EventID=' . $record[0] . '\';}">delete</a>**
</tr>'
(Note that immediately after the reference to $record[0] there are two single-quotes. One to begin the new string literal and then an escaped one to be the first character in that string literal, since the client-side code will need that single-quote character to terminate its string literal. That's probably the root of your confusion in the matter... These server-side strings aren't just HTML, they're also JavaScript which has its own client-side strings.)
You'll also want to URL-encode that value being emitted as part of a query string (even though it should just be a numeric identifier I suspect, it's still good form):
'</center></td><td>**<a href="JavaScript:if(confirm(\'delete record?\')==true)
{window.location=\'phpSQLServerDeleteRecord.php?EventID=' . urlencode($record[0]) . '\';}">delete</a>**
</tr>'
There are a number of other ways to potentially clean this up. Take a look at the PHP documentation on strings, particularly around the "heredoc" syntax. My PHP is to rusty to whip up an example of that, but I suspect it will end up looking a little cleaner in the resulting code. Either way, it's good to get some practice in the differences between the various ways PHP handle string literals.
I will echo the comment from #mario above but give you an example of how to use Heredoc syntax to make large blocs of text much more readable and easy to work with, as you will not need to mess with escaping quotes at all.
while (...)
{
$o .= <<<EOT
<tr>
<td><center>{$record[0]}</center></td>
<td><center>{$record[1]}</center></td>
<td><center>{$record[2]}</center></td>
<td><center>{$record[3]}</center></td>
<td><center>{$record[4]}</center></td>
<td><center>{$record[5]}</center></td>
<td><center>{$record[6]}</center></td>
<td><center>{$record[7]}</center></td>
<td>**<a href="JavaScript:if(confirm('delete record?')==true)
{window.location='phpSQLServerDeleteRecord.php?EventID={$record[0]}}">delete</a>**</td>
</tr>
EOT
}
Now doesn't that look a whole lot nicer?
Note: brackets around PHP variables are optional. I just like them when using Heredoc as I find it makes it easier to see where your variables are.
Read here for more information on Herdoc syntax:
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
For future readers, please look to answer by #David as well. He does good job of explaining why the OP was having his problem. I really look at this answer as complementary to that one, giving the reader an example of what might be a good way to go about solving the problem.
echo'<img src="'.$row['filename'].'" onmouseover="this.src='.$row['back_filename'].'" onmouseout="this.src='.$row['filename'].'" />';
I'm calling in 2 images from a database using mySql and php, How come this onmousover doesn't work?
ps. I'm calling a path to the image not storing the image in the database itself.
try this
echo'<img src="'.$row['filename'].'" onmouseover="this.src=\''.$row['back_filename'].'\'" onmouseout="this.src=\''.$row['filename'].'\'" />';
You are not providing the needed quotes for the inline javascript, you need single quotes '' around the filename as it is a string, causing whatever the variables hold to be interpreted by javascript as something other than what you expect.
Also use a heredoc to help with preventing errors caused by misquoting and worrying about escaping quotes.
echo <<<END
<img src="{$row['filename']}" onmouseover="this.src='{$row['back_filename']}'" onmouseout="this.src='{$row['filename']}'" />
END;
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'>
I can't really find good guidelines through Google searches of the proper way to escape variables in URLs. Basically I am printing out a bunch of results from a MySQL query in a table, and I want one of the entries in each row to be a link to that result's page. I think this is easy, that I'm just missing a apostrophe or backslash somewhere, but I can't figure it out. Here's the line that's causing the error:
echo " Who Owns It? ";
and this is the error I'm getting:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING
How do I fix this error?
In addition, what are some general guidelines for working with echo and variables in URLs?
echo " Who Owns It? ";
There are two things here that should be changed. For one thing there shouldn't be a / after movies.php. The second is that there aren't any apostrophies around url variables. It should be movie_id=$row['movie_id']. Whenever I use a php variable I usually concatonate it instead of embed it in the quotations. So in the end I'd do something like this:
echo " Who Owns It? ";
The $row['movie_id'] inside the double quoted string is not allowed (especially the single quotes). Either write it without ' or use the curly braces syntax:
echo " Who Owns It? ";
echo " Who Owns It? ";
See variable parsing for further information.
This is a better way:
$movie_id = urlencode($row["movie_id"]);
echo ' Who Owns It? ';
Good luck!
This is a better(er) way:
$movie_id = urlencode($row["movie_id"]);
echo " Who Owns It? ";
Easier to read. Besides the single and double quote speed thing is not much of an issue any more.
Echo or URLs have nothing to do with your problem. It's PHP strings syntax.