Other miscellaneous items
13.1 Generating images
PHP can operate and process images. If you have the GD library installed, you can even generate images using PHP.
Header("Content-type: image/gif");
$string=implode($argv," ");
$im = imagecreatefromgif("images/button1.gif");
$orange = ImageColorAllocate($im, 220, 210, 60);
$px = (imagesx($im)-7.5*strlen($string))/2;
ImageString($im,3,$px,9,$string, $orange);
ImageGif($im);
ImageDestroy($im);
?>
(Translator’s Note: The above code segment lacks comments, please refer to the image processing function section of the PHP Manual)
This code is in In other pages, it is called through the following tag , and then the above button.php3 code obtains the text value and adds the value to the image file obtained separately--in the above The image file in the code is images/button1.gif--finally output to the browser. If you want to use image buttons in a form field, but don't want to have to regenerate a new image every time the text on the button changes, you can use this simple method to dynamically generate image files.
13.2 Cookies
PHP supports HTTP-based cookies. When needed, you can use cookies just as easily as regular variables. Cookies are pieces of information that the browser saves on the client, so you can know whether anyone on a specific PC has visited your site, the visitor's traces on your site, and so on. A typical example of using cookies is the screening of browser preferences. Cookies are set by the function setcookie(). Like the function header() that outputs HTTP headers, setcookie() must be called before any actual content is output to the browser. The following is a simple example:
if (empty($VisitedBefore))
{
// If the cookie is not set, assign the current time value to the cookie
// The last parameter in the function declares the cookie The saved time
// In this example it is 1 year
// The time() function returns the time in seconds since January 1, 1970
SetCookie("VisitedBefore", time(), time() +(60*60*24*365));
}
else
{
// Welcome visitors to come again
echo "Hello there, welcome back
";
// Read the cookie and determine
if ( (time() - $VisitedBefore) >= "(60*60*24*7)" )
echo "Why did you take a week to come back. You should be here more often!? ";
}
? >
13.3 Commonly used functions
Let’s take a brief look at some commonly used functions.
array
array - generate an array
count - the number of array elements
sort - array sorting, there are several other sorting functions available
list - list array elements
each - return the next key/value pair
current - Return the current array element
next,prev - Return the pointers before and after the current array element
Date and time
checkdate - Verify date/time format
date - Generate date/time format
time - Current time information
strftime - Format date/time
Directory, file system
chdir - change directory
dir - directory category
opendir, readdir, closedir - open, read, close directory
fopen, fclose - open, close file
fgets, fgetss - read content line by line
file - Read the entire file into an array variable
Regular expression
ereg - Match regular expression
eregi - Match regular expression in case-insensitive way
ereg_replace - Match regular expression and replace
eregi_replace - Match regular expression in case-insensitive way Expression and replacement
split - split the string according to the rules and store it in array form
String
AddSlashes - use the string after adding a slash
echo - output one or more strings
join, implode - combine the array elements Merge into strings
htmlentities, htmlspecialchars - Convert HTML special characters into HTML markup form
split - Split the string according to rules and store it in array form
13.4 Extend our sample homepage
We will use some of the functions mentioned above and Thoughts on adding more dynamic content to our sample home page. We can add a navigation bar at the top of each page, and at the same time make the current page automatically not displayed by links; we can also add a user verification form to upload music, images and other files and automatically update the page.
Navigation bar
actually add a piece of code to the footer.inc file.Assume that all files with the suffix .php3 in your website will appear in the navigation bar. The following is the code saved as include/navbar.inc:
/* Output the navigation bar and link all except the current page .php3 file on the site*/
# Read directory
$d = dir("./");
echo "
| n";
while($entry = $d- >read())
{
// Ignore no file case
if ( !is_file($entry) )
continue;
/* Separate the file name from the extension. Since . is a special character in regular expressions, it should be quoted */
list($filenm, $fileext) = split(".",$entry, 2);
// Ignore non-.php3 files
if( $fileext != "php3" )
continue;
/* Now that we have selected all the .php3 files, let’s search for the first line (title) in the file
Similar to $title="something";
And separate the above title content , used as link text*/
$linknm = "";
$fp=fopen($entry,"r");
while($buffer=fgets($fp, 4096))
{
$buffer = trim( $buffer);
// We have put the title of each file on the first line of the file for easy search
// But it may cause * trouble when you change the variable name
if (ereg("title *= * "", $buffer))
{
/* We have obtained the title content and can
remove spaces and other processing on this basis.
must be processed in PHP code, such as $title = "blah blah" */
eval($buffer);
// Then display the link text as the title text
$linknm = $title;
break;
}
}
fclose($fp);
if ( $entry == basename($PHP_SELF) )
echo "$linknm";
else
echo "$linknm";
echo " | ";
}
$d->close();
echo "
?>
Photo Collection
We will refer to HTTP-based authentication, file system functions and file upload functions to maintain a directory where image files can be placed.
At the same time, we need to create a directory where image files can be listed. A page showing all the photos in this directory.
File upload
include("include/common.inc");
// Let’s do another user verification here
if(!isset($PHP_AUTH_USER))
{
Header("WWW-Authenticate: Basic realm="$MySiteName"");
Header("HTTP/1.0 401 Unauthorized");
echo "Sorry, you are not authorized to upload filesn";
exit;
}
else
{
if ( !( $PHP_AUTH_USER==$MyName && $PHP_AUTH_PW==$MyPassword ) )
{
// If it is a wrong username/password pair, force re-authentication
Header("WWW-Authenticate: Basic realm="My Realm"") ;
Header("HTTP/1.0 401 Unauthorized");
echo "ERROR : $PHP_AUTH_USER/$PHP_AUTH_PW is invalid.
";
exit;
}
}
if ( $cancelit )
{
// When the visitor presses the "Cancel" button, he will be redirected to the homepage
header ( "Location: front_2.php3" );
exit;
}
function do_upload () {
global $userfile, $userfile_size, $userfile_name, $userfile_type;
global $local_file, $error_msg;
global $HTTP_REFERER;
if ( $userfile == "none" ) {
$error_msg = "You did not specify a file for uploading.";
return;
}
if ( $ userfile_size > 2000000 )
{
$error_msg = "Sorry, your file is too large.";
return;
}
// Wherever you have write permission below...
$upload_dir = "photos";
$local_file = "$upload_dir/$userfile_name";
if ( file_exists ( $local_file ) ) {
$error_msg = "Sorry, a file with that name already exists";
return;
};
// You can also check this File name/type pair to determine what kind of file it is: gif, jpg, mp3…
rename($userfile, $local_file);
echo "The file is uploaded
n";
echo "Go Back
n";
}
$title = "Upload File";
include("include/header.inc");
if (empty($userfile) | | $userfile=="none")
{
// Output the following form
?>
(You may notice a slight delay while we upload your file.)
} else {
if ( $error_msg ) { echo "$error_msg
"; }
if ( $sendit ) {
do_upload ();
}
}
include("include/common.inc");
?>
Photo Gallery
include("include/common.inc");
$title = "Gallery";
include("include/header.inc");
?>
Here are some of our family photos. This PHP script can really
be made better, by splitting into multiple pages.
P>
$d = dir("photos");
while($entry = $d->read())
{
if (is_file("photos/$entry"))
echo " n";
}
$d->close();
?>
include("include/footer.inc");
? >
In addition, you can add an input element to the file upload form to describe the uploaded file. This element will be stored in the file and then read and displayed by the code in the photo gallery above.
The above introduces the tips for beginners to get started with PHP (14), including the tips for beginners to get started. I hope it will be helpful to friends who are interested in PHP tutorials.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

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.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use