A different angle on How to write html code inside php? - php

We write PHP code inside the HTML code via <?php ... ?> tags. So normally it would not make sense to write HTML code inside PHP code that is already inside HTML code, if you can just exit the PHP for the lines you need. But what if you need the HTML code in the same line as you have the PHP code?
My example would go like this:
<div>
<?php ($bool) ? <script>...</script> : <script></script> ?>
</div>
Is this:
<div>
<?php if($bool): ?>
<script>...</script>
<?php else: ?>
<script>...</script>
<?php endif; ?>
</div>
the only way?
Note: instead of <script> you could have <h1>, <strong>, <title> or any other "one-liner".
Thank you in advance.

Sure, alternative syntax would be the way to go when you have multiple lines of HTML, as you already stated...
However, for one liners, you can shorten <?php echo '...' ?> with <?= '...' ?> and wrap your HTML within single or double quotes, depending if you are already using double quotes within your HTML syntax. You may also escape them if you like, but that'd be messy.
<div>
<?= ($bool) ? "<script>...</script>" : "<script></script>" ?>
</div>

In order to print any string into your html code from PHP snippets use echo function.
http://php.net/manual/en/function.echo.php

So you just need to add echo
<div>
<?php
if($bool) {
echo '<script>...</script>';
} else {
echo '<script>...</script>';
} ?>

Stumbled upon this and decided to answer my own question just to point other newbies in the right direction.
Important note: Nowadays I'm using Laravel Framework and if you don't know it, you should definitely get to know it (there are alternatives though).
But I started following MVC architecture strongly even before that. So even before Laravel's Blade templates, my views looked something like the following.
<html>
<body>
<?php if ($isUserAuthenticated) : ?>
<div>
<span>Welcome <?= $username ?>
</div>
<?php else : ?>
Login
<?php endif ?>
</body>
</html>
As you can see there is absolutely no data manipulation in the view.
I also tried my best not to store any HTML strings into variables, but sometimes it makes for less code, so I did something like the following.
$alert = match($errorCode) {
1 => <<<HTML
<div class="alert alert-danger">Big error</div>
HTML,
2 => <<<HTML
<div class="alert alert-warning">Small error</div>
HTML,
default => ""
};
That way I can keep syntax highlighting (in VSCode) for HTML.
Note: match expression is new in PHP8, but you could achieve the same before with a switch statement.

Related

PHP How To Display HTML+PHP Code Stored in MySQL

I am trying to store HTML and PHP in a MySQL text field and display it in PHP.
When it displays on site it renders as commented out tags:
<!--?php
if(isset($sp_msg) && $sp_msg != ''){
print '<div-->
This of course screws the whole page up.
How am I supposed to go about displaying this data correctly? I would like to eventually add this to a full functioning CMS so I would like to understand how to do this correctly.
page.php
<?php
require_once('library/autoload.php');
$pid = $_REQUEST['id'];
$page = $ct->get_page_info($pid);
$sp_msg = $page['special_msg'];
require_once('h.php');
?>
<div id="row">
<?php
print $page['page_content'];
?>
</div>
<?php
require_once('f.php');
?>
'page_content' stored in mysql as text
<h3>MY HEADER TEXT</h3>
<?php
if(isset($sp_msg) && $sp_msg != ''){
print '<div>'.$sp_msg.'</div>';
}
?>
<hr>
<p>paragraph text</p>
You need to eval the stored php code. When you print out the string stored in the MySQL you don't run it, you only print it.
<div id="row">
<?php
eval($page['page_content']);
?>
</div>
Warning:
I really don't recommend it. If any suspicious code can be entered into that DB it could cause really big problems. You can't check the PHP code if its not a crypto virus for example. This code will execute anything on the server.
See the PHP manual: eval

Template inheritance and sections without Blade syntax

How to structure view hierarchy without using blade? What are the pure php counterparts of blade directives (i,e #section, #extend , etc)?
Perhaps, something similar to <?php extend('foo') ?>
In Phalcon framework, while it has its own template engine (Volt) all of its template engine is also available in pure PHP syntax.
Since Blade directives just compile to normal PHP, it is technically possible to use the view structuring features without actually using Blade. I don't think it's very pretty though, and I personally would think twice about this decision.
You can find all the PHP code, Blade is compiled to, in this class:
Illuminate\View\Compilers\BladeCompiler
Here are some of them:
#section('content')
<?php $__env->startSection('content'); ?>
#endsection
<?php $__env->stopSection(); ?>
#extends('layout')
This is a bit a tricky one. Usually Blade compiles it and then adds it to a footer variable which is printed at the bottom. So instead of putting it at the top (like you would with #extends) you have to place this at the end of your view:
<?php echo $__env->make('layout', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
#yield('content')
<?php echo $__env->yieldContent('content'); ?>
To put this in a pure PHP way you'll have to check out the storage/framework/cache/views and see what's happening there. Basically, is what Blade compiles to PHP code (instead of using # and with proper function calls).
One way I can think is:
In your template where you use yield:
<!-- template.php -->
<div class="container">
<!-- instead of using yield('container') -->
<?php echo "_yield:container"; ?>
</div>
In your file, instead of using section and stop
<!-- view.php -->
<!-- instead of using extend('template') -->
<?php $templatePath = 'template.php'; ?>
<?php $sections = []; ?>
<!-- instead of using section('container') -->
<?php $currentSectionName = 'container'; ob_start(); ?>
<p>This will be in my container div</p>
<!-- instead of using stop -->
<?php
// get the current html
$sections["_yield:".$currentSectionName] = ob_get_contents();
ob_end_clean();
ob_start();
require($templateName);
$template = ob_get_contents();
ob_end_clean();
echo str_replace($template,array_keys($sections),array_values($sections));
?>
Of course, this approach is simplistic at best. The code provided is not intended as a copy & paste solution, more like the concept.
Everything else is simple:
#foreach($arr as $k=>$v)
...
#endforeach
translates to
<?php foreach($arr as $k=>$v) : ?>
...
<?php endforeach; ?>
That's how it's exactly done by the BladeCompiler. The same is with if and while.
The pure PHP equivalent to Blade is to split your code in sections like header and footer (for example) and then use require in your page to blend those sections in the corresponding place.
<?php
require("template/header.php");
// Here goes the body code
require("template/footer.php");
?>
There is no pure PHP functions that i can think of, to extend a page from a main template, a you do using the yield directive.
Blade compiles into PHP every time and what it compiles is stored in to storage/framework/views/*
The following link is a list of all things blade can compile to, you should be able to extract some knowledge out of this:
https://github.com/illuminate/view/blob/master/Compilers/BladeCompiler.php
The general idea for most templating engine is that they structure your code like so:
if ($condition):
// do stuff
endif;
while ($condition):
// do stuff
endwhile;
foreach ($array as $key => $value):
// do stuff
endforeach;
For further reference, see https://secure.php.net/manual/en/control-structures.alternative-syntax.php
Neither of blade directives is a 'pure' PHP function. PHP functions cannot start with # and all blade directives do. In short, blade directives are shortcuts or synonyms to PHP built-in functions or control structures.
You are free to use any other template engine – it doesn't have to be Blade. Blade is built-in, but you are not locked to it. Just install a vendor package or make your own one, and return your HTML output with response, instead of using View facade.

HTML is still reading php code with <!---->

I have the following problem. I used the following code in my page to ignore some php code, but it seems that over the Thanksgiving weekend there was an update and it is no longer ignoring the code.
<!--
<div class="main">
<div class="main-sub">
<?php include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php');
?>
<div id="mid-top"><img src="" width="990" height="20" alt="Top Spacer"/></div>
<div id="mid_shdw">
-->
The rest of the html code is being ignored, but only php code is not being ignored. I know one of the ways is to include <!-- into the php function. But is there any other way to ignore the php code with the rest of the html code?
This is an HTML comment. It has no effect on the PHP code.
You should use PHP comments:
Block comment:
/*
BLOCK OF COMMENTED CODE
*/
Line comment:
// this is a commented line
The PHP code is interpreted by the server and is calculated "long" before it gets to the users browser. The HTML markup while still on the server, is just text. Only when the HTML arrives at the users browser does it get rendered (or ignored!). So your HTML comments did not matter to the server - it saw PHP code and ran it - the PHP interpreter is not programmed to recognize these strange <!-- symbols that you are giving it. ;)
Your PHP code will always be executed because it doesn't know about your HTML code that surrounds it.
The solution, if you your PHP code not to execute is to comment it out:
<!--
<div class="main">
<div class="main-sub">
<?
// php include('http://www.contractorsintelligence.com/contractors-license/includes-
// page-elements/navigation1.php');
?>
<div id="mid-top"><img src="" width="990" height="20" alt="Top Spacer"/></div>
<div id="mid_shdw">
-->
<?php /* comments */ ?>
The PHP is executed before the HTML is processed client-side.
If you want to ignore the PHP code, its your best bet to do it like this:
<?php
/* include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php'); */
?>
Whereas /* starts a comment and */ ends it.
PHP will parse the page before it is sent to the client (or browser). Therefore PHP is not 'interested' in <!-- or --> at all.
On the other hand, if the HTML code that is being included by your call to include() contains further HTML commentary (<!-- or -->) it may close your ignored code before the point you intended it to.
UPDATE
Your overall approach is a bit fuzzy. See here, if you want to use PHP to decide whether to show certain HTML code or not, you don't want to use HTML comments to accomplish that.
Try this instead:
<?php
if($result["r_approved"] != "APPROVED"){
?>
<div class="main">
<div class="main-sub">
<?php
include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php');
?>
</div>
<div id="mid-top">
<img src="https://www.contractorsintelligence.com/images/shadowbg-top.png" width="990" height="20" alt="Top Spacer"/>
</div>
<div id="mid_shdw"></div>
</div>
<?php
}
?>
You php page is executed and everything between <? ?> is executed. Php doesn't care about <!-- --> or any other tag except <? or <?php .
Then the browser doesn't display/load what is inside <!-- -->.
If you want to comment php, use // or /* ... */
<?php /* include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php'); */ ?>
Two things are happening at once which I think might be confusing:
Unless you wrap everything inside the php tags with /* */ or use // that code will be executed because it comes from the server.
The browser is the only one that parses the <!-- -->.
So your server is parsing the php and then the browser is hiding what was parsed.
Solution
<?php // include('http://www.contractorsintelligence.com/contractors-license/includes-page-elements/navigation1.php'); ?>
Thats because the <!-- isn't parsed by PHP, only by the browser. The easiest (but not always best readable) solution is
<?php if (false) { ?>
<b>This html will not be sent to browser</b>
<?php include('this will not be included'); ?>
<?php } // endif ?>

Echo PHP variable with html formatting

What I need to do is echo a PHP variable but It needs to be on the bottom of a certain DIV in my HTML page, not just the bottom of the page. Putting it in that DIV id should cover the formatting because that div is formatted using CSS.
Does anyone know how to do this?
I believe what you are looking to do is something similar to the following.
<div id="divName"><?php echo($variable); ?> </div>
<div><?php echo $variable; ?> </div>
Am I not understanding what you're trying to do or does that work?
You can also write like this:
<?php echo "<div id='idName'> Hello World </div>"?>
<?php echo "<b>This text is in bold.</b>"?>

New(relatively) to code igniter : some basic questions

I'm typing this on an iPad so forgive me if being concise is a bit rude. My question is:
Is it ever ok to have simple logic inside a view? For instance,
<HTML>
<!-- ... Stuff
-->
<?php if($this->session->userdata('authorized'): ?>
<p>You are authorized</p>
<?php else: ?>
<p>You are not authorized</p>
<?php endif; ?> // Question 1, is this the proper use of an endif:?
<!-- .. Stuff
->>
</HTML>
/* Starting to type the rest of message on my laptop. Big thank yous to the coders on
this site who made my pc login transfer my unsaved, half typed iPad post */
The above was just a leftover comment in the code that would have made the limited php use look ugly. I wanted to let it be seen though.
Anyways, on to question #2:
Is it even proper to use a simple conditional like this in a view?
Thanks for reading, and hello again.
In answer to the first question:
That is the proper use of an endif, all is valid and recommended way by codeigniter.
In terms of the second question, this method can be used in a view file; however I would recommend using it in the $data array passed to the page meaning it will be accessed as $authorised; I say this as it will make more sense to a front end designer.
Information on the $data array can be found here, just navigate to "Adding logic to the controller".
I hope this is of help to you.
I recommend you to use differents views in the controller for each case:
// In the controller
if($this->session->userdata('authorized')
$this->load->view('not_autorized.php');
else
$this->load->view('view.php');
So you get clean code an views.
Use the Language class to store your 'You are authorized' and 'You are not authorized' text. Do your session check in the controller, and pass the correct language value to the view in the data array.
Edit: Additional question from STONYFTW:
What approach should one take with a bit of more complex code, such as:?
<?php if(!$this->session->userdata('isLoggedIn')): ?>
<div id="login_form">
<?php echo form_open('login/validateCredentials'); ?>
<?php echo form_input('username', 'Username'); ?>
<?php echo form_password('password', 'Password'); ?>
<?php echo form_submit('submit', 'Log In'); ?>
<div id="login_form_link_container">
<?php echo anchor('login/register', 'Register')." ".anchor('login/recover','Forgot Pass?'); ?>
</div>
</div>
<?php endif; ?>

Categories