Home Backend Development PHP Tutorial 3. Start with an example_PHP tutorial

3. Start with an example_PHP tutorial

Jul 21, 2016 pm 04:08 PM
php and use Example practice tool start us Features of software


3 PHP Practice


Many features of PHP are related to other software or tools. Using the PHP knowledge we have learned so far, we can try to build a simple interactive website. We can learn a lot through this process. Okay, let's now focus on the construction of a typical personal website.



3.1 Plan a site

Generally, a personal site includes a welcome page, a guestbook page, a bookmark link page, a counter, contact information, and even Photo collection and some music files and so on. Let’s start with a title page, a contact information page, and a resume page. We also need standard, universal page headers and footers.



Title page --front.html





Here we have a very simple html file:





<br><br>My personal homepage--Welcome<br><br></TITLE> ;<br><br></HEAD><br><br><BODY><br><br><H1><br><br>My personal homepage<br><br>< /H1><br><br><H2><br><br>Welcome<br><br></H2><br><br><HR><br><br><P> ;<br><br>Welcome to my humble abode, although there is nothing here yet. <br><br></P><br><br><P><br><br>But I hope there will be more soon. <P ALIGN="CENTER"><br><br><SMALL> <I> ;<br><br>Copyright ? Myself, 1999<br><br></I> </SMALL><br><br></P><br><br></BODY> ;<br><br></HTML><br><br><br><br>Contact information page--count.html<br><br><br><br>Similarly we have another one Simple page: <br><br><HTML><br><br><HEAD><br><br><TITLE><br><br>My personal homepage--contact information<br> <br>







My Personal Homepage





Contact Information








You can contact me at 1-800-PHP-INFO










Copyright ? Myself, 1999













3.2 HTML to PHP



As you can see from above, every page has the same header and footer. Writing the same information to each page like above is fine when the workload is light, but imagine how much effort you have to expend when there are more than 100 pages and you need to change their header or bottom for them all? What a tedious and boring task it is to manually change page after page! So we should write PHP header and bottom files for these pages, and then we just need to reference them in every HTML page. We will place these include files in a subdirectory called include. Below we will write the common content of these sites into the file.



Site-wide common variable settings: common.inc


// Site-wide common variables

$ MyEmail = "phptalk@tnc.org";

$MyEmailLink = "$MyEmail";

$MyName = "PHP Talk";

$MySiteName = $MyName."'s Home Page";

?>



General page header: header.inc


// Define the general page header

?>





<br><br><? echo "$MySiteName - $title"; ?><br><br>






















Bottom of the general page: footer.inc


// Bottom of the general page

?>








Copyright ? by



, 1999











New page front.php3:


include("include/common.inc");

$title = "Welcome";

include("include/ header.inc");

?>



Welcome to my humble abode, although there is nothing here yet.





But I hope there will be more soon.




include("include/footer.inc");

?>



New cont.php3:


include("include/common.inc");

$title = " Contact Information";

include("include/header.inc");

?>



You can pass 1 -800-PHP-INFO Contact me




include("include/footer.inc");

?>



Now you can guess the benefits of this arrangement. If you want to change the header or bottom of the page, you only need to change the corresponding file. If you want to change your e-mail address or even your name, just modify the common.inc file. It's also worth noting that you can include files with any file name or file extension into your file, and you can even include files from other sites.



3.3 Counter



Let’s add a counter to the homepage. This example has been told many times, but it is still useful to demonstrate how to read and write files and create your own functions. counter.inc contains the following code:


/*


A simple counter

*/

function get_hitcount($counter_file)

{

/* Return the counter to zero

In this way, if the counter has not been used, the initial value will be 1

Of course you can also set the initial value to 20000 to deceive people

*/

$count=0;

// If the file storing the counter already exists, read Get the content

if ( file_exists($counter_file) )

{

$fp=fopen($counter_file,"r");

// We only took the top 20, I hope your site will not be too popular

$count=0+fgets($fp,20);

// Due to the function fgets( ) returns a string, which we can automatically convert to an integer by adding 0

fclose($fp);

// The file operation is completed

}

//Increase the count value once

$count++;

//Write the new count value to the file

$fp=fopen($counter_file, "w");

fputs($fp,$count);

fclose($fp);

# Return count value

return ( $count);

}

?>

Then we change the front.php3 file to display this counter:


include("include/counter.inc");

// I put the counter value in the file counter.txt, read it out and output it

printf ("%06d

n",

get_hitcount("counter.txt"));

include( "include/footer.inc");

?>

Check out our new front.php3



3.4 Feedback Form



Let’s add another feedback form for your viewers to fill out and e-mail to you. For example, we use a very simple method to implement it. We only need two pages: one to provide the viewer with an input form; the other to obtain the form data, process it, and mail it to you.



Getting form data in PHP is very simple.When a form is sent, each element contained in the form is assigned a corresponding value, and can be used like a reference to a general variable.









In process_form.php3, the variable $mytext is assigned the entered value - very simple! Similarly, you can get variable values ​​from form elements such as list boxes, multi-select boxes, radio boxes, buttons, etc. The only thing you have to do is give each element in the form a name so that you can reference it later.



According to this method, we can generate a simple form containing three elements: name, e-mail address and message. When the visitor sends the form, the PHP page (sendfdbk.php3) that processes the form reads the data, checks whether the name is empty, and finally emails the data to you.



Form: form.php3


include("include/common.inc");

$ title = "Feedback";

include("include/header.inc");

?>



< FORM ACTION="sendfdbk.php3" METHOD="POST">

SIZE="20" MAXLENGTH= "30">

value="Your Email" NAME="email">
















include("include/footer.inc");

?>



Process form: sendfdbk.php3


include("include/common.inc");

$title = "Feedback ";

include("include/header.inc");

if ( $name == "" )

{

// Now I hate anonymous comments!

echo "Duh ? How come you are anonymous?";

}

elseif ($name == "Your name")

{

// This viewer really doesn’t want to be named!

echo "Hello ? Your name is proposed to be replaced with

your actual name!";

}

else

{

// Output a polite thank you

echo "

Hello, $name.




Thank you for your feedback. BR>

$MyName


$MyEmailLink

";

// Finally mail out

mail($ MyEmail, "Feedback.","

Name : $name

E-mail : $email

Comment : $comment

");

}

include("include/footer.inc");

?>



3.5 Simple on-site search engine



PHP can call external programs. In a Unix environment we can use the program grep to implement a simple search engine. We can make it a little more complicated: use a page to output a form for users to enter search strings and output query results.


include("include/common.inc");

$title = "Search";

include("include/ header.inc");

?>



" METHOD="POST">

"

SIZE="20" MAXLENGTH="30">








if ( ! empty($searchstr) )

{

// empty() is used To check whether the query string is empty

// If it is not empty, call grep query

echo "
n";

// Call grep to check Query all files in case-insensitive mode

$cmdstr = "grep -i $searchstr *";

$fp = popen( $cmdstr, "r" ); // Execute Command and output pipeline

$myresult = array(); // Store query results

while( $buffer = fgetss ($fp, 4096))

{

// grep returns this format: File name: the number of lines in the matching string

// Therefore we use the function split() to separate and process the data

list($fname, $ fline) = split(":",$buffer, 2);

// We only output the result of the first match

if ( !defined($myresult[$fname]) )

$myresult[$fname] = $fline;

}

// Now we store the results in the array, we can process and output them below

if ( count($myresult) )

{

echo "
    n";

    while(list($fname,$fline) = each($myresult))

    echo "


  1. $fname : $fline
  2. n";

    echo "
n";

}

else

{

// If not Query results

echo "Sorry. Search on $searchstr

returned no results.
n";

}

pclose($fp);

}

?>


include("include/footer.inc" ; . Contains the current file name.

fgets() reads the file line by line, with a maximum length of 4096 (specified) characters.

fgetss() is similar to fgets(), except that it parses the output HTML tags.

split() has a parameter of 2, because we only need to split the output into two parts. Also need to omit ":".

each() is an array operation function, used to traverse the entire array more conveniently.

The functions of popen() and pclose() are very similar to fopen() and fclose(), except that pipeline processing is added.

Please note that the above code is not a good way to implement a search engine. This is just an example to help us learn PHP better. Ideally you should build a database of keywords and then search them.




http://www.bkjia.com/PHPjc/314675.html

www.bkjia.com

true

http: //www.bkjia.com/PHPjc/314675.html

TechArticle

3PHP Practice Many features of PHP are related to other software or tools. Using the PHP knowledge we have learned so far, we can try to build a simple interactive website. Take advantage of this...

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How Debian improves Hadoop data processing speed How Debian improves Hadoop data processing speed Apr 13, 2025 am 11:54 AM

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

How to use Nginx logs to improve website speed How to use Nginx logs to improve website speed Apr 13, 2025 am 09:09 AM

Website performance optimization is inseparable from in-depth analysis of access logs. Nginx log records the detailed information of users visiting the website. Cleverly using this data can effectively improve the speed of the website. This article will introduce several website performance optimization methods based on Nginx logs. 1. User behavior analysis and optimization. By analyzing the Nginx log, we can gain a deep understanding of user behavior and make targeted optimization based on this: High-frequency access IP identification: Find the IP address with the highest access frequency, and optimize the server resource configuration for these IP addresses, such as increasing bandwidth or improving the response speed of specific content. Status code analysis: analyze the frequency of different HTTP status codes (such as 404 errors), find out problems in website navigation or content management, and proceed

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How Debian OpenSSL prevents man-in-the-middle attacks How Debian OpenSSL prevents man-in-the-middle attacks Apr 13, 2025 am 10:30 AM

In Debian systems, OpenSSL is an important library for encryption, decryption and certificate management. To prevent a man-in-the-middle attack (MITM), the following measures can be taken: Use HTTPS: Ensure that all network requests use the HTTPS protocol instead of HTTP. HTTPS uses TLS (Transport Layer Security Protocol) to encrypt communication data to ensure that the data is not stolen or tampered during transmission. Verify server certificate: Manually verify the server certificate on the client to ensure it is trustworthy. The server can be manually verified through the delegate method of URLSession

Debian mail server SSL certificate installation method Debian mail server SSL certificate installation method Apr 13, 2025 am 11:39 AM

The steps to install an SSL certificate on the Debian mail server are as follows: 1. Install the OpenSSL toolkit First, make sure that the OpenSSL toolkit is already installed on your system. If not installed, you can use the following command to install: sudoapt-getupdatesudoapt-getinstallopenssl2. Generate private key and certificate request Next, use OpenSSL to generate a 2048-bit RSA private key and a certificate request (CSR): openss

PHP: Creating Interactive Web Content with Ease PHP: Creating Interactive Web Content with Ease Apr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

See all articles