Sorry if this a completely nube sounding questioning. I'm new to the PHP syntax conventions, so I'm not entirely sure what I should be looking for.
The book I've got gives the following example as a conventional php block in html code.
<?php
//... some code ...
?>
I get that, but the confusing bit is that the example code I'm looking at some examples from xampp (e.g. the CD collection source code) doesn't seem to follow the same convention.
Instead, the example code reads more like this.
<? include("langsettings.php"); ?>
<?
//... some code ...
?>
Are the two forms just equivalent for all intents and purposes or did I completely miss something crucial to an intro to php here?
Also why doesn't php use closing tags (or does it and have I just not seen them)? I guess I'm thinking of javascript with the closing tags, but I guess either way, they're codebases in and of themselves so it works. It just seems like html has symmetry at the core of it's syntax, but php syntax sort breaks from that symmetry, which is odd.
Thanks for your time.
The only difference between these is that the second requires the setting short_open_tag to be enabled (which is off by default in new PHP version).
<?php regular open tag.
<? Short open tag (disabled by default)
Beyond this, the placement of something like <? include("langsettings.php"); ?> on its own line enclosed in its own pair of <? ?> is really a matter of style specific to the source you found it in. Different projects use very widely different conventions, and PHP books each tend to adopt their own convention.
PHP doesn't unfortunately have any real specific coding conventions such as you might find in languages like Ruby, Java, or Python, which is, in my unsolicited opionion, one of PHP's chief failings as well as one of its greatest flexibilities.
Now, as to whether or not short open tags are good practice for use in a modern PHP application is a separate issue entirely, which has been discussed at great length here.
The two forms are equivalent, but you will find that the shortcode can give you issues. I would stick with the regular tags:
<?php
and the block closed by
?>
Edit: The closing tag is optional, but only if you want everything after the opening tag to be interpreted as PHP until the end of the page.
Anything outside those blocks are interpreted as HTML, so you have to ensure that you watch where you are opening and closing.
For example:
<body>
<h1> The Heading </h1>
<p>
<?php
echo "This is the Content";
?>
</p>
</body>
Will work, and output the php generated string into your paragraph tag.
PHP is similar to javascript in that it doesn't have 'open' and 'close' tags, but rather utilize a semicolon to declare the end of a particular php statement.
include "file1.php";
include "file2.php";
If you forget the semi colon, like so
include "file1.php"
include "file2.php";
That will generate an error.
The closing tag for a PHP block is ?>. The closing tag is not required, but it can be used if you want to interpret part of your page as PHP and other parts as literal HTML. People sometimes do this if they want to do some PHP processing at the beginning of the page, then write an ordinary static HTML page with just a few PHP variables echoed into it.
In other words, text that comes after a <?php tag and before a ?> tag is interpreted as PHP. If the closing tag is omitted, then all text between the opening php tag and the end of the page is interpreted as PHP.
One exception to this is that if you open a conditional statement inside a php block, then close the php block, ALL the following text on the page will be subject to that conditional, until you start a new php block and close the conditional statement. For example, if you run the script:
<?php
if(1==0) {
?>
<B>conditional HTML</B>
<?php
}
?>
the HTML between the two PHP blocks will not appear on the page.
Note that different PHP blocks are all part of the same script. Variables, functions, and classes defined in one block can be used by other blocks on that page, and so forth.
PHP starting tag is <?php and closing tag is ?>.
If there are short tags allowed on server you can use <? ?> syntax also.
You can read more about that on Offcial PHP Documentation
Best regards,
Tom.
Issues regarding short version long open tags have already been covered.
I'll just mention one common gotcha in the question that hasn't been mentioned yet in these answers.
Compare the following:
<?php
/*
* Some comments here, (c) notice, etc.
*/
header("Content-type: text/html");
...
vs
<?php
/*
* Some comments here, (c) notice, etc.
*/
?>
<?php
header("Content-type: text/html");
...
The second one doesn't work.
Why?
There's a blank line of non-PHP code between the first block of PHP and the second. In a server environment that is not using output buffering, the blank line signals to PHP that the headers are all done, and anything from this point on is part of the HTML (or whatever) being sent to the browser.
Then, we try to send a header. Which produces:
Warning: Cannot modify header information - headers already sent
So ... be careful of your blank lines. A blank line INSIDE your PHP is fine. OUTSIDE your PHP, it may have nasty side-effects.
Related
I was reading PHP Manual and I come across following text paragraph :
Line feeds have little meaning in HTML, however it is still a good
idea to make your HTML look nice and clean by putting line feeds in. A
linefeed that follows immediately after a closing ?> will be removed
by PHP. This can be extremely useful when you are putting in many
blocks of PHP or include files containing PHP that aren't supposed to
output anything. At the same time it can be a bit confusing. You can
put a space after the closing ?> to force a space and a line feed to
be output, or you can put an explicit line feed in the last echo/print
from within your PHP block.
I've following questions related to the text from above paragraph :
What does exactly mean by 'Line feeds' in HTML?
How to add them to the HTML code as well as PHP code and make visible in a web browser? What HTML entities/tags/characters are used to achieve this?
Is the meaning of 'Line feed' same in case of HTML and PHP? If no, what's the difference in meaning in both the contexts?
Why the PHP manual is saying in first line of paragraph itself that? What does PHP Manual want to say by the below sentence?
"Line feeds have little meaning in HTML"
How can it be useful to remove a linefeed that follows immediately after a closing tag ?> when someone is putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything?
Please someone clear my above mentioned doubts by giving answer in simple, lucid and easy to understand language. If someone could accompany the answer by suitable working code examples it would be of great help to me in understanding the concept more clearly.
Thank You.
What does exactly mean by 'Line feeds' in HTML?
It is a general computing term.
The character (0x0a in ASCII) which advances the paper by one line in a teletype or printer, or moves the cursor to the next line on a display.
— source: Wiktionary
How to add them to the HTML code
Press the enter key on your keyboard. Note that (with a couple of exceptions like <pre>) all whitespace characters are interchangeable in HTML. A new line will be treated as a space.
as well as PHP code
Ditto … or you could use the escape sequence \n inside a string literal.
and make visible in a web browser?
The material you quoted is talking about making source code look nice. You generally don't want line feed characters to be visible in a browser.
You could use a <pre> element instead.
Outside of <pre> elements (and the CSS setting they have by default) you can use a space instead of a new line for the same effect in HTML.
What HTML entities/tags/characters are used to achieve this?
… but the advice given in the last sentence of the material you quoted is probably a better approach.
'Lines feed' exactly means a 'New line' both in Html and Php, only the syntax is different.
In case of Html tag, you can use <br> or <br/> tag for a Lines feed. Basically, this tag shows a new line in the output of the Html attribute block, while running through the browser.
You can take the following example for <br> tag:
<html> <body>
<p> To break lines<br>in a text,<br/>use the br element. </p>
</body> </html>
Output:
To break linesin a text,use the br element.
In case of Php, you can use '\n' for a lines feed.
If you are using a string in Php, then instead of writing,
echo "New \nLine";
you can use nl2br() function to get line break, like:
echo nl2br("New \nLine");
Output:
New
Line
I've been using BeautifulSoup to convert relative URLs in some ancient HTML files from an archival site to absolute URLs (mostly so they can be targeted better by .htaccess rules). This part I've got down: search for certain tags and their atts, use urllib.parse.urljoin (this is Python3) to correct. Fine.
However, there are also some .php files in this collection, from later years of this website. They mostly use 3-5 lines to include other .php files, then the rest is HTML, though there are some exceptions.
Problem: BeautifulSoup parsers try to interpret what's between <?php ?> tags. In fact, there appear to be cases where they just throw out just the angle brackets, but leave the question marks -- behaviour which I hackishly addressed thus:
for c in soup.contents:
c = str(c) # previously a BeautifulSoup Tag
# I don't need soup after this point, hence not reconstructing contents
c = ('<' if c.startswith('?') else '') + c
c = c + ('>' if c.endswith('?') else '')
But in any case, I noticed that whole <?php ?> tags were often mangled, in different ways depending on the parser. For example, the html5lib parser takes these lines:
<?
//echo "BEGIN PAGE: " . $_SESSION["i"]."<br>";
include ('util.php');
And interprets the tag as ending at the > that closes <br>.
What I'd prefer to happen is for the php tags to be left alone. (Obviously, in an ideal world a parser would read through them and work on any inner HTML, but that seems like asking for too much!)
Possible solutions
Skip .php files and only work with .html -- the work being done is not essential, just an optimization, so no great loss will ensue;
Find a BeautifulSoup parser not mentioned in the docs that handles these cases better;
Pre-parse the text myself, extract all <?php ?> blocks, and reinsert after the work with BeautifulSoup is done, taking care to recall where they should fall (potentially very difficult if any of these thousands of files have <?php echo 'foobar' ?> in the middle of HTML lines, for example)
Similarly to the above, programmatically protect all <?php ?> tags from the parser, e.g. inserting HTML comments around them, and then remove the protection after the soup
To answer my own question... :)
I used solution #4: programmatically protect all <?php ?> tags from the parser by inserting HTML comments around them. The parser then skips interpreting whatever's inside a comment. Later, when using soup.prettify() or soup.contents, the output can just be given a straightforward replace <!--<? with <? and likewise for closing tags.
Note that this doesn't work for PHP tags used to generate dynamic content inside certain HTML tags, e.g.:
<a href= "<? echo foo_bar(); ?>" >
The current versions of html.parser, lxml, and html5lib all interpret this as a series of nonsense attributes of <a>, even when the PHP tags are enclosed in HTML comments. In such cases I manually extracted the tags with regex to solve my issue instead.
A simple code sample <?echo '<?this text is ignored?> this text is shown';?> writes just "this text is shown" and ignores the text inside php tags despite it's a string.
Unfortunately, I can't find any explanation in specs, so, how to handle this? I know, that we can escape special symbols and everything goes all right, but what's the matter of such php behaviour?
PHP 5.3, local server.
This behaviour prevents from reading lines from php files inside zip via zip_entry_read() and usage of eval() then.
PHP is not ignoring the text inside your inner <? .. ?>, your browser is ignoring it.
Anything you put inside of angle braces is an HTML tag as far as your browser is concerned.
I'm not sure what you were expecting, but if you want the tags to show in the browser you have to replace the opening < with <
If you actually wanted to execute the code inside the inner php tags you can just go ahead and remove the inner tags as they are redundant.
I use notepad++ and I like it
I specifically want it to do this :
Close automatically HTML tags. (eg. </div>)
Close tags after starting with proper indention for .jsp, .asp, .php files. (eg.<% %>, <?php ?>)
Put a semicolon at the line end by default (whenever I start a new line inside <?php ?>)
For (1), it is really frustrating for me, when I want to write HTML tags in php files.
I upgraded to 6.5.1, and tried the TextFX, but it works only with files which have the extension .html or .htm
Could someone please guide me in achieving these features?
Regarding auto-closing html tags, for me only having html as the language didn't do the trick.
(This answer is incomplete, but is too large for a comment given the images.)
Changing the auto-complete preferences, as below, worked:
Settings > Preferences
Auto-Completion tab > Auto-Insert section > html/xml close tag
I use Notepad++ v6.5.2
If you are editing a PHP file and want it to auto-complete the HTML tags, in addition to turning on "Auto-insert HTML/XML tags" in Preferences, you have to change the programming language to HTML while editing that file.
In Notepad++, go to the Language menu, and find HTML and click on it.
This will set the file's language to HTML so that auto-complete tags will work in a PHP file.
Even with the language set to HTML, it still highlights anything in <?php ?> tags as PHP code, and it does not affect auto-closing of brackets, if you have that enabled.
You must have Auto-Insert html/xml close tags on, as mentioned in Noha's answer.
Settings > Preferences
Auto-Completion tab > Auto-Insert section > html/xml close tag
For 2. you can't enter custom pairs for auto-complete (in the Auto-Insert section) with two characters. So this is not possible without a plugin. If I find one, I will update my answer.
However, for auto closing code with semicolon ";", you can use this option and "trick" Notepad++ to not put it on every line inside a php tag (which I don't believe is a good use case), but put it only when needed. I tested with ; and ; as opening and closing tags, which essentialy gives you what you need (without the php tags check though) and it's not so nice. But if you use an opening tag of "$" and a closing one ";", then you can get an auto-close functionality whenever you use a variable (which will mean you are writing code).
Please note that using < and > or any other similar pairs will break other auto-complete functionality (including the auto-close html tags). This is certainly bad, because it would be nice to have both <> auto close and html tags auto-close.
Is it possible to detect text outside php open and close tags. Most of the time there is text outside these tags as a result of typo. Since it is "syntactically" correct to have text outside these tags, php -l exits with a success
some random unwanted text due to a typo
<?
//some useful code
?>
I want to detect that there is some text before php open tags
Anything outside of the PHP tag itself would likely fall into DOM level interactions in a client-side language like JavaScript, and even then once the page renders the php tags don't exist to the DOM as they are rendered in there respective HTML varations in a matter of speaking. If you wanted to to actually find something outside of <? /*code*/ ?> you could look into http://php.net/manual/en/function.file-get-contents.php and open the file server side, but you would have to build up some form of parser logic that would look for the php tags and see if there is anything above or below (outside) of them that is out of place.
Alternatively you could also double check your work to ensure the tags are opened and closed properly and nothing is outside of them like what your looking for..
On a side note is there anything your attempting to figure out as to why you would actually want to see whats outside of the PHP tags?