Dauntless comments php. Simple commenting system using AJAX. php comment syntax: single line comment

I once wrote about . So, we only considered there " greedy"representatives. However, not always their " greed"It helps us, very often it hurts. A little lower I will show an example where you can clearly see what they sometimes do, and also show how to reduce their ardor and make repetition quantifiers are "lazy".

Let's look at a simple and already classic example:

$str = "Small line c bold selection.";
.*<\/b>
echo $result_str;
?>

Perhaps you are expecting something like this: Small bold_highlight here with bold_highlight here". That is, just replacing the content inside the tag<b> to the string we specified along with the tag itself. However, this is not entirely true, since this is where " greed of quantifiers". And as a result, the replacement was not inside each tag<b>, but from the very first opening tag to the very last closing tag. This is what greed is.

Here's how to write this code so that the replacement happens the way we want:

$str = "Small line c bold selection.";
$result_str = preg_replace("/ .*?<\/b>/i", "bold_highlight_here", $str);
echo $result_str;
?>

All we've changed is the regex after the repetition quantifier " .* "question mark, which is just makes the quantifier "lazy". Now the result will be: " A small bold_highlight here with a bold_highlight here. which is what we were trying to achieve.

I really hope you understand the problem. "greed" quantifiers and understand how they work. And also realized how this can be fixed with a simple sign " ? ". This topic is really important, and a huge number of newcomers to regular expressions make the same mistakes related to "greed" of repetition quantifiers, so if you have not yet realized the whole meaning to the end, then re-read the article again.

25.04.2017


Hello!
We continue to learn the basics of PHP from scratch!
In this lesson I will tell you what a comment is in PHP and in practice we will try to write your comment in the code. But that is not all. I also want to tell you how to comment out the code and why it should be done at all.

What is a comment inPHP
Comment inPHP is a php-developer hint for quick orientation in the code, as well as for editing.

A comment in PHP is not visible to the user who opened the web page for viewing. Even if the user decides to look source page, the comment will still not be visible, as all the php.

PHP code comment

There are 2 types of comments for PHP code:

→ one-liner
→ multiline

⇒ Single line comment for PHP
For a single-line comment, use the characters "//" or "#"

After these characters, everything written on one line will be ignored and treated as a comment.

Subscribe to update"; # subscribe (this is a comment) ?>


Subscribe to update

⇒ Multiline comment for PHP
A multiline comment for PHP starts with "/*" and ends with "*/".
Anything between these characters will be ignored and treated as a comment.
A multi-line comment is used if there are several lines in the entry.

On the screen, you will only see the following text:

Hello readers of the blog - site !!!

P.S.: Always comment your code. If you think that you will remember everything that you did in the code in 1-2 years, you are mistaken, the chance is very small. Even if you remember, you will have to spend a lot of time studying - what, where and why ...
Make the future pleasant for yourself - comment out the code and then you will say to yourself "THANK YOU!!!".
Leave a comment in the code, it will take 1 minute of your time, but it will save you a whole day in the future.

Comment out PHP code

Let's say you wrote a php code, but for some reason you need to remove 2 lines from the code.
I'm not in a hurry to remove something from the code, especially if it's php code, I'd better comment it out. And suddenly it will be necessary to return the code. It's easier to uncomment than to write code in a new way.

How to comment out code inPHP
An example with a single line comment:

Subscribe to update"; ?>

An example with a multi-line comment.

Step 1 - XHTML

First, let's look at the comment markup. Given code generated by PHP with class Comment .

demo.php

Username
Jun 30, 2010

Comment text

div avatar contains a link (if the user entered the correct URL when posting the comment) and the avatar image we get from gravatar.com . We'll return to generating the markup in the PHP step. At the end follow div name div time and comment text.

Other important element in XHTML is the comment form. She sends with POST. All fields except URL must be completed.

demo.php

Add a comment

The form is submitted using AJAX. The check is performed in the background submit.php. Each field has a corresponding element label, with attribute set for .

Step 2 - PHP

PHP handles communication with the database MySQL data and generates the markup for the comment. It also gets the end of the AJAX request and inserts the comment data into the table comments.

demo.php

/* / Select all comments and populate the $comments array with objects */ $comments = array(); $result = mysql_query("SELECT * FROM comments ORDER BY id ASC"); while($row = mysql_fetch_assoc($result)) ( $comments = new Comment($row); )

MySQL query select all records from table and populate array $comments class objects comment. This array is output further when the script is executed.

demo.php

/* / Print comments one by one: */ foreach($comments as $c)( echo $c->markup(); )

Each comment has a method markup(), which generates the correct HTML code, ready to be displayed on the page. Following are the class and method definitions.

The class receives a row from the database (obtained using mysql_fetch_assoc()) and store it in a variable $data. It is available only to the class method.

comment.class.php - Part 1

class Comment ( private $data = array(); public function __construct($row) ( /* / Constructor */ $this->data = $row; ) public function markup() ( /* / This method outputs XHTML markup for */ // Set an alias to avoid writing $this->data every time: $d = &$this->data; $link_open = ""; $link_close = ""; if($d["url"] )( // If a URL was entered when adding a comment, // determine the opening and closing link tags $link_open = ""; $link_close = ""; ) // Convert the time to UNIX format: $d["dt"] = strtotime ($d["dt"]); // Needed to set the default image: $url = "http://".dirname($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"])."/ img/default_avatar.gif"; return "
".$link_open." ".$link_close."
".$link_open.$d["name"].$link_close."
".date("d M Y",$d["dt"])."

".$d["body"]."

"; }

The script uses gravatar to represent the avatar in the comments. Gravatar is a very useful service that matches an avatar with an email address. The avatar image can be easily obtained by passing the encoded function md5() your email address on gravatar.com.

The script determines the URL on which it is executed and determines the exact address of the image default_avatar.gif. This image is passed along with the md5 hash, and if no avatar was found for the given email address, then an alternative image will be displayed.

comment.class.php - Part 2

public static function validate(&$arr) ( /* / This method is used to validate data sent via AJAX. / / It returns true/false depending on the validity of the data, and fills / the $arr array, which is passed as a parameter with either data or */ $errors = array(); $data = array(); // Use the filter_input function introduced in PHP 5.2.0 if(!($data["email"] = filter_input(INPUT_POST,"email ",FILTER_VALIDATE_EMAIL))) ( $errors["email"] = "Please enter a valid Email."; ) if(!($data["url"] = filter_input(INPUT_POST,"url",FILTER_VALIDATE_URL))) ( // If an invalid URL was entered in the URL field, // act as if no URL was entered: $url = ""; ) // Use a filter with a callback function: if(!($data["body"] = filter_input(INPUT_POST,"body",FILTER_CALLBACK,array("options"=>"Comment::validate_text")))) ( $errors["body"] = "Please enter comment text."; ) if(!( $data["name"] = filter_input(INPUT_POST,"nam e",FILTER_CALLBACK,array("options"=>"Comment::validate_text")))) ( $errors["name"] = "Please enter a name."; ) if(!empty($errors))( // If there are errors, copy the $errors array to $arr: $arr = $errors; return false; ) // If the input is correct, clean up the data and copy it to $arr : foreach($data as $k=>$v)( $arr[$k] = mysql_real_escape_string($v); ) // email must be lowercase: $arr["email"] = strtolower(trim($ arr["email"])); return true; )

Method validate()(also part of a class) is defined as static. This means that it can be called directly with the construct comment::validate(), without creating a class object. This method validates data that is passed through AJAX.

The method uses new feature filter, which became available in PHP 5.2.0. This way we can easily check and filter the data that is passed to the script. For example, filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL) means we check if $_POST["url"] correct URL. If so, then the function returns the value of the variable, otherwise it returns the value false.

Before using such a function, it was necessary to use regular expressions to validate data (using a series of constructs if). An added benefit is that we get the data before doing any specific transformations.

It is also possible to define a function that will perform additional data modifications.

comment.class.php - Part 3

private static function validate_text($str) ( /* / This method is used as FILTER_CALLBACK */ if(mb_strlen($str,"utf8")<1) return false; // Кодируем все специальные символы html (<, >, ", & .. etc) and convert // the newline character to a tag
: $str = nl2br(htmlspecialchars($str)); // Remove any remaining newlines $str = str_replace(array(chr(10),chr(13)),"",$str); return $str; )

Last method validate_text passed as a return function in two calls filter_input. It converts all special HTML characters, which effectively blocks XSS attacks. Also it replaces newlines with tags
.

submit.php

/* / This array will be filled with either data / that are passed to the script, / or error messages. /*/ $arr = array(); $validates = Comment::validate($arr); if($validates) ( /* All right, insert data into the database: */ mysql_query(" INSERT INTO comments(name,url,email,body) VALUES ("".$arr["name"]."", "".$arr["url"]."", "".$arr["email"]."", "".$arr["body"]."")"); $arr["dt "] = date("r",time()); $arr["id"] = mysql_insert_id(); /* / The data in $arr is prepared for mysql query, / but we need to display it, so / we are preparing all elements in the array: /*/ $arr = array_map("stripslashes",$arr); $insertedComment = new Comment($arr); /* Print the markup of the comment just inserted: */ echo json_encode(array("status "=>1,"html"=>$insertedComment->markup())); ) else ( /* Display error messages */ echo "("status":0,"errors":".json_encode($arr ).")"; )

submit.php fetches a comment from the data via an AJAX request. Validates it and outputs a JSON object containing either XHTML markup with an embedded comment or a list of errors. jQuery use property status to determine what should be displayed - either an error message or adding comment markup to the page.

Below are two examples.

Successful response

( "status": 1, "html": "Html Code Of The Comment Comes Here..." )

Property html contains the comment code.

Error response

( "status": 0, "errors": ( "email": "Please enter a valid Email.", "body": "Please enter a comment body.", "name": "Please enter a name." ) )

When there is an error, jQuery loops through the errors object and displays messages next to the fields that have errors.

Step 3 - CSS

Now that the markup is correctly generated and displayed on the page, we can move on to styling.

styles.css - Part 1

.comment, #addCommentContainer( /* Style for comments */ padding:12px; width:400px; position:relative; background-color:#fcfcfc; border:1px solid white; color:#888; margin-bottom:25px; / * CSS3 rounded corners and shadows */ -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; -moz-box-shadow:2px 2px 0 #c2c2c2; -webkit-box- shadow:2px 2px 0 #c2c2c2; box-shadow:2px 2px 0 #c2c2c2; ) .comment .avatar( /* / The avatar is positioned absolutely. / Outer offset for the comment div /*/ height:50px; left:-70px; position :absolute; width:50px; background:url("img/default_avatar.gif") no-repeat #fcfcfc; /* Center vertically: */ margin-top:-25px; top:50%; -moz-box-shadow :1px 1px 0 #c2c2c2; -webkit-box-shadow:1px 1px 0 #c2c2c2; box-shadow:1px 1px 0 #c2c2c2; )

div .comment and #addCommentContainer have the same style. Several CSS3 rules are used to round corners and reflect shadows.

styles.css - Part 2

.comment .avatar img( display:block; ) .comment .name( font-size:20px; padding-bottom:10px; color:#ccc; ) .comment .date( font-size:10px; padding:6px 0; position:absolute; right:15px; top:10px; color:#bbb; ) .comment p, #addCommentContainer p( font-size:18px; line-height:1.5; overflow-x:hidden; ) #addCommentContainer input, # addCommentContainer textarea( /* Input style */ display:block; border:1px solid #ccc; margin:5px 0 5px; padding:3px; font-size:12px; color:#555; font-family:Arial, Helvetica, sans-serif; ) #addCommentContainer textarea( width:300px; ) label( font-size:10px; ) label span.error( color:red; position:relative; right:-10px; ) #submit( /* "Submit" button " */ background-color:#58B9EB; border:1px solid #40A2D4; color:#FFFFFF; cursor:pointer; font-family:"Myriad Pro",Arial,Helvetica,sans-serif; font-size:14px; font -weight:bold; padding:4px; margin-top:5px; -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px; ) #s ubmit:hover( background-color:#80cdf5; border-color:#52b1e2; )

In the second part, we set the styles for comments and form elements. Let's note the selector input, which highlights elements depending on an attribute type.

Step 4 - jQuery

Now let's move on to jQuery.

script.js

$(document).ready(function()( /* The following code is executed only after the DOM is loaded */ /* This flag prevents multiple comments from being submitted: */ var working = false; /* Catching the form submit event: */ $(" #addCommentForm").submit(function(e)( e.preventDefault(); if(working) return false; working = true; $("#submit").val("Working.."); $("span .error").remove(); /* Submit form fields to submit.php: */ $.post("submit.php",$(this).serialize(),function(msg)( working = false; $ ("#submit").val("Submit"); if(msg.status)( /* / If the insert was successful, add a comment / below the last one on the page with a slideDown effect /*/ $(msg.html).hide ().insertBefore("#addCommentContainer").slideDown(); $("#body").val(""); ) else ( /* / If there are errors, loop through the object / msg.errors and output them to page /*/ $.each(msg.errors,function(k,v)( $("label").append(" "+v+""); )); ) ),"json"); )); ));

We use a function call $(document).ready() A that binds a function to the event . Variable working acts as a flag that signals that an AJAX request is in progress (thus preventing duplication of the same comment).

In the return function for the POST AJAX request, we check the property status to determine if the comment was inserted successfully. If yes, we add the resulting markup to the page after the last comment with animation slideDown.

If there were problems, then we display error messages by adding span error to the corresponding element label(element attribute label contains id input that has an error).

Ready!

Conclusion

To run the script on your server you need to create a table comments in your MySQL database. You can do it with SQL code from file table.sql, which must be entered on the SQL tab in phpMyAdmin. Then you need to set the MySQL database connection parameters in the file connect.php .

Comments in PHP are similar to comments used in HTML. In PHP syntax, comments always begin with a special sequence of characters, and any text that appears between these special characters will be ignored by the interpreter.

In HTML, the main purpose of a comment is to serve as a note to developers who can view your site's source code. PHP comments differ in that they will not be displayed to visitors. The only way to view PHP comments is to open the file for editing. This makes PHP comments only useful for PHP programmers.

In case you forgot or didn't know how comments are made in HTML, see the example below.

php comment syntax: single line comment

Whereas html has only one type of comment, PHP has two types. The first type we will discuss is the single line comment. That is, a comment that tells the interpreter to ignore whatever happens on that line to the right of the comments. To use this comment, use the characters "//" or "#" and all text to the right will be ignored by the PHP interpreter.

Psst...You can"t see my PHP comments!"; // echo "nothing"; // echo "My name is Humperdinkle!"; # echo "I don't do anything either"; ?>

Result:

hello world! Psst...You can't see my PHP comments!

Note that several of our echo commands were not processed because we commented them out with special comment characters. This type of comment is often used to quickly write about complex and obfuscated code, or to temporarily remove a line of PHP code (for debugging purposes).

php comment syntax: multiline comment

Like HTML comments, multiline comments in PHP can be used to comment on large blocks of code, or to write comments on multiple lines. Multiline comments in PHP start with "/*" and end with "*/". Anything between these characters will be ignored.

Result.