Tips for newbies on the road PHP newbies on the road (14)
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.)< /I>
} 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.

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.
