What's the correct method using PHP & HTML [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have created many sites that requires php, html and css. They all work fine but i'm now thinking if all that time i do it in a wrong way.
Usually, first i build the site template and styling and then i code the php.
Then i just include the php functions etc in the HTML.
For example take a look of a table that lists some posts (index.php):
<div class="posts">
<h1 class="content-title">New Posts</h1>
<?php
$rows = list_posts();
while ($row=mysql_fetch_array($rows)) {
echo "
<div>
<img class='post-avatar' src='img/icon_newsletter.jpg'>
<h2 class='post-title'>".$row['post_title']."</h2>
<p class='post-meta'>
Από <a href='#'>".$row['post_user']."</a> | ".$row['post_date']." | <a class='post-views' href='viewpost.php?id=".$row['post_id']."#comments'>Comments: ".total_comments($row['post_id'])."</a>
</p>
<p>
".substr($row['post_body'], 0, 180)."...
</p>
<img class='post-icon-read' src='img/read.png' /> <a href='viewpost.php?id=".$row['post_id']."'>Συνέχεια άρθρου..</a>
</div>
";
}
?>
</div>

There is room for improvement.
Keep the HTML within the PHP. It iss not personal opinion, there are technical reasons.
When you do this:
html
<?php PHP ?>
html
<?php ?>
html
<?php PHP ?>
html
There is overhead within PHP when you switch back and forth between HTML mode and PHP Mode. And it makes you look like a Word Press Hack.
A few things:
- Heredoc syntax
- Numeric Arrays
- escape quotes
Start with the basic template:
echo <<<EOT
// Top of page
EOT;
while ($row=mysql_fetch_array($rows), MYSQL_NUM) {
}
echo <<<EOT
// bottom of page
EOT;
The reason to use MYSQL_NUM is so the column values can be use without concatenation.
Instead of
<a href='#'>".$row['post_user']."</a> | ".$row['post_date']." | <a class='post-views' href='viewpost.php?id=".$row['post_id']."#comments'>Comments: ".total_comments($row['post_id'])."</a>
you can do this:
$comment = total_comments($row[2]) ;
echo "$row[0]$row[1]<a class=\"post-views\" href=\"viewpost.php?id=$row[2]#comments\">Comments: $comment</a>";
The backslash will escape the double quotes within double quotes. Quote marks do not need to be escaped within Heredoc.
Single dimension Numeric arrays can be used within double quotes and within Heredoc.
Top of page:
echo <<<EOT
<!DOCTYPE html>
<html lang="en"><head><title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Edit Rotation Diet</title>
<style type="text/css">
</style></head>
<body><div id="page">
EOT;
Bottom of page:
echo <<<EOT
<script type="text/javascript">//<![CDATA[
//]]>
</script></body></html>
EOT;
Let's say the page content is a table
<body><div id="page"><table>
EOT;
while ($row=mysql_fetch_array($rows), MYSQL_NUM) {
echo <<<EOT
<tr>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
<td>$row[3]</td>
</tr>
EOT;
}
echo <<<EOT
</table>
<script type="text/javascript">//<![CDATA[
Indentation of HTML along with PHP is wrong. You should think about how the HTML is going to look when someone views the source. View the source on most any Word Press page.. Looks like crap.
The blank line between the echo and first html gives you a line feed.
When you echo HTML like you did it ends up looking real bad when you view the source, like Word Press.
Personally, I do not like a four space indent. Before you know it your code is hidden beyond the right border. I use two spaces.
I think this is ugly and a waste of vertical space:
if($x = 1)
{
echo '<p>one</p>';
}
else
}
echo '<p>two</p>'
}
I think this is plenty clear. Without having excessive vertical scrolling/
if($x = 1){
echo '<p>one</p>';
}
else{
echo '<p>two</p>
}

Related

PHP - replacing dot into arrows

I have this data in my database that i fetched:
As you can see i store an html template in my database.
This is the code i used to output that html:
$php = Blade::compileString($template->content);
dd($php) //i used laravel framework, btw.
Then this is the output:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Exmaple.com</title>
<style>
</style>
</head>
<body>
<div class="account-details">
<b>Account Name</b>: <?php echo e(company.name); ?><br>
<b>Plan</b>: <?php echo e(plan.name); ?><br>
<b>Source</b>: <?php echo e(source.name); ?><br>
<b>Source Type</b>: <?php echo e(source.source_type.name); ?><br>
<br>
</div>
<div class="welcome" style="font-family:Arial;font-size:small">
Hi <?php echo e(user.first_name); ?>,<br>
<br>
There seems to be a problem blah blah blah<br>
<br>
Details of the problem are:<br>
<?php echo e(sourceMessage); ?><br>
<br>
You can check and update the source here:<br>
https://example.com<br>
<br>
<br>
<span style="font-size:12.8px">
Kind regards,<br>
<br>
Test Team<br>
<br>
Email: example.com<br>
Website: example.com<br>
</span>
</div>
</body>
</html>
I want to change the .(dot) into -> so in this example, some of text will output like:
from <?php echo e(company.name); ?> to <?php echo e(company->name); ?>
from <?php echo e(source.name); ?> to <?php echo e(source->name); ?>
So i think if it's in a <?php echo e(whatever); ?> that's the time we check and replace the . with -> ?
I think this can be done by RegEx but I'm not expert on that.
The reason why i wanted to replace it is because i am getting a template from an email service then returns ., so i wanted to replace that with -> because I know PHP reads -> in accessing objects rather than ..
You can use preg_replace to look for pieces of code matching <?php ... e(f) and replace the .s in f with ->:
$html = preg_replace_callback('/(<\?php\s+.*?\be\()([^)]+\))/',
function ($m) {
return "{$m[1]}$" . str_replace('.', '->', $m[2]);
},
$html);
Note we use a callback as it makes it easier to deal with replacing a.b.c with a->b->c. Also, to really look like PHP, you need to add a $ at the beginning of the variable name, which this code does. If you don't want it, just change {$m[1]}$ to {$m[1]}
Demo on 3v4l.org
If you're doing that on a editor like VS code or sublime, you just need to replace the function e usage parts.
CTRL + H
(In sublime or VS code) to open up replace dialog.
Make sure the Regex option is clicked.
This would do the trick;
Search (e\(.+)\.(.+\))
Replace $1->$3

How can I use 20 lines of HTML code in PHP without breaking up the PHP tags (<?php ?>)? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I wanted to create a form and some other HTML inside some PHP code but without breaking up the tags.
Example:
function paypal() {
// HTML code
}
So is there a way I can use a block of HTML code in PHP?
You can use heredoc syntax.
For example, as an alternative to this:
if ($something) { ?>
<div>
</div>
<?php }
You can do this:
if ($something) {
echo <<<HTML
<div>
</div>
HTML;
}
Interestingly enough, I saw someone doing just that earlier today. Here's an example solution using heredoc syntax:
echo <<<ENDFLAG
... some text/html here ...
... more lines of HTML ...
ENDFLAG;
ENDFLAG can be anything. Here's more info: http://www.tuxradar.com/practicalphp/2/6/3
I'm guessing what you are trying to is change something like this:
<?php //some php code here ?>
<p>Some html code here</p>
<br>
<p>Some html code here</p>
<?php //some other php code here ?>
etc...
You can just do
<?php
//some php code here
echo '<p>Some html code here</p>';
echo '<br>';
echo '<p>Some html code here</p>';
//some other php code here
?>
Your function can do the same...
<?php
function paypal() {
//Do some fancy php
$i = 'paypal';
$retVal = '<p>' . $i . '</p>';
return $retVal;
};
echo paypal();
?>
You can do it with echo, just put all the lines after an echo and it will work perfectly. example :
<?php echo ' <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>';
?>
<?php
//your php code
echo '<html></html'; //your html code
?>
But it's very bad way to use html code in php with echo.
I recommend you to use html templates (mustache - https://github.com/bobthecow/mustache.php)

Posting html code with php fails at style attribute and spaces

I'm using ACE Editor for a website which has been developed by Codeigniter framework. The problem is that after submitting the form, some tags attributes stripped.
HTML:
<form enctype="multipart/form-data" method="post" action="<?php echo site_url( 'admin/slider/populateFile')?>">
<div id="e1" style="display: none;">
<?php if(isset($sliderHTML)) { echo $sliderHTML; } ?>
</div>
<textarea class=" form-control" id="editorTextarea" name="sliderHTML" type="text" rows='20' wrap="off">
<?php if(isset($sliderHTML)) { echo $sliderHTML; } ?>
</textarea>
<pre id="editor"></pre>
</form>
PHP:
function populateFile()
{
$sliderHTML = $this->input->post('sliderHTML');
//echo $sliderHTML;
$filePath = 'application/views/admin/slider/sliderHTML.txt';
write_file($filePath, $sliderHTML, 'w');
redirect('admin/slider', 'location');
}
This is an example of what I'm trying to write in the code editor:
<img class="ls-l" style="top:195px;left:50%;white-space:nowrap;" data-ls="offsetxin:0;delayin:1720;easingin:easeInOutQuart;scalexin:0.7;scaleyin:0.7;offsetxout:-800;durationout:1000;" src="http://localhost:8080/afa/application/views/images/upload/slider/4978d-s1.jpg" alt="">
<p class="ls-l" style="top:150px;left:116px;font-weight: 300;height:40px;padding-right:10px;padding-left:10px;font-size:30px;line-height:37px;color:#ffffff;background:#82d10c;border-radius:3px;white-space:nowrap;" data-ls="offsetxin:0;durationin:2000;delayin:1500;easingin:easeOutElastic;rotatexin:-90;transformoriginin:50% top 0;offsetxout:-200;durationout:1000;">
FEATURES
</p>
But, the output will be like:
<img class="ls-l" data-ls="offsetxin:0;delayin:1720;easingin:easeInOutQuart;scalexin:0.7;scaleyin:0.7;offsetxout:-800;durationout:1000;" src="http://localhost:8080/afa/application/views/images/upload/slider/4978d-s1.jpg" alt="">
<p class="ls-l" 300;height:40px;padding-right:10px;padding-left:10px;font-size:30px;line-height:37px;color:#ffffff;background:#82d10c;border-radius:3px;white-space:nowrap;" data-ls="offsetxin:0;durationin:2000;delayin:1500;easingin:easeOutElastic;rotatexin:-90;transformoriginin:50% top 0;offsetxout:-200;durationout:1000;">
FEATURES
</p>
Notice that style attribute of img has been stripped, and this happens also for <p> but it stops on the space after font-weight:. I don't know why.
Any Ideas?
EDIT: Finally, I knew that this has nothing to do with the code editor. The problem was with xss_filtering in Codeigniter and this answer works for me. :)
I am not familiar with Ace in particular (i like Wysihtml5), but I think they have something in common.
Wysihtml5 strips html (you can select which). It makes sure the html output is clean.
In short, it's a function and apparently style is not permitted. You should permit that (if it has the option to)
You should escape value of $sliderHTML with htmlspecialchars before adding it to the document, otherwise it will create actual tags and break your page.
try putting "</textarea><script>alert('all your passwords belong to us')</script>" in place of $sliderHTML

How do I insert an HTML page using PHP?

I wanted to know, is there any way to insert an HTML page into PHP without using the include function? I do not want to use an external html file, I want to write the html coding directly into the php coding.
Thanks for your help!
Interleave it:
<?php
// Some php code.
?>
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>Header</h1>
<?php /* More php code. */ ?>
<p>Blah!</a>
</body>
</html>
<?php /* Even more php. */ ?>
From a best practices point of view, though, avoid doing this - having business logic (PHP) and presentation (HTML) in the same place makes maintaining harder.
EDIT: To address your comment. You can either do it the same way, or use echo:
<?php if (x == 5) { ?>
<p>Blah!</a>
<?php } else {
echo '<p>Bleh</p>';
} ?>
If you need to include snippets of HTML based on conditions, you can interleave code like this. In this case it's convenient to use the alternative syntax for loop controls
<?php if ( $var ): ?>
<html>
<title>YAY</title>
</html>
<?php endif; ?>
so the code is clearer to read and you retain HTML syntax coloring (if your editor supports it).
It is very bad habit to mix HTML and PHP (for more than just output control), but here you go:
$html = "<div>This is HTML</div>"
echo $html;
or Heredoc syntax:
$html = <<<EOF
<div>
<p>
Some longer HTML
</p>
</div>
EOF;
echo $html;
or using alternative syntax for control statements if the output depends on some condition (or if you loop through an array etc.)(which is far better than building HTML with strings):
<?php if($foo): ?>
<div> Some HTML output </div>
<?php else: ?>
<div> Some other HTML </div>
<?php endif; ?>
or just
<?php //PHP here ?>
<div>HTML</div>
<?php //more PHP ?>
<div>more HTML</div>
<?php //even more PHP ?>

How to output formatted HTML from PHP?

I like to format all my HTML with tabs for neatness and readability. Recently I started using PHP and now I have a lot of HTML output that comes from in between PHP tags. Those output lines all line up one the left side of the screen. I have to use /n to make a line go to the next. Is there anything like that for forcing tabs, or any way to have neat HTML output coming from PHP?
If there is relative bigger blocks of html you are outputting then HEREDOC syntax would help you format the html the way you want witout bothering much about echo tabs using php.
$html = <<<HTML
<html>
<head><title>...</title></head>
<body>
<div>$phpVariable</div>
</body>
</html>
HTML;
If you use some tool to parse your html , remember it will also add an extra overhead of processing and data payload for each request so you might want to do it only for debug purposes.
There's the tidy extension which helps you to (re-)format your html output.
But it has a little price tag attached to it. Parsing the output and building an html dom isn't exactly cost free.
edit: Could also be that you're simply looking for the \t "character". E.g.
<html>
<head><title>...</title></head>
<body>
<?php
for($i=0; $i<10; $i++) {
echo "\t\t<div>$i;</div>\n";
}
?>
</body>
</html>
or you nest and indent your php/html code in a way that the output is indented nicely. (Sorry for the ugly example:)
<html>
<head><title>...</title></head>
<body>
<?php for($i=0; $i<10; $i++) { ?>
<div><?php echo $i; ?></div>
<?php } ?>
</body>
</html>
<html>
<head><title>...</title></head>
<body>
<?php for($i=0; $i<10; $i++) { ?>
<div><?php echo $i; ?></div>
<?php } ?>
</body>
</html>
Actually this is a good example but in this case it's better to use Alternative way of doing things
<html>
<head><title>...</title></head>
<body>
<?php for($i=0; $i<10; $i++): ?> // notice the colon
<div><?php echo $i; ?></div>
<?php endfor; ?>
</body>
</html>
Reference

Categories