search
HomeBackend DevelopmentPHP TutorialA simple counter written in php3_PHP tutorial

A simple counter written in php3_PHP tutorial

Jul 21, 2016 pm 04:03 PM
phpdynamicCanImage ProcessingpowerfuluseofSimpleabilitycounter

PHP has extremely powerful image processing capabilities, and it can easily and dynamically generate web images.
The following is a simple counter made using php.

1. General idea:
Record the number of past visitors in a text file. When the web page is visited, open the file
and read out the number of past visitors, and add 1. Get the latest number of visitors, format the number into the
standard format, then call the image processing function to output the number into a picture, and then write the new number of visitors back to
to record the number of visitors. in the file.

2. Function description used by the program:
A. Related file operations:
a. Open file:
Function prototype: int fopen(string filename, string mode);
Return result: If the file is opened successfully, the function returns the file stream pointer, otherwise it returns FALSE(0).
Parameter description:
string filename -- The name of the file to be opened must be in the form of a string.
For example, "zzm.txt", "..zzm.txt", etc.
String mode -- The way to open the file, must be in character form.
'r', read-only form, the file pointer points to the beginning of the file
'r+', readable and writable, the file pointer points to the beginning of the file
'w', write-only form, the file pointer points to the file at the beginning, truncate the file length to 0,
If the file does not exist, an attempt will be made to create the file.
'w+', readable and writable, the file pointer points to the beginning of the file, truncates the file length to 0,
If the file does not exist, it will try to create the file.
'a', append form (can only be written), the file pointer points to the end of the file, if the file
does not exist, an attempt will be made to create the file.
'a+', readable and writable, the file pointer points to the end of the file, if the file does not exist,
will try to create the file.
Example: Open "zzm.txt" under the current directory in read-only mode
$fp = fopen("zzm.txt", "r");

b. Close the file:
Function prototype: int fclose(int fp);
Return result: 1 is returned on success, 0 is returned on failure
Parameter description: int fp is the file stream pointer returned by the fopen function.
Example: Close the zzm.txt file just opened with fopen
fclose($fp);

c. Read the file:
Function prototype: string fgets(int fp, int length ; File stream pointer, the value returned by the fopen function
int length -- the number of characters read, the actual number of characters read is length -1
Example: read 9 characters from $fp
$str1 = fgets($fp,10);

d. Write file:
Function prototype: int fputs(int fp, string str, int [length]);
Return result : Same as fclose
Parameter description:
int fp – the file stream pointer to which information is to be written, the value returned by the fopen function
string str – the string to be written to the file.
int length -- the length to write, optional, if length is not provided, the entire string will be written,
Otherwise, length characters will be written.
Example: Write "0000000001" to $fp
fput($fp, "0000000001");

B. Related string functions:
a. Calculate the string length:
Function prototype: int strlen(string str);
Return result: Return the length of the string
Parameter description:
String str -- the string whose length is to be calculated
Example: Calculate" The string length of 000000000"
$str2 = "000000000";
$len2 = strlen($str);

b. String addition: the easiest, use a. Two strings are concatenated.
Example: Add $str1 and $str2
$str = $str1.$str2

C. Related graphics functions:
a. New image:
Function prototype :int imagecreate(int x_size, int y_size);
Return result: Return an empty image identification number (ImageID) of X*Y pixel size
Parameter description: x_size, y_size are the width and height of the new image respectively ( In pixels)
Example: Create a new empty image with a size of 88*31 pixels
$ImageID = imagecreate(88, 31);

b. Assign a color to the image:
Function prototype: int imagecolorallocate(int im, int red, int green, int blue);
Return result: Return an RGB color identification number to the image ($im)
Parameter description: int im image identification number Int Red, Green, and Blue are the weight of three colors of red, green and blue, respectively. )
$white = imagecolorallocate($im, 255, 255, 255);
c. Fill the image with color:
Function prototype: int imagefill(int im, int x, int y, int col) ;
Return result: Return 1 if successful, otherwise return 0
Parameter description: int im, the identification number of the image
> (0,0) represents the upper left corner of the image
int col, the identification number of the color
Example: Fill in black starting from the upper left corner of the image (that is, the entire image) (has been defined with the imagecolorallocate function
The color identification number for black is $black).
imagefill($im, 0, 0, $black);

d. Calculate the width of the image:
Function prototype: int imagesx(int ​​im);
Return result: return image The width (unit is pixel)
Parameter description: int im, the identification number of the image.
Example: Calculate the width of image $im
$px = imagesx($im);

e. Write horizontal text in the image:
Function prototype: int imagestring(int im , int font, int x, int y, string s, int col)

Return result: Return 1 if successful, otherwise return 0
Parameter description: int im, image identification number
int font , font identification number, built-in fonts 1 to 5, users can use imageloadfont() to load the font themselves.
int x, int y, start writing the coordinates of the font, (0,0 ) is the upper left corner of the picture.
string s, the string to be written
int col, the color identification number of the font
Example: write the font size as 3 and the color at the image (3,3) position as white (imagecolorallocate( has been used ) function
defines the string "E&J Counter" with black color identification number $white)
ImageString($im, 3, 3, 3, "E&J Counter", $white);

f. Draw a straight line in the image:
Function prototype: int imageline(int im, int x1, int y1, int x2, int y2, int col);
Return result: Return 1 if successful, otherwise return 0 Parameter description: int iM, image recognition number
int x1, int y1, the starting coordinate of the line
int x2, int y2, the scoring coordinates
int color, the line of the line Color identification number
Example: Draw a straight line with color $white from (1,14) to (85,14) in image $im
imageline($im, 1, 14, 85, 14, $ white);

g. Output the image into GIF format:                                                                                                                                                                                                                                                            Parameter description: int im, the identification number of the image
string filename, the name of the generated picture, optional, if filename is empty, directly?
氖涑?
Picture, you need to use Header(" Content-type: image/gif") Predefine the content output by php
as an image
Example: Output the image $im into a picture with the file name "image1.gif"
imagegif($im, "image1.gif");

h. Release the image:
Function prototype: int imagedestroy(int im);
Return result: Return 1 if successful, otherwise return 0
Parameter description: int im, the image identification number to be released. This function will release the image of the identification number im and the system resources occupied by the image.
Example: Release image $im
imagedestroy($im);

3. How to install this counter:
A. The system must have a PHP interpreter installed. PHP can be downloaded at http://www.php.net/. There are also many
detailed
technical information on this site that can be browsed or downloaded for reading. Please refer to its own instructions for how to install PHP.
B. Copy the following program list into a file with the extension php, and put it into a directory that can run php scripts?
lv妫?
And create a plain text file under the directory , the name is zzm.txt.The purpose of this file is to record the number of previous
visitors
. You can preset the initial value of the counter, for example 5000.
C. How to call this counter on the web page? You can call it in the following ways:
A simple counter written in php3_PHP tutorial


Attachment: Complete program list

Header ("Content-type: image/gif");
//Define the output as image type

$fp = fopen("zzm.txt", "r");
//With Open the file zzm.txt that records the number of previous visitors in read mode

$str1 = fgets($fp,10);
//Read 9 characters from the file, the maximum number of visits that this counter can record The number of people is 999999999

$str1++;
//Counter added

fclose($fp);
//Close file (" zzm.txt", "w");
//Open the file that records the number of visitors by writing zzm.txt

fputs($fp, $str1);
//Put the latest Write the number of visitors into the file

fclose($fp);
//Close the file

/*
The following is the formatted output of the number of visitors. If the number of visitors is If it is not enough 9 digits, for example, 5000 (4 digits),
will convert the number of visitors into 000005000 and output it. The method is to calculate the number of digits in the number of visitors, and
compare it with the digits of 000000000 (9 digits) to get the difference in digits, and then put a corresponding 0 in front of the number
. For example, the length of 5000 differs from 000000000 by 5, so five zeros must be added in front of 5000.
*/
$ len1 = strlen ($ str1);
// Calculate the number of visits to the number of visits

$ str2 = "000000000";
$ len2 = strlen($str);
//Define the maximum number of counting digits of the counter

$dif = $len2 - $len1;
//Calculate the difference between the two digits, that is, the previous Number of complemented 0s

$rest = substr($str2, 0, $dif);
//Intercept the 0s to be complemented

$string = $rest.$str1 ;
//Add 0 in front

$font = 4;
//Define the font size

$im = imagecreate(88,31);
//Create a new image Like

$black = ImageColorAllocate($im, 0,0,0);
//Define black

$white = ImageColorAllocate($im, 255,255,255 );
/ /Define white

imagefill($im, 0,0,$black);
//Set the background color of the counter to black

$px = (imagesx($im) -8.3*strlen($string))/2;
//According to the length of the string, calculate the horizontal coordinates where the string starts to be written. The purpose is to try to center the string horizontally

ImageString( $im,3,$px,2,"E&J Counter",$white);
//Write "E&J Counter" to the image

imageline($im, 1, 14, 85, 14, $white);
//Draw a horizontal line

ImageString($im,$font,$px,15.5,$string,$white);
//Write the number of visitors
Imagegif ($ im);
// output the image into gif format
ImageDestroy ($ im);
// Release the image
? & Gt;



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

truehttp: //www.bkjia.com/PHPjc/316134.htmlTechArticlephp has extremely powerful image processing capabilities, and you can use it to dynamically generate web images easily. Below is a simple counter made using php. 1. General idea: Put the past...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor