Select an item from the sidebar to view content.
Provide your own website design to ensure it meets your brand image and business needs, and enhances user experience and appeal.
Create a website that adapts to multiple devices, whether it is desktop, tablet or mobile phone, to provide the best viewing experience.
Supports complete e-commerce functions, including product display, shopping cart system, online payment integration, etc., helping you easily sell online.
Establish a stable and efficient back-end system, including database management, API integration and server configuration, to support the smooth operation of the website.
Carry out speed optimization and SEO optimization for the website, improve website performance and search engine rankings, and attract more traffic.
Provide regular website maintenance and content update services to ensure website security and the latest information.
We provide technical support at any time, solve problems and provide professional consultation to help you improve the operational efficiency of your website.
HTML (Hypertext Markup Language) is the basic standard language for building web pages. It is responsible for defining the structure and content of web pages, combining text, images, links and other multimedia through various tags.
A standard HTML element consists of a start tag, content and end tags. For example:<p>This is a text</p>. Tags can be nested to form a hierarchical DOM tree structure.
Tags can contain attributes to provide additional information. Common properties include:
| Property name | Instructions for use |
|---|---|
| href | Defines the link's destination URL. |
| src | Define the source path of images or media. |
| alt | Alternative text when the image cannot be displayed. |
| class / id | Used for CSS style selection or JavaScript operations. |
Modern HTML emphasizes semantics and uses tags such as header, footer, article, nav, etc. This not only helps with search engine optimization (SEO), but also improves the readability and accessibility of your web pages.
HTML is responsible for content structure, CSS is responsible for visual styling, and JavaScript is responsible for interactive behavior. The combination of the three can form a modern and complete web application.
Listed below are the standard web color names supported by HTML. These names can be used directly in CSS or HTML attributes, and the browser will automatically parse them into the corresponding numerical values.
| Color preview | English name | Hex code |
|---|---|---|
| Black | #000000 | |
| White | #FFFFFF | |
| Red | #FF0000 | |
| Blue | #0000FF | |
| Yellow | #FFFF00 | |
| Lime | #00FF00 | |
| Cyan / Aqua | #00FFFF | |
| Magenta / Fuchsia | #FF00FF |
| Preview | name | code |
|---|---|---|
| LightGray | #D3D3D3 | |
| Silver | #C0C0C0 | |
| DarkGray | #A9A9A9 | |
| Gray | #808080 | |
| DimGray | #696969 | |
| SlateGray | #708090 |
| Orange | #FFA500 | |
| Gold | #FFD700 | |
| Khaki | #F0E68C | |
| Chocolate | #D2691E | |
| SaddleBrown | #8B4513 |
JavaScript is an efficient, flexible and dynamic scripting language that is widely used in front-end and back-end development. The following are the main features of JavaScript:
JavaScript is a dynamically typed language, and variables do not need to specify data types when they are declared. This means that the type of the variable can change dynamically during program execution.
let value = 10; // initialized to numeric type
value = "Hello"; // can be changed to string type
JavaScript supports object orientation and usesprototypal inheritanceway to realize inheritance and reuse of objects. This allows JavaScript to define and manipulate objects more flexibly.
let person = {
name: "Alice",
greet: function() {
return "Hello, " + this.name;
}
};
In JavaScript, functions are also objects that can be passed as parameters, returned, or assigned to variables. This feature supports many functional programming patterns.
function greet(name) {
return "Hello, " + name;
}
let sayHello = greet;
console.log(sayHello("Alice")); // Functions can be used as variables
JavaScript natively supports asynchronous operations, especially throughPromiseandasync/awaitMakes handling asynchronous behavior more intuitive. This is useful for handling asynchronous operations such as network requests and timing events.
async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
fetchData();
JavaScript was originally used for front-end development in web browsers, but is now widely used in back-end development (such as Node.js), desktop applications, mobile applications and even IoT devices.
The flexibility and diversity of JavaScript make it one of the core technologies of modern web development and provide powerful support in various application fields.
In JavaScript, Boolean is a basic data type with only two possible states or values:
true: Represents truth, yes, opening or success.false: Represents false, no, closed or failed.The Boolean value is the basis for all logical judgments and process control, such asif...elseStatements and loops.
You can assign Boolean values directly to variables or use comparison operators to produce Boolean values.
let isLogged = true;
let isGuest = false;
// The comparison operator will return the Boolean value
let isGreater = (10 > 5); // true
let isEqual = (5 === '5'); // false (because the data types are different)
This is the most common use of Bollinger Values.ifstatement checks whether the result of the expression within the brackets istrue, and then decides whether to execute the block of code.
let age = 20;
if (age >= 18) {
console.log("I am an adult and can vote.");
} else {
console.log("Underage.");
}
let userValid = checkUserStatus(); // Assume return true or false
if (userValid) {
// if userValid is true
displayDashboard();
} else {
// if userValid is false
showLoginError();
}
Logical operators are used to combine or invert Boolean values. There are three main types:
!(NOT): logical negation, inverting the Boolean value.&&(AND): Logical AND, only when both sides aretrueOnly then will the message be returnedtrue。||(OR): Logical OR, as long as one side istrueJust send backtrue。let isLoggedIn = true;
let hasPermission = false;
// ! (NOT)
let isNotLoggedIn = !isLoggedIn; // false
// && (AND)
if (isLoggedIn && hasPermission) {
console.log("The user is logged in and has permission.");
}
// || (OR)
if (isLoggedIn || isGuest) {
console.log("Just log in or be a guest to continue.");
}
JavaScript allows the use of other data types where Boolean values are required, and implicit conversions are performed. These values will be treated astrueorfalse:
falsevalue):In conditional judgment, the following six values will be regarded asfalse:
false(the Bollinger value itself)0(number zero)""or''(empty string)nullundefinedNaN (Not a Number)truevalue):**All other values** except the six Falsy values mentioned above, including:
"0"(non-empty string)"false"(non-empty string)1, -100)[]{}let myString = "Hello";
let myNumber = 0;
if (myString) {
// myString is "Hello", which is a Truthy value and will be executed
console.log("String is not empty.");
}
if (myNumber) {
// myNumber is 0, which is a Falsy value and will not be executed.
console.log("The number is non-zero.");
}
if ({}) {
// The empty object {} is the Truthy value and will be executed
console.log("Object already exists.");
}
A JavaScript array (Array) is a variable used to store multiple values. Each value in the array is called an element, and each element has a numeric index (Index), starting from 0.
// Create array
let fruits = ["Apple", "Banana", "Cherry", "Date"];
//Access array elements
console.log(fruits[0]); // Output: Apple
console.log(fruits.length); // Output: 4
//Add elements to the end of the array
fruits.push("Elderberry");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
//Remove the tail element of the array
let lastFruit = fruits.pop();
console.log(lastFruit); // Output: Elderberry
console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Date"]
slice()The method returns a new array containing the selected elements from the original array. It does not modify the original array.
grammar:array.slice(start, end)
start(optional): The starting index to retrieve (inclusive). If not specified, starts at index 0.end(optional): End index of retrieval (not included). If not specified, retrieve to the end of the array.let numbers = [10, 20, 30, 40, 50, 60, 70]; // Start at index 2 (30) and end at let slice1 = numbers.slice(2); console.log(slice1); // Output: [30, 40, 50, 60, 70] // Starting at index 1 (20) and before index 4 (50) let slice2 = numbers.slice(1, 4); console.log(slice2); // Output: [20, 30, 40] // Use negative indices: -1 points to the last element, -3 points to the third to last element (50) let slice3 = numbers.slice(-3, -1); console.log(slice3); // Output: [50, 60] //Copy the entire array let copy = numbers.slice(); console.log(copy); // Output: [10, 20, 30, 40, 50, 60, 70] console.log(numbers); // The original array has not been modified
The following function provides an efficient way to randomly select a specified number of elements (for example, 5) from an array. This method will ensure that the selected elements are not repeated.
/**
* Randomly select a specified number of elements from the array
* @param {Array} arr original array
* @param {number} count The number of elements to be selected (default is 5)
* @returns {Array} A new array containing randomly selected elements
*/
function getRandomElements(arr, count = 5) {
// If the array elements are less than or equal to the required number, return a copy of the array
if (arr. length<= count) {
return arr.slice();
}
// 建立一個原始陣列的副本,用於隨機選取
let tempArray = arr.slice();
let result = [];
for (let i = 0; i < count; i++) {
// 隨機產生一個索引
let randomIndex = Math.floor(Math.random() * tempArray.length);
// 將選中的元素加入結果陣列
result.push(tempArray[randomIndex]);
// 將選中的元素從 tempArray 中移除,確保不會重複選取
tempArray.splice(randomIndex, 1);
}
return result;
}
let largeArray = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"
];
let randomFive = getRandomElements(largeArray, 5);
console.log(randomFive); // 輸出範例: ["P", "A", "H", "R", "M"] (每次執行結果不同)
In JavaScript development, there are several common ways to determine whether a value exists in an array. Which method to choose depends on whether you only need the "Boolean value result" or whether you need to get the "index position" or "object content" of the member.
This is the most recommended standard practice after ES6, with the clearest semantics and returning true or false directly.
const fruits = ['apple', 'banana', 'orange'];
const hasApple = fruits.includes('apple'); // true
Use in older browsers or when you need to know the position of an element. If it exists, return the index value (starting from 0), if not, return -1.
const tags = ['js', 'php', 'css'];
if (tags.indexOf('php') !== -1) {
//The logic of element existence
}
Use some when the array members are objects or you need to check based on specific logic rather than exact values. As long as one member meets the condition, true will be returned.
const users = [
{ id: 101, name: 'Alex' },
{ id: 102, name: 'Bob' }
];
const exists = users.some(user => user.id === 101); // true
| need | Suggested method | Postback example |
|---|---|---|
| Find the first qualified member | find() | { id: 101, name: 'Alex' } or undefined |
| Find the first index that meets the criteria | findIndex() | 0 or -1 |
| Find all eligible members | filter() | [match 1, match 2] or [] |
If you need to frequently check the existence of members in a very large set of data, it is recommended to convert the array into a Set object. Set's has method query complexity is O(1), which is much faster than array's O(n).
const hugeArray = [/* A large amount of data */];
const mySet = new Set(hugeArray);
if (mySet.has('targetValue')) {
// quick hit
}
You can useconcatMethod to merge two arrays:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let result = arr1.concat(arr2);
console.log(result); // [1, 2, 3, 4, 5, 6]
Using the spread operator is also a common way:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let result = [...arr1, ...arr2];
console.log(result); // [1, 2, 3, 4, 5, 6]
If you wish to add the elements of the second array to the first array, you can combinepushAnd spread operator:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
arr1.push(...arr2);
console.log(arr1); // [1, 2, 3, 4, 5, 6]
Willconsole.log('op_panel_htm()')Change to dynamically obtain the function name and output it, for exampleconsole.log(get_curr_method_name())。
function get_curr_method_name() {
const stack = new Error().stack;
const lines = stack.split("\n");
// Line 0 is Error, line 1 is get_curr_method_name, line 2 is the function that calls it
const callerLine = lines[2] || '';
const match = callerLine.match(/at (.+?) \(/);
return match ? match[1] : 'anonymous';
}
TableOperator.prototype.op_panel_htm = function () {
console.log(get_curr_method_name());
};
If you execute like this:
const t = new TableOperator();
t.op_panel_htm();
This may be output on the console:
TableOperator.op_panel_htm
The actual output depends on the browser stack format, Chrome/Edge generally outputs the full path of the function.
Error().stack, the format of different browsers is slightly different.It can be encapsulated into a custom debugging function:
function debug_log(msg = '') {
console.log(`[${get_curr_method_name()}] ${msg}`);
}
How to use:
debug_log("Initialization completed");
The output results are as follows:
[TableOperator.op_panel_htm] initialization completed
When a JavaScript project becomes large and has many functions, modularization and classification should be used to improve maintainability and readability. The following explains how to effectively manage multiple functions, including whether to useclass。
Store related functions in different files according to functional classification, for example:
/utils/mathUtils.js → Mathematical operation related functions
/utils/domUtils.js → DOM operation function
/modules/tableOperator.js → Table operation related classes or functions
Each file usesexport / importgrammar:
// mathUtils.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from './utils/mathUtils.js';
console.log(add(2, 3));
It is more structural to wrap functions with related logic in an object or class, for example:
// domUtils.js
export const DomUtils = {
createElement(tag) {
return document.createElement(tag);
},
removeElement(el) {
el.parentNode.removeChild(el);
}
};
Or use class:
// tableOperator.js
export class TableOperator {
constructor(tableId) {
this.table = document.getElementById(tableId);
}
highlightRow(index) {
// ...
}
sortByColumn(colIndex) {
// ...
}
}
If it is just a tool function (such as string processing, mathematical operations), it is recommended to useexport functionorexport const obj = { ... }Just manage.
/src
/utils
stringUtils.js
mathUtils.js
/components
tableOperator.js
chartViewer.js
main.js
in JavaScriptclassUses similar to other OOP languages, including constructorsconstructor, member variables and method (function) definitions.
class Person {
//Member variables (public)
name;
age;
//Constructor
constructor(name, age) {
this.name = name;
this.age = age;
}
//Member method
greet() {
console.log(`Hello, I am ${this.name} and I am ${this.age} this year`);
}
// Static method (no need to instantiate)
static species() {
return 'human';
}
}
const p = new Person("Xiao Ming", 25);
p.greet(); // Output: Hello, I am Xiao Ming, 25 years old this year
console.log(p.name); // Xiao Ming
console.log(Person.species()); // Human
this.name, can be accessed externally.class Counter {
#count = 0; // Private variable
increment() {
this.#count++;
console.log(this.#count);
}
#secret() {
console.log("This is a private method");
}
revealSecret() {
this.#secret(); // Can be called internally
}
}
class Animal {
speak() {
console.log("Make a sound");
}
}
class Dog extends Animal {
speak() {
console.log("Woof woof!");
}
}
in class methodthisPoint to this instance. But if used in events or callbacks, please usebind()or arrow function to ensure pointing.
class Button {
constructor() {
this.label = "Click";
document.addEventListener("click", this.handleClick.bind(this));
}
handleClick() {
console.log(`You pressed ${this.label}`);
}
}
JavaScript classes provide encapsulation, inheritance, method and attribute support similar to other languages. They are suitable for medium to large projects and are also easy to integrate with modules. If you need more rigorous typing and control, consider using TypeScript.
JavaScript modules (modules) provide a way to encapsulate variables and functions in files. You can useimport/exportThe mechanism is similar toclassThe division of labor and structuring functions are suitable for tool functions or single functional logic units.
| Function | class | module |
|---|---|---|
| Encapsulating data and behavior | ✅ | ✅(via export package) |
| Instantiable | ✅ | ❌(Exists as a singleton) |
| Inheritance and polytype | ✅ | ❌(Requires manual management) |
| single functional component | Can | more suitable |
// file: mathUtils.js
export const MathUtils = {
add(a, b) {
return a + b;
},
multiply(a, b) {
return a * b;
}
};
// file: main.js
import { MathUtils } from './mathUtils.js';
console.log(MathUtils.add(3, 4)); // 7
console.log(MathUtils.multiply(2, 5)); // 10
// file: stringHelper.js
export function toUpper(str) {
return str.toUpperCase();
}
export function truncate(str, len) {
return str.length > len ? str.slice(0, len) + '…' : str;
}
// file: main.js
import { toUpper, truncate } from './stringHelper.js';
console.log(toUpper("hello")); // HELLO
console.log(truncate("JavaScript", 5)); // JavaS…
// file: config.js
let config = {
env: "dev",
version: "1.0"
};
export function getConfig() {
return config;
}
export function setEnv(env) {
config.env = env;
}
// file: app.js
import { getConfig, setEnv } from './config.js';
console.log(getConfig()); // { env: "dev", version: "1.0" }
setEnv("prod");
console.log(getConfig()); // { env: "prod", version: "1.0" }
Modules are suitable for encapsulating tool functions, constants and settings, andclassDifferent, the module isIt is automatically executed when loading and is unique in the entire domain., very suitable for logical classification and neat program structure. Use when you need object instances that can be created multiple times or object-directed inheritanceclassMore suitable.
function runExclusive(fn) {
let last = Promise.resolve();
return function (...args) {
last = last.then(() => fn(...args));
return last;
};
}
async function doTask(name) {
console.log(`Start ${name}`);
await new Promise(resolve => setTimeout(resolve, 2000));
console.log(`End ${name}`);
}
const doTaskOnce = runExclusive(doTask);
// Call multiple times at the same time
doTaskOnce("A");
doTaskOnce("B");
doTaskOnce("C");
Start A
End A
Start B
End B
Start C
End C
To save a specific HTML element on a web page (such as $\lt$table$\gt$) as a local $\text{.html}$ file, you usually need to use JavaScript to obtain the HTML code of the element, and then trigger the storage process through the browser's download API. This is a client-side solution.
Use the $\text{document.getElementById}$ or $\text{document.querySelector}$ selector to get the $\lt$table$\gt$ element you want to store and retrieve its $\text{outerHTML}$.
var tableElement = document.getElementById('myTableId');
var tableHtml = tableElement.outerHTML;
The $\lt$table$\gt$ code alone is not enough to form a complete $\text{.html}$ file. You need to wrap it in the basic $\lt$html$\gt$, $\lt$head$\gt$ and $\lt$body$\gt$ tags to ensure that the archive opens and displays correctly in the browser. You should also include any necessary $\lt$style$\gt$ tags or $\lt$link$\gt$ tags to preserve the table's styling (CSS).
var fullHtml = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Stored table</title></head><body>' + tableHtml + '</body></html>';
Blob (Binary Large Object) objects are used to store binary or binary-like data. We convert a string containing complete HTML code into a $\text{Blob}$ of type $\text{text/html}$.
var blob = new Blob([fullHtml], { type: 'text/html' });
Use $\text{URL.createObjectURL}$ to create a local $\text{URL}$ pointing to $\text{Blob}$, and assign it to the $\text{href}$ attribute of a $\lt$a$\gt$ element, and set the $\text{download}$ attribute to specify the name of the downloaded file.
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'exported_table.html'; //Specify the downloaded file name
a.click(); // Simulate click and trigger download dialog box
// Release resources
URL.revokeObjectURL(a.href);
If your table styles were added dynamically via an external $\text{CSS}$ file or $\text{JavaScript}$ on the page, simply saving $\text{outerHTML}$ may lose those styles or functionality. To solve this problem:
Emulate C/C++#ifdef DEBUGConditional compilation mechanism to achieve controllability in JavaScriptdebug_log(), control the output level and switch of the log according to the development stage (under development, testing, official version).
// 0 = no output, 1 = error, 2 = warning, 3 = message, 4 = debug
const LOG_LEVEL = 3;
function debug_log(msg, level = 3) {
if (level<= LOG_LEVEL) {
const name = get_curr_method_name();
console.log(`[${name}] ${msg}`);
}
}
function get_curr_method_name() {
const stack = new Error().stack;
const lines = stack.split("\n");
const callerLine = lines[2] || '';
const match = callerLine.match(/at (.+?) \(/);
return match ? match[1] : 'anonymous';
}
function initApp() {
debug_log("Initializing", 4); // Debug level
debug_log("Loading settings successfully", 3); // Message
debug_log("The setting value may be too old", 2); // Warning
debug_log("Loading failed", 1); // Error
}
LOG_LEVEL = 4(wide open)LOG_LEVEL = 2(Only errors and warnings are displayed)LOG_LEVEL = 0(complete silence)When used with tools such as Webpack/Vite/ESBuild, conditional constants can be usedprocess.env.NODE_ENVRemove logs:
if (process.env.NODE_ENV === 'development') {
debug_log("Messages in development environment");
}
It can also be used with Babel plug-ins (such as babel-plugin-transform-remove-console) to remove allconsole.*。
Although JavaScript does not have conditional compilation, it can achieve a debugging level and release control mechanism similar to C++ through variable control and packaging optimization strategies to ensure that the information during the development phase is complete and the official version is clean and free of noise.
The browser console is part of the developer tools and is used to:
F12orCtrl + Shift + I→ Click on the “Console” tabCmd + Option + Iconsole.log("Message"):Print message$0: Select the currently selected element in the Elements paneldocument.querySelector():Select DOM elementsdir(obj): List object propertiescopy(obj): Copy variables to clipboard//Print message
console.log("Hello Console");
// Get page elements and operate
const btn = document.querySelector("button");
btn.textContent = "New Label";
btn.click();
//View object
console.dir(btn);
---
If the following message appears in the Console, it means that Chrome prohibits directly pasting multi-line code for security reasons:
Don’t paste code into the DevTools Console ... Please type ‘allow pasting’ below and press Enter
enterallow pastingand press Enter to remove the restriction.
clear():Clear Console messagesinspect(element): Jump directly to the Elements panel to locate the element$and$$:yesquerySelectorandquerySelectorAllabbreviationFor security reasons and to prevent malicious websites or others from being induced to post dangerous code, Chrome by default prohibits pasting multi-line code directly into the Console.
The message appears:
Warning: Don’t paste code into the DevTools Console that you don’t understand or haven’t reviewed yourself.
This could allow attackers to steal your identity or take control of your computer.
Please type ‘allow pasting’ below and press Enter to allow pasting.
---
allow pasting(without quotes)// 1. Console enter allow pasting and press Enter
allow pasting
// 2. Paste the JavaScript code you want to execute
const host = document.querySelector('i18n-message[key="login.button.loginWithLine"]');
// ...(following code)
---
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.open("GET", "data.php", true);
xhr.send();
</script>
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
alert("Server response: " + xhr.responseText);
}
};
xhr.send("name=Xiao Ming&score=90");
</script>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log("Name: " + json.name);
}
};
xhr.send();
</script>
$.ajax({
url: "data.php",
method: "GET",
success: function(response) {
$("#result").html(response);
},
error: function(xhr) {
alert("Error: " + xhr.status);
}
});
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log("Response content: " + xmlhttp.responseText);
}
};
xmlhttp.open("GET", "api/data.php", true);
xmlhttp.send();
xmlhttp.open("POST", "api/save.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=test&value=123");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
console.log("Status: " + data.status);
}
};
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var json = JSON.parse(xmlhttp.responseText);
console.log("Data received successfully:", json);
} catch (e) {
console.error("The returned content is not valid JSON", xmlhttp.responseText);
}
}
};
xmlhttp.open("GET", "data.php", true);
xmlhttp.send();
</script>
error_reporting(0)Turn off error output.
<br />
<b>Deprecated</b>: Facebook\FacebookApp implements the Serializable interface...
...
{ "status": "ok", "data": [...] }
error_reporting(0);
ini_set('display_errors', 0);This prevents PHP from outputting any error or warning messages.<?php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
// Assume this is the data to be returned
$data = ["status" => "ok", "value" => 123];
echo json_encode($data);
exit;
?>
composer update facebook/graph-sdkOr check the version requirements in composer.json to use a PHP 8.1 compliant version.let response = xmlhttp.responseText;
let jsonStart = response.indexOf("{");
if (jsonStart >= 0) {
let jsonStr = response.substring(jsonStart);
let json = JSON.parse(jsonStr);
//Use json to process data
}
<div id="msg"></div>
<script>
let name = "Xiao Ming";
document.getElementById("msg").textContent = name;
</script>
<div id="box"></div>
<script>
let color = "red";
document.getElementById("box").innerHTML =
`<p style="color:${color}">Text color: ${color}</p>`;
</script>
<a id="link">link</a>
<input id="nameInput">
<script>
let URL = "https://example.com";
let name = "Xiaohua";
document.getElementById("link").href = URL;
document.getElementById("nameInput").value = name;
</script>
<img id="avatar" alt="user avatar">
<script>
let image source = "https://example.com/avatar.png";
document.getElementById("avatar").setAttribute("src", image source);
</script>
<div id="card"></div>
<script>
let userID = 456;
document.getElementById("card").dataset.userid = user ID; // Will correspond to data-userid="456"
</script>
<a id="myLink">Link</a>
<input id="myInput">
<script>
let URL = "https://example.com";
let name = "Xiao Ming";
document.getElementById("myLink").href = URL;
document.getElementById("myInput").value = name;
</script>
<img id="avatar">
<script>
let image source = "https://example.com/avatar.png";
document.getElementById("avatar").setAttribute("src", image source);
</script>
<div id="card"></div>
<script>
let username = 123;
document.getElementById("card").dataset.userid = user code; // Will correspond to data-userid="123"
</script>
<div id="container"></div>
<script>
let title = "dynamic title";
document.getElementById("container").innerHTML =
`<h3 data-title="${title}">${title}</h3>`;
</script>
The following example will add a<div class="abc">Child elements of:
// Assume there is a parent element
const parent = document.getElementById("myParent");
// Create div element
const child = document.createElement("div");
// Set class
child.className = "abc"; // or use classList.add("abc");
//Add to parent element
parent.appendChild(child);
<div id="myParent"></div>
<script>
const parent = document.getElementById("myParent");
const child = document.createElement("div");
child.className = "abc";
child.textContent = "This is a new DIV";
parent.appendChild(child);
</script>
child.classList.add("abc", "def")id、style、datasetpropertieswill be in#myParentAppears in:
<div class="abc">This is a new DIV</div>
querySelectorAll()Use CSS selector syntax to select all elements that meet the criteria and return a staticNodeList。
// Select all <div> with category "item"
let items = document.querySelectorAll("div.item");
// Use forEach to iterate through the results
items.forEach(item => {
item.style.color = "blue";
});
andquerySelectorAll()Similar, but it will only return the "first" element that meets the criteria. If not found, returnnull。
// Select the first element with ID "main-title"
let title = document.querySelector("#main-title");
// Select the first <p> tag on the page
let firstPara = document.querySelector("p");
This is the fastest and most direct method, designed for selecting a single element by its unique ID.
let header = document.getElementById("header-section");
Select elements based on category names and return a "Live"HTMLCollection. This collection is automatically updated when the DOM structure changes.
let buttons = document.getElementsByClassName("btn-submit");
// Note: you cannot use forEach directly on HTMLCollection, you need to convert it to an array first
Array.from(buttons).forEach(btn => console.log(btn));
Select elements based on tag names (such as div, p, span) and also return an instantHTMLCollection。
let allLinks = document.getElementsByTagName("a");
console.log("The page has a total of " + allLinks.length + " links");
| method | Postback type | Parameter type | performance |
|---|---|---|---|
| querySelector | Single Element | CSS selectors | ordinary |
| querySelectorAll | NodeList (static) | CSS selectors | ordinary |
| getElementById | Single Element | ID string | fastest |
| getElementsByClassName | HTMLCollection (instant) | category string | quick |
querySelectorAllreturnedNodeListIs static, which means that the contents of the manifest will not change even if an element is later removed from the DOM. andgetElementsBy...Series returnedHTMLCollectionIt is dynamic and will reflect the latest status of the DOM at any time.
When you want to select elements that meet multiple conditions at the same time, just place the selectors closely together without leaving any spaces in between.
// Select elements whose category contains both "btn" and "primary"
let primaryButtons = document.querySelectorAll(".btn.primary");
// Select the <li> tag with class "item"
let listItems = document.querySelectorAll("li.item");
If you want to select all elements that match condition A or condition B, use "comma",Separate different selectors.
// Select all <h1> and all <h2>
let headers = document.querySelectorAll("h1, h2");
// Select elements with category "active" or elements with category "highlight"
let markers = document.querySelectorAll(".active, .highlight");
Filter based on the presence or value of an HTML attribute. This is useful when working with forms or custom data properties.
// Select all <button> with "disabled" attribute
let disabledBtns = document.querySelectorAll("button[disabled]");
// Select all <input> whose name attribute starts with "user" (use ^=)
let userInputs = document.querySelectorAll("input[name^='user']");
// Select all elements whose data-type attribute is exactly equal to "video"
let videos = document.querySelectorAll("[data-type='video']");
Use structural relationships between elements for in-depth screening.
// Descendant selector: select all <a> inside #nav (regardless of level)
let navLinks = document.querySelectorAll("#nav a");
//Children selector: select the <div> directly below .container (first layer only)
let directDivs = document.querySelectorAll(".container > div");
// Adjacent sibling selector: selects the first <p> immediately following <h1>
let firstParas = document.querySelectorAll("h1 + p");
This is extremely powerful when working with lists or status filters.
// Select all even-numbered columns in the table (2nd, 4th, 6th...)
let evenRows = document.querySelectorAll("tr:nth-child(even)");
// Select all checkboxes that are currently checked
let checkedBoxes = document.querySelectorAll("input[type='checkbox']:checked");
// Select all <section> that do not have the "hidden" category (use :not)
let visibleSections = document.querySelectorAll("section:not(.hidden)");
You can combine all the above rules to create complex query conditions.
// Select all <div> in the container with the ID "main", the class "card" and the "data-id" attribute
let complexQuery = document.querySelectorAll("#main div.card[data-id]");
// Select both the first <li> and the last <li>
let endpoints = document.querySelectorAll("li:first-child, li:last-child");
to findcurrElemfirst after<footer>elements, the most reliable way is to iterate over all<footer>element and useNode.compareDocumentPosition()method to determine their relativecurrElemlocation.
document.querySelectorAll('footer')Get all the items on the page<footer>element.<footer>element, callcurrElem.compareDocumentPosition(footer). If the resulting bitmask contains $4$(NODE_FOLLOWING), it means that the<footer>in file ordercurrElemafter.<footer>, to stop traversing.find target<footer>element, you can use the modern DOM interfaceElement.before()Insert new content before this element.
targetFooter.before(contentToAdd);
Here'scontentToAddCan be a string (which will be converted to a text node) or one or more DOM nodes/elements.
function addContentBeforeNextFooter(currElem, contentToAdd) {
// 1. Get all footer elements in the file
const allFooters = document.querySelectorAll('footer');
let nextFooter = null;
// 2. Traverse and find the first footer after currElem
for (const footer of allFooters) {
// Check if footer follows currElem (bitmask 4)
// 4: The argument node follows the reference node.
if (currElem.compareDocumentPosition(footer) & 4) {
nextFooter = footer;
break; // Stop immediately after finding the first one
}
}
// 3. If the target footer is found, insert content in front of it
if (nextFooter) {
nextFooter.before(contentToAdd);
console.log('Content was successfully inserted before the first footer after currElem.');
return nextFooter;
} else {
console.log('No footer element found after currElem.');
return null;
}
}
// Example: Create content to be inserted
const newDiv = document.createElement('div');
newDiv.textContent = 'This is the newly inserted content. ';
// Assume currElem is a DOM element you have obtained
// const currElem = document.getElementById('some-id');
// addContentBeforeNextFooter(currElem, newDiv);
This updated functionfindNearestFooterAllows you to specify a direction ('before'or'after') to find the closestcurrElemof<footer>element.
Node.compareDocumentPosition()bit mask of the method to determine<footer>is incurrElemBefore or after.'after'): Determine whether it contains bit $4$ (NODE_FOLLOWING)。
document.querySelectorAllAlready sorted in file order, the first one found that meets the conditions<footer>That's the goal.'before'): Determine whether it contains bit $2$ (NODE_PRECEDING)。
document.querySelectorAllIt is sorted from top to bottom. We need to traverse the list in reverse direction and find the first one that meets the conditions.<footer>is the closestcurrElemThat one./**
* Find the first <footer> element before or after currElem and insert content before and after it.
* @param {HTMLElement} currElem - The element used as the reference point.
* @param {('before'|'after')} direction - The direction to look for ('before' or 'after').
* @param {HTMLElement|string} contentToAdd - the content (element or string) to be inserted.
* @returns {HTMLElement|null} - The footer element found, or null if not found.
*/
function findNearestFooter(currElem, direction, contentToAdd) {
const allFooters = document.querySelectorAll('footer');
let nearestFooter = null;
if (direction === 'after') {
// Find the first footer "after"
for (const footer of allFooters) {
// 4 (NODE_FOLLOWING): footer after currElem
if (currElem.compareDocumentPosition(footer) & 4) {
nearestFooter = footer;
break; // Stop when finding the first one because it is the closest
}
}
//Insert content (before found footer)
if (nearestFooter) {
nearestFooter.before(contentToAdd);
console.log('Content has been inserted before the first footer after currElem.');
}
} else if (direction === 'before') {
// Find the first footer "before"
// You must traverse backward from the end of the list to find the footer closest to currElem
for (let i = allFooters.length - 1; i >= 0; i--) {
const footer = allFooters[i];
// 2 (NODE_PRECEDING): footer before currElem
if (currElem.compareDocumentPosition(footer) & 2) {
nearestFooter = footer;
break; // Stop when the first one is found (the first one in reverse traversal)
}
}
// Insert content (after found footer)
// Since our requirement is to find the "before" footer, the content is usually inserted after the footer.
if (nearestFooter) {
// To be consistent with your previous request (insert before footer), we'll still assume before
// If it is required to insert "after" the found footer, use nearestFooter.after(contentToAdd);
nearestFooter.before(contentToAdd);
console.log('Content has been inserted before the first footer before currElem.');
}
}
if (!nearestFooter) {
console.log(`No footer element found in currElem ${direction === 'before' ? 'before' : 'after'}.`);
}
return nearestFooter;
}
// Example: Assume currElem and contentToAdd are defined
// const currElem = document.getElementById('some-reference');
// const newContent = document.createElement('p');
// newContent.textContent = 'This is the inserted content';
// // Call example: Find the first footer after currElem
// findNearestFooter(currElem, 'after', newContent.cloneNode(true));
// // Call example: Find the first footer before currElem
// findNearestFooter(currElem, 'before', newContent.cloneNode(true));
document.querySelectorAll()What is returned is a **NodeList**. NodeList is not a true JavaScript array, but it haslengthattributes and numeric indexes, so you can useArray.from()or spread operator (Spread Operator...) to convert it to an array and then useArray.prototype.slice()Method to get the initial subset.
/**
* Get the first 5 elements in the collection returned by querySelectorAll.
* @param {string} selector - CSS selector string.
* @returns {Array} - Array containing the first 5 elements (if there are less than 5 elements, all elements are returned).
*/
function getFirstFiveElements(selector) {
const nodeList = document.querySelectorAll(selector);
// 1. Convert NodeList to array
const allElements = Array.from(nodeList);
// 2. Use slice(0, 5) to get the first 5 elements
const firstFive = allElements.slice(0, 5);
return firstFive;
}
//Example usage:
// const topFiveDivs = getFirstFiveElements('div');
// console.log("First 5 elements:", topFiveDivs);
To get a random element from a collection, you need to perform the following steps:
The most efficient way is usually to randomly sort the array and then take the top five.
/**
* Randomly obtain 5 elements from the collection returned by querySelectorAll.
* @param {string} selector - CSS selector string.
* @returns {Array} - Array containing 5 random elements (if there are less than 5 elements, all elements are returned).
*/
function getRandomFiveElements(selector) {
const nodeList = document.querySelectorAll(selector);
// 1. Convert NodeList to array
let allElements = Array.from(nodeList);
// If the total number of elements is less than 5, return all elements directly
if (allElements.length<= 5) {
return allElements;
}
// 2. 實作 Fisher-Yates (或稱 Knuth) 隨機排序法
// 這是一種高效且公平的隨機排列方法。
for (let i = allElements.length - 1; i >0; i--) {
// Generate a random index j between 0 and i
const j = Math.floor(Math.random() * (i + 1));
// Swap allElements[i] and allElements[j]
[allElements[i], allElements[j]] = [allElements[j], allElements[i]];
}
// 3. Get the first 5 elements of the randomly sorted array
const randomFive = allElements.slice(0, 5);
return randomFive;
}
//Example usage:
// const randomFiveImages = getRandomFiveElements('img');
// console.log("Random 5 elements:", randomFiveImages);
Responsive web design is a website design method that allows the website to adapt to the screen sizes and resolutions of different devices. This means that the content of the website will automatically adjust to provide the best experience whether you are using it on a mobile phone, tablet, or desktop computer.
The key to responsive design is flexible layouts, resizable images, and CSS media queries. These technologies allow a website to automatically resize and arrange elements based on the width of the device.
Use media queries in CSS to adjust layout, for example:
@media (max-width: 600px) { body { font-size: 14px; } }
Responsive design can improve user experience, reduce development costs, and increase SEO effects. Responsive web pages are easier to maintain since there is no need to design a different version for each device.
JavaScript is a front-end programming language whose code is downloaded to the user's browser and executed, making it easy to view or copy. Although it is impossible to completely prevent the code from being reverse engineered, various measures can be taken to increase the intensity of protection and implement an authorization mechanism for trial and official versions.
Use tools to convert source code into an unreadable format.
npm install -g javascript-obfuscator
javascript-obfuscator input.js --output output.js
Obfuscated code example:
var _0x1a2b=["\x68\x65\x6C\x6C\x6F"];console[_0x1a2b[0]]("Hello World!");
Use compression tools to remove whitespace and comments to reduce code readability, such as usingUglifyJS。
Store important logic on the server and provide services through APIs instead of executing them directly on the front end.
fetch('https://example.com/api').then(response => response.json()).then(data => console.log(data));
Add a detection mechanism to the page to prevent the use of developer tools.
document.addEventListener('keydown', (event) => {
if (event.key === 'F12' || (event.ctrlKey && event.shiftKey && event.key === 'I')) {
event.preventDefault();
}
});
Combine trial and production logic with the API, such as checking user identity against authorization codes.
fetch('https://example.com/verify_license', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ licenseKey: userLicenseKey })
}).then(response => response.json()).then(data => {
if (data.valid) {
console.log('Official version enabled');
} else {
console.log('Trial version limited functions');
}
});
Disable certain features in the trial version, such as the availability of UI components or data access.
Set trial period check logic based on the user's first use date.
const startDate = localStorage.getItem('startDate') || new Date();
localStorage.setItem('startDate', startDate);
if (new Date() - new Date(startDate) > 14 * 24 * 60 * 60 * 1000) {
console.log('Trial period has ended');
} else {
console.log('during trial period');
}
In web pages, monitoring changes in scroll position can achieve many dynamic effects, such as displaying a return to top button, floating navigation bar, etc. Listening for such events can be easily implemented using JavaScript.
In JavaScript, this can be done viawindow.addEventListener('scroll', handler)Method to listen for scroll events. Fires on scrollhandlerfunction to perform corresponding processing.
The following example displays the vertical position of the current page scroll and displays it at the bottom of the page.
<script>
//Define scroll event handler
function handleScroll() {
const scrollPosition = window.scrollY; // Get the vertical scroll position
document.getElementById("scrollPositionDisplay").textContent = "Current scroll position: " + scrollPosition + " px";
}
//Add scroll event listener
window.addEventListener('scroll', handleScroll);
</script>
<div id="scrollPositionDisplay" style="position: fixed; bottom: 20px; left: 20px; background-color: #eee; padding: 10px;">
Current scroll position: 0 px
</div>
Adding too many operations in the scroll event may affect performance, it is recommended to userequestAnimationFrameorsetTimeoutPerform throttling to reduce the frequency of event triggers.
Events that listen for scroll position changes can be used for a variety of dynamic effects to enhance the interactivity of web pages. Through simple JavaScript, scrolling events can be monitored to improve user experience.
width: max-contentThis approach allows the width of the element to automatically adjust based on the content while staying on a new line.
pre {
display: inline-block;
width: max-content;
}
Effect:
This is a text.
This is a code block.
float: leftThis method usesfloatFloat the element to the left and start it on a new line.
pre {
display: inline-block;
float: left;
}
Effect:
This is a text.
This is a code block.
::beforevirtual elementUse virtual elements to force elements to wrap while maintaining adaptive width.
pre {
display: inline-block;
}
pre::before {
content: '';
display: block;
clear: both;
}
Effect:
This is a text.
This is a code block.
white-space: preusewhite-spaceControl line wrapping behavior so block widths naturally adapt to content.
pre {
display: inline-block;
white-space: pre;
}
Effect:
This is a text.
This is a code block.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Windows App UI Simulation</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
.app-window {
width: 800px;
height: 500px;
margin: 50px auto;
background: #ffffff;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
overflow: hidden;
display: flex;
flex-direction: column;
}
.title-bar {
background: #0078d7;
color: #ffffff;
padding: 10px 15px;
display: flex;
justify-content: space-between;
align-items: center;
}
.title-bar h1 {
font-size: 16px;
margin: 0;
}
.title-bar .buttons {
display: flex;
gap: 5px;
}
.title-bar .buttons button {
width: 20px;
height: 20px;
background: #ffffff;
border: none;
border-radius: 50%;
cursor: pointer;
}
.title-bar .buttons button:hover {
background: #e0e0e0;
}
.content {
flex: 1;
padding: 15px;
overflow: auto;
}
.sidebar {
width: 200px;
background: #f3f3f3;
border-right: 1px solid #ddd;
display: inline-block;
vertical-align: top;
}
.main-content {
display: inline-block;
width: calc(100% - 200px);
vertical-align: top;
}
.sidebar ul {
list-style: none;
margin: 0;
padding: 0;
}
.sidebar ulli {
padding: 10px 15px;
cursor: pointer;
border-bottom: 1px solid #ddd;
}
.sidebar ul li:hover {
background: #e9e9e9;
}
.main-content p {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div class="app-window">
<div class="title-bar">
<h1>My Windows App</h1>
<div class="buttons">
<button title="Minimize"></button>
<button title="Maximize"></button>
<button title="Close" style="background: #e81123;"></button>
</div>
</div>
<div class="content">
<div class="sidebar">
<ul>
<li onclick="showContent('Home')">Home</li>
<li onclick="showContent('Settings')">Settings</li>
<li onclick="showContent('About')">About</li>
</ul>
</div>
<div class="main-content" id="mainContent">
<p>Select an item from the sidebar to view content.</p>
</div>
</div>
</div>
<script>
function showContent(section) {
const content = {
Home: '<h2>Home</h2><p>Welcome to the home page.</p>',
Settings: '<h2>Settings</h2><p>Adjust your application preferences here.</p>',
About: '<h2>About</h2><p>This is a mock Windows App created using HTML and JavaScript.</p>',
};
document.getElementById('mainContent').innerHTML = content[section] || '<p>Content not found.</p>';
}
</script>
</body>
</html>
index.html。Select an item from the sidebar to view content.
React is a popular JavaScript library developed by Facebook for building dynamic and efficient user interfaces. Its component-based design enables developers to quickly create and reuse UI components.
Vue.js is a lightweight and easy-to-use framework suitable for developing small to medium-sized applications. Its simple API and intuitive design make it possible to quickly design UIs.
Bootstrap is a front-end framework that provides a variety of ready-made UI components and layout tools to quickly build responsive websites.
Material-UI is a React UI framework based on Google Material Design. It contains many beautiful components and is suitable for quickly designing high-quality interfaces.
Tailwind is a practical CSS framework that can quickly build customized UI when used in conjunction with JavaScript. Its atomic design gives developers flexible control over styles.
Foundation is a responsive front-end framework that provides a variety of UI components and grid systems, suitable for quickly building modern web designs.
Chakra UI is a simple and customizable React UI framework that provides an intuitive API and diverse components.
Quasar is a UI framework based on Vue.js that can quickly build responsive and cross-platform applications.
React is a declarative JavaScript library developed by Meta that focuses on building user interfaces. It greatly improves the development efficiency and maintainability of database-driven applications through component development and virtual DOM technology.
When developing database-based applications, React is often combined with a modern tool chain to handle data flow:
Although any plain text editor can be used for React development, in order to cooperate with database field hints and type checking, the following are the most common choices in the industry:
In order to optimize the development process of React and database applications, it is recommended to install the following tools in the IDE:
| Tool type | Popular choices | core value |
|---|---|---|
| Code Editor (IDE) | VS Code, WebStorm | Efficient code writing and type hints |
| Package management tools | npm, pnpm, yarn | Manage React and its ecosystem dependencies |
| Build tools | Vite, Turbopack | Extremely fast hot update and project packaging performance |
| debugger | React DevTools | Real-time monitoring of component status and performance bottlenecks |
import React, { useState, useEffect } from 'react';
function DatabaseView() {
//Simulated database data
const [data, setData] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
// Simulate obtaining data from the database
useEffect(() => {
const fetchData = async () => {
const mockData = [
{ id: 1, name: 'John Doe', email: '[email protected]', age: 28 },
{ id: 2, name: 'Jane Smith', email: '[email protected]', age: 34 },
{ id: 3, name: 'Alice Brown', email: '[email protected]', age: 25 },
{ id: 4, name: 'Bob White', email: '[email protected]', age: 40 },
];
setData(mockData);
};
fetchData();
}, []);
//Filter data
const filteredData = data.filter(
(item) =>
item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
item.email.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
<h1>Database View</h1>
<input
type="text"
placeholder="Search by name or email"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
style={{
marginBottom: '20px',
padding: '10px',
width: '300px',
fontSize: '16px',
}}
/>
<table
style={{
width: '100%',
borderCollapse: 'collapse',
marginTop: '10px',
}}
>
<thead>
<tr>
<th style={{ border: '1px solid #ddd', padding: '10px' }}>ID</th>
<th style={{ border: '1px solid #ddd', padding: '10px' }}>Name</th>
<th style={{ border: '1px solid #ddd', padding: '10px' }}>Email</th>
<th style={{ border: '1px solid #ddd', padding: '10px' }}>Age</th>
</tr>
</thead>
<tbody>
{filteredData.map((item) => (
<tr key={item.id}>
<td style={{ border: '1px solid #ddd', padding: '10px' }}>
{item.id}
</td>
<td style={{ border: '1px solid #ddd', padding: '10px' }}>
{item.name}
</td>
<td style={{ border: '1px solid #ddd', padding: '10px' }}>
{item.email}
</td>
<td style={{ border: '1px solid #ddd', padding: '10px' }}>
{item.age}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default DatabaseView;
create-react-app。DatabaseView.js。App.jsImport and use<DatabaseView />。React and PHP do not mix code directly, but throughJSONformat data for communication. React usesfetchoraxiosSend a request and PHP will return the result after processing.
The backend PHP code no longer outputs HTML, but instead outputs JSON headers and data.
<?php
// Allow cross-origin requests (CORS)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// Simulate obtaining data from the database
$stocks = ["AAPL", "TSLA", "NVDA", "GOOGL", "MSFT"];
echo json_encode($stocks);
?>
In React, we usually douseEffectCall the PHP API in the hook.
import { useEffect, useState } from 'react';
function StockList() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://your-server.com/api.php")
.then(res => res.json())
.then(json => setData(json));
}, []);
return (
<ul>
{data.map(item => <li key={item}>{item}</li>)}
</ul>
);
}
| type | Recommended plan | illustrate |
|---|---|---|
| Traditional PHP | Native PHP or CodeIgniter | Suitable for simple API interface. |
| modern frame | Laravel | The most powerful PHP framework with complete built-in API support. |
| Hybrid solution | Inertia.js | Laravel can be seamlessly integrated with React without writing an API. |
In a development environment, since React usually runs onlocalhost:5173, while PHP runs onlocalhost:8000, you will encounterCORS (Cross-Origin Resource Sharing)mistake. Be sure to include at the top of PHPAccess-Control-Allow-Originheader.
Vue.js is a progressive JavaScript framework for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. The core library only focuses on the view layer, making it very easy to get started and integrate with existing projects.
Vue combines HTML templates and JavaScript objects to allow developers to manage web content in an intuitive way. Currently, the mainstream recommendation is to use Vue 3.Composition API。
<!-- Vue template -->
<div id="app">
<h1>{{ message }}</h1>
<button @click="reverseMessage">Reverse text</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue;
createApp({
setup() {
const message = ref("Hello Vue!");
const reverseMessage = () => {
message.value = message.value.split('').reverse().join('');
};
return { message, reverseMessage };
}
}).mount('#app');
</script>
The instruction is withv-The special attribute of the prefix is responsible for binding data to DOM behavior.
| instruction | use | example |
|---|---|---|
| v-bind (:) | Bind HTML attributes | :src="imageUrl" |
| v-on (@) | Listen for events | @click="doSomething" |
| v-if / v-else | Conditional rendering | v-if="isVisible" |
| v-for | List rendering (similar to Array usage) | v-for="item in items" |
| v-model | Two-way data binding | v-model="inputText" |
You can easily integrate the previously mentionedslice()Or randomly select logic and manipulate components through the selector concept.
<script setup>
import { ref } from 'vue';
const allStocks = ref(['AAPL', 'TSLA', 'GOOGL', 'MSFT', 'AMZN', 'NVDA', 'META']);
const selectedStocks = ref([]);
// Combined with random selection logic
const pickFive = () => {
const shuffled = [...allStocks.value].sort(() => 0.5 - Math.random());
selectedStocks.value = shuffled.slice(0, 5);
};
</script>
<template>
<div>
<button @click="pickFive">Randomly select 5 stocks</button>
<ul>
<li v-for="stock in selectedStocks" :key="stock">{{ stock }}</li>
</ul>
</div>
</template>
Web API (Web Application Programming Interface) is an interface based on the HTTP protocol that allows the exchange of data between different systems and is often used for communication between the front end and the back end.
| method | use |
|---|---|
| GET | Get information |
| POST | Add new information |
| PUT | Update information |
| DELETE | Delete data |
Here is an example of using JavaScript to send a GET request:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Please enter a Chinese character and the system will display the phonetic notation of the character:
Not yet queried
Google ID login is an authentication method based on the OAuth 2.0 protocol that allows users to log in to third-party websites or applications using their Google accounts. This approach not only improves user convenience but also enhances security because users do not need to remember additional passwords.
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g_id_signin" data-type="standard" data-shape="rectangular" data-theme="outline" data-text="signin_with" data-size="large" data-logo_alignment="left"></div>
When the user clicks the login button, Google will perform authentication. After successful login, the user's information (such as email, name, etc.) will be sent back to your application, and you can perform subsequent processing based on this information.
Signing in with a Google ID provides users with a simple, secure way to sign in, and reduces the hassle of managing multiple accounts. By integrating Google's login system, developers can improve user experience and attract more users to their website or application.
If you want to embed a YouTube video, please modify the original link to embed format:
<iframe width="560" height="315" src="https://www.youtube.com/embed/{vid}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
in{vid}is the ID of the YouTube video.
For example, the video link ishttps://www.youtube.com/watch?v=dQw4w9WgXcQ, the embed code is as follows:
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
Such embedding format avoidsX-Frame-OptionsLimit so that the video can be displayed normally on the page.
Can be used directly in HTML<iframe>Embed YouTube videos,
But YouTube doesn'tDirect iframe embedding into "search results page" is not supported,
Because the search results are interactive content (including login, recommendation, tracking, etc. functions), they will be blocked by YouTube's embedding policy.
The following attempts to embed search results will fail or display an error message:
<!-- ⚠️ Unable to display properly -->
<iframe width="800" height="600"
src="https://www.youtube.com/results?search_query=cat+video">
</iframe>
This method will be blocked by the browser or YouTube and will display "Rejected to display in iframe".
---To embed a Search Results effect into a web page, useYouTube Data API v3Dynamically query videos, then use JavaScript to display the results yourself and create<iframe>。
Go toGoogle Cloud ConsoleEnable "YouTube Data API v3" and obtain the API key.
<div>
<input id="search" type="text" placeholder="Search keywords">
<button onclick="searchYouTube()">Search</button>
</div>
<div id="results" style="display:grid;grid-template-columns:repeat(auto-fill,300px);gap:1em;margin-top:1em;"></div>
<script>
const API_KEY = "YOUR_API_KEY";
function searchYouTube() {
const q = document.getElementById("search").value;
const url = `https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&maxResults=6&q=${encodeURIComponent(q)}&key=${API_KEY}`;
fetch(url)
.then(r => r.json())
.then(data => {
const container = document.getElementById("results");
container.innerHTML = "";
data.items.forEach(item => {
const vid = item.id.videoId;
const title = item.snippet.title;
const frame = document.createElement("iframe");
frame.width = "300";
frame.height = "170";
frame.src = `https://www.youtube.com/embed/${vid}`;
frame.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture";
frame.allowFullscreen = true;
const div = document.createElement("div");
const caption = document.createElement("p");
caption.textContent = title;
caption.style.fontSize = "14px";
caption.style.fontWeight = "bold";
div.appendChild(frame);
div.appendChild(caption);
container.appendChild(div);
});
});
}
</script>
---
<iframe>embedded, can be played directly.iframe.src = "https://www.youtube.com/embed/" + videoId + "?autoplay=1"Play automatically.snippet.thumbnailsShow thumbnail instead of embedding immediately.Node.js is a server-side execution environment based on the Chrome V8 JavaScript engine that allows developers to write back-end applications using JavaScript.
express:Lightweight web application frameworkfs: File system operationshttp:Create HTTP serverpath: Process file pathconst http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, Node.js!');
});
server.listen(3000, () => {
console.log('Server has been started, listening port 3000');
});
Node.js brings a unified language back-end development environment to front-end developers, improves development efficiency and is suitable for building modern network applications.
There are many ways to install Node.js, but for developers, it is strongly recommended to use version management tools (such as nvm) instead of directly downloading the official website installation file. This will prevent future permission errors and make it easy to switch between versions.
This is the most flexible approach and is suitable for computer environments that require long-term development.
nvm-setup.exeand install.nvm install lts //Install the latest long-term support version (LTS) nvm use lts // Switch and enable this version node -v // Confirm installation is successful
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install --lts //Install LTS version node -v // View version number
If you only need a quick installation and don't plan to change versions frequently, you can go toNode.js official website。
Installing Node.js will also include the following core components:
| Component name | illustrate |
|---|---|
| Node.js execution environment | The core that allows JavaScript to run on the server side. |
| npm (Node Package Manager) | The world's largest software registry for downloading packages (such as Vue, React). |
| Corepack | New tools for managing package managers (e.g. Yarn, pnpm). |
After the installation is complete, you can enter the following command to confirm that all tools are ready:
node -v // Display Node version, such as v20.11.0 npm -v // Display npm version, such as 10.2.4
If you get the error "Because script execution is prohibited on your system" when executing in Windows, please open PowerShell as an administrator and execute:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
nvm (Node Version Manager) is a version management tool designed specifically for Node.js. It allows you to install and switch multiple different versions of Node.js on the same computer, which is an essential tool for developers who need to maintain multiple projects using different Node versions at the same time.
When developing front-end projects (such as Vue, React), different projects may depend on specific Node.js versions. Downloading the installation file directly from the official website can only install a single version, but nvm solves the problem of version conflicts.
The following are nvm instructions frequently used during development:
// View all currently installed versions nvmls // View all Node.js versions available for installation in the cloud nvm ls-remote // Install a specific version (e.g. v18.16.0) nvm install 18.16.0 //Switch to the specified version nvm use 18.16.0 // Check the version currently in use nvmcurrent //Set the default version (the version that is automatically used every time the terminal is turned on) nvm alias default 18.16.0
when you executenvm usenvm will dynamically modify your system'sPATHEnvironment variables switch the address pointing to the Node executable file to the corresponding version folder, thereby achieving painless switching.
| operating system | Recommended versions/tools | Remark |
|---|---|---|
| macOS / Linux | nvm (nvm-sh) | The most original and stable version. |
| Windows | nvm-windows | It is not developed by the same team, but its functions are almost the same. You need to download the .exe to install. |
Install on Windowsnvm-windowsBefore, it is strongly recommended to uninstall Node.js that was originally installed on your computer to avoid environment variable conflicts that may cause switching failure.
NPM (Node Package Manager) is a package management tool for Node.js, used to manage libraries and modules of JavaScript code. It allows developers to install, share and version control the various packages required for their projects.
npm init: Initialize a new project and createpackage.jsonfile.npm install:Installpackage.jsonAll dependent packages listed in .npm install [package name]: Install the specified package.npm uninstall [package name]: Remove the specified package.npm update: Update installed packages.package.jsonIt is the core file of the project, recording the project name, version, description, dependent packages and other information. It is the basis of the NPM management suite.
NPM is the earliest and most widely used JavaScript package management tool, but later alternatives such as Yarn have emerged, providing faster installation speed and parallel processing. Both can be used in most Node.js projects.
Vite (French for "fast") is a new generation of front-end construction tools designed to provide an extremely fast development experience. It mainly consists of two parts: a development server (based on native ES modules) and a set of build instructions (packaged using Rollup).
Before Vite appeared, Webpack was the mainstream tool, but as the project grew larger, the compilation speed would become very slow. Vite solves this pain point:
You can quickly choose to create a Vue, React, Svelte or pure JavaScript project with one line of command.
// Use npm to create a project npm create vite@latest my-vue-app //Go to the folder and install the package cd my-vue-app npm install //Start the development environment npm rundev
in projectpackage.json, you will see the following commonly used scripts:
| instruction | use | illustrate |
|---|---|---|
| npm run dev | Start development server | Used during local development and supports real-time updates. |
| npm run build | Project packaging | Produce highly optimized static files (put into dist folder). |
| npm run preview | Preview packaging results | Simulate the running status after deployment locally. |
The configuration of Vite is very intuitive and is usually used to add plug-ins (Plugins) or set up a server proxy (Proxy).
import { defineConfig } from 'vite'
import vue from '@vue/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
port: 3000, // Modify the development server port number
open: true // Automatically open the browser on startup
}
})
Webpack:Like a fully functional "large-scale processing factory", all parts must be processed before starting operation. It is slower but extremely functional.
Vite:Like "Modern Express", it dynamically loads whatever parts you need, extremely fast and in line with modern browser standards.
Electron is an open source framework that allows developers to build cross-platform desktop applications using HTML, CSS, and JavaScript. It combines Chromium and Node.js to allow web technologies to access native system resources.
npm install --save-dev electron
// main.js
const { app, BrowserWindow } = require('electron');
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);
<!DOCTYPE html>
<html>
<body>
<h1>Hello, Electron! </h1>
</body>
</html>
npx electron .
electron-builderCan be used to generate installation filesTypeScript is a superset of JavaScript, developed by Microsoft. It adds a "Type System" to JavaScript and will eventually be compiled into pure JavaScript for execution in the browser. It solves the problem that JavaScript, as a weakly typed language, is difficult to maintain and error-prone in large projects.
By adding after the variable: typeto declare the type.
let name: string = "Gemini";
let age: number = 18;
let isStudent: boolean = true;
//array type
let stocks: string[] = ["AAPL", "TSLA", "NVDA"];
// Function parameters and return value types
function add(a: number, b: number): number {
return a + b;
}
This is one of the most powerful features of TypeScript, used to define the structure (Shape) of objects.
interface User {
id: number;
username: string;
email?: string; // Question mark indicates optional attribute
}
const newUser: User = {
id: 1,
username: "Alex"
};
Modern development environments such as Vite support TypeScript by default. Select when creating a projectvue-tsorreact-ts, Vite will automatically handletsconfig.jsonconfiguration.
// Use Vite to create a TS project npm create vite@latest my-ts-app -- --template vue-ts
Rewriting the previously mentioned random selection function into a TypeScript version will make it safer:
// Generic <T> allows this function to handle arrays of any type
function getRandomElements<T>(arr: T[], count: number = 5): T[] {
if (arr. length<= count) return [...arr];
const tempArray = [...arr];
const result: T[] = [];
for (let i = 0; i < count; i++) {
const randomIndex = Math.floor(Math.random() * tempArray.length);
result.push(tempArray.splice(randomIndex, 1)[0]);
}
return result;
}
const randomStocks = getRandomElements<string>(["AAPL", "TSLA", "GOOGL"], 2);
TypeScript files (.ts) cannot be executed directly in the browser, and their life cycle is as follows:
| stage | action | tool |
|---|---|---|
| writing period | Define types and write .ts code | VS Code + TS Engine |
| compile time | Check for type errors and remove type tags | tsc / Vite / esbuild |
| Execution period | Run pure .js files in the browser | Browser Engine |
Browser Extension is a small application used to extend browser functions, usually written in HTML, CSS, and JavaScript. It can modify web page content, add toolbar buttons, interact with background services, and improve user experience.
manifest.json: Describe the extended function name, version, permissions and entrance.popup.html: The interface displayed after clicking the toolbar icon.background.js: Background resident script, used to process events and logic.content.js: Scripts injected into web pages can directly manipulate the DOM.chrome://extensions/load.manifest.jsonand related files.my-extension/
├─ manifest.json
├─ popup.html
├─ popup.js
└─ icon.png
{
"manifest_version": 3,
"name": "Hello Extension",
"version": "1.0",
"description": "A simple Chrome extension example",
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
}
},
"permissions": []
}
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<style>
body { width:200px; font-family:sans-serif; text-align:center; }
button { margin-top:10px; padding:5px 10px; }
</style>
</head>
<body>
<h3>Hello from Chrome Extension</h3>
<button id="btn">Click me</button>
<script src="popup.js"></script>
</body>
</html>
document.getElementById("btn").addEventListener("click", () => {
alert("Button clicked!");
});
Place a PNG icon (recommended size 128x128) for the toolbar to display.
chrome://extensions/Chrome extensions are built on standard web technologies, so their core language is fully consistent with web development, which is an essential foundation.
To build more complex and reactive user interfaces (especially popups and options pages), common front-end frameworks can be used. Note, however, that it is generally not recommended to use heavyweight frameworks in background service workers that extend functionality.
In order to simplify the development process, handle code packaging, hot reloading (Hot Reloading) and cross-browser compatibility, the use of modern development tools is a trend.
| Tools/Kits | use | Advantages |
|---|---|---|
| Vite / Webpack | Bundler | Package multiple code files, styles, and resources into a browser-readable format to optimize code size. Vite is very popular for its fast hot module replacement (HMR). |
| WXT / Plasmo | Special framework for extended functions | A framework specifically designed for extension development, it can automatically handle Manifest file generation, TypeScript configuration, hot reloading and cross-browser support (Chrome, Firefox, Edge, etc.), greatly simplifying the development experience. |
| pnpm / npm / yarn | Package management tools | Manage third-party JavaScript libraries and tools that your project depends on. |
This is an essential tool for all Chrome extension development.
php.iniIt is the main configuration file of PHP and affects the execution mode and functions of PHP.
By modifying this file, you can adjust error output, memory limits, upload size, time zone, and more.C:\php\php.iniOr in the installation directory./etc/php/version number/apache2/php.inior/etc/php/version/cli/php.ini。php --iniQuery the configuration file used by the CLI.-cIf the parameter is specified, the path will be loaded first.php.ini。PHPRCthe specified directory.php --iniorphpinfo()query)./etc/php.iniorC:\Windows。; Set time zone
date.timezone = Asia/Taipei
; show error
display_errors = On
error_reporting = E_ALL
; Upload file size
upload_max_filesize = 20M
post_max_size = 25M
; Memory limit
memory_limit = 256M
; Maximum execution time (seconds)
max_execution_time = 30
php.iniAfterwards, you need to restart Apache, Nginx or PHP-FPM for it to take effect.phpinfo()Check the currently loadedphp.iniPath and parameter values.php.ini。.user.inior.htaccessOverwrite some settings.The Boolean value is the simplest data type in PHP. It can only represent two states: **true** or **false**. Boolean values are often used for control processes (e.g.if/elseconditional judgment) and logical operations.
You can use keywordstrueorfalseto define a Boolean variable. These keywords are not case-sensitive (for example,TRUE、Trueortrueare the same), but it is generally recommended to use lowercasetrueandfalseto comply with standard practice.
$is_active = true;
$is_logged_out = FALSE; // Although uppercase letters are possible, they are not recommended.
//Conditional judgment
if ($is_active) {
echo "<p>The user is currently active.</p>";
} else {
echo "<p>The user is currently inactive.</p>";
}
When PHP expects a Boolean value but is given another data type (e.g. inifcondition), PHP will automatically convert (or type cast) the value to a Boolean value.
The following values are considered false (called Falsy values):
falseitself.0(zero).0.0(zero).""or''。"0"(a string containing the single digit zero).array()or[]。NULL。All other values, including any non-zero number, any non-empty string (even"false"or" "[including spaces]), will be regarded as **true (true)** (called Truthy value).
$a = 0;
$b = "Hello";
$c = "";
$d = [1, 2];
$e = null;
echo "<h3>Falsy value example</h3>";
if (!$a) { // $a (0) converts to false
echo "<p>$a (integer 0) is treated as FALSE.</p>";
}
if (!$c) { // $c (empty string) converts to false
echo "<p>$c (empty string) is treated as FALSE.</p>";
}
if (!$e) { // $e (NULL) converts to false
echo "<p>NULL is treated as FALSE.</p>";
}
echo "<h3>Truthy value example</h3>";
if ($b) { // $b ("Hello") converts to true
echo "<p>$b (non-empty string) is treated as TRUE.</p>";
}
if ($d) { // $d (non-empty array) converts to true
echo "<p>Non-empty arrays are treated as TRUE.</p>";
}
You can also use(bool)orboolval()The function explicitly converts the variable to a Boolean value, which is useful when debugging or when strict type checking is required.
$f = "0"; // string of number zero $g = 100; // positive integer $f_bool = (bool)$f; $g_bool = boolval($g); echo "<p>The string '0' is converted to: "; var_dump($f_bool); // Output: bool(false) echo "</p>"; echo "<p>The integer 100 is converted to: "; var_dump($g_bool); // Output: bool(true) echo "</p>";
In PHP, comparison operators are used to compare two values (numbers or strings). According to the comparison result, it will be returnedtrueorfalse. Understanding the difference between "loose comparison" and "strict comparison" is the key to avoiding program bugs.
| operator | name | example | Conditions that result in true |
|---|---|---|---|
== |
equal to (loose) | $a == $b |
Values are equal (type comparison will be automatically converted) |
=== |
Congruent (strict) | $a === $b |
The values are equal and the types are also the same |
!= / <> |
not equal to | $a != $b |
Values are not equal |
!== |
Not congruent | $a !== $b |
Values are not equal or types are not the same |
> |
greater than | $a > $b |
$a is greater than $b |
< |
less than | $a < $b |
$a is less than $b |
>= |
Greater than or equal to | $a >= $b |
$a is greater than or equal to $b |
<= |
less than or equal to | $a <= $b |
$a is less than or equal to $b |
<=> |
spaceship operator | $a <=> $b |
Returns -1, 0, or 1 (PHP 7+) |
This is the most common area of confusion in PHP development. PHP is a weakly typed language.==Will try to convert variables of different types into the same type before comparing them, and===No conversion is performed at all.
This is true as long as the "values" are equal after conversion:
$a = 100; // integer (int)
$b = "100"; // string (string)
if ($a == $b) {
echo "Equal"; // This will be executed because PHP converts strings into numeric comparisons
}
The "value" must be exactly the same as the "data type":
$a = 100;
$b = "100";
if ($a === $b) {
echo "Equal";
} else {
echo "not equal"; // this will be executed because int is not equal to string
}
The shorthand syntax makes your code cleaner when dealing with comparison logic:
$result = ($a > $b) ? "A Big" : "B Big";$name = $input_name ?? "Visitor";(Provides a default value when the variable does not exist or is null).Safety advice:When performing authentication, permission checks, or API return value judgment, be sure to use===. For example checkstrpos()The return value of0(position) andfalse(not found) in==will be treated as the same, which will lead to logical errors.
In PHP, an array is a very useful composite data type that can store multiple values in a single variable. PHP's array is actually an ordered map. A map is a type that associates Values with Keys.
PHP's arrays can be roughly divided into three common forms based on the type of their keys:
Use consecutive integers as keys. If you don't specify a key when building the array, PHP will start with0Start automatically assigning integer indexes.
//Create an indexed array
$fruits = array("apple", "banana", "orange");
// Or use shorthand syntax (after PHP 5.4)
$colors = ["red", "green", "blue"];
//Access elements
echo $fruits[0]; // Output: apples
echo $colors[2]; // Output: blue
Use strings as keys (key names). This allows you to use meaningful names to access the values in the array.
//Create an associative array
$person = array(
"name" => "Xiao Ming",
"age" => 25,
"city" => "Taipei"
);
// Or use shorthand syntax
$scores = [
"Math" => 90,
"English" => 85
];
//Access elements
echo $person["name"]; // Output: Xiao Ming
echo $scores["English"]; // Output: 85
The values in the array are in turn another array. This is typically used to store tabular or hierarchical data.
$students = [
[
"name" => "Alice",
"scores" => ["Math" => 95, "Science" => 88]
],
[
"name" => "Bob",
"scores" => ["Math" => 78, "Science" => 92]
]
];
//Access elements (access Bob's Science scores)
echo $students[1]["scores"]["Science"]; // Output: 92
PHP provides hundreds of built-in functions for working with arrays. Here are some of the most commonly used ones:
count($array): Counts the number of elements in the array.print_r($array): Displays the structure and values of an array in a human-readable format (usually used for debugging).array_push($array, $value1, ...): Push (add) one or more elements to the end of the array.array_pop($array): Pops (removes and returns) the last element in the array.array_keys($array): Returns a new array composed of all key names in the array.array_values($array): Returns a new array consisting of all the values in the array.in_array($needle, $haystack): Check if a specific value exists in the array.array_key_exists($key, $array): Check if a specific key exists in the array.Commonly usedforeachLoop through all elements in the array:
$staff = ["Manager" => "Zhang San", "Engineer" => "Li Si", "Designer" => "Wang Wu"];
// Traverse the associative array (get keys and values)
foreach ($staff as $title => $name) {
echo $title . ": " . $name . "<br>";
}
// Traverse the indexed array (only get values)
$items = ["A", "B", "C"];
foreach ($items as $item) {
echo $item . "<br>";
}
strcasecmp()Perform case-insensitive string comparisons.
If the returned value is 0, it means that the two strings are equal.<?php
$str1 = "Hello";
$str2 = "hello";
if (strcasecmp($str1, $str2) === 0) {
echo "Strings are equal (ignoring case)";
} else {
echo "Strings are not equal";
}
?>
str_ireplace()。
<?php
$text = "Hello World";
$result = str_ireplace("hello", "Hi", $text);
echo $result; // Output "Hi World"
?>
ito ignore case.<?php
if (preg_match("/hello/i", "HeLLo PHP")) {
echo "Comparison successful";
}
?>
When processing file path strings in PHP, handwritten string slicing (such as usingexplode), because different operating systems (Windows uses\, for Linux/) are handled differently. PHP has several powerful functions built in to safely disassemble paths.
This is my most recommended function. It can disassemble the path into: directory name, complete file name, file extension, and file name without extension.
$path = "/var/www/html/assets/img/logo.png"; $info = pathinfo($path); echo $info['dirname']; // /var/www/html/assets/img echo $info['basename']; // logo.png echo $info['extension']; // png echo $info['filename']; // logo (PHP 5.2+ supported)
$path = "C:\projects\web\index.php"; echo basename($path); // index.php echo basename($path, ".php"); // index (remove the specified file extension) echo dirname($path); // C:\projects\web
It will resolve all relative path symbols (such as../or./), and returns the true absolute path on the operating system. If the file does not exist, it will be returnedfalse。
echo realpath("../../config.php");
//Output similar to: /var/www/config.php
---
In order to ensure that no errors occur during Windows development and Linux deployment, it is recommended to uniformly convert backslashes to forward slashes:
$path = "C:\User\Admin\Desktop\test.txt";
$safe_path = str_replace('\\', '/', $path);
// Result: C:/User/Admin/Desktop/test.txt
Manual splicing$dir . '/' . $fileprone to appear//Double slash error. Can be usedDIRECTORY_SEPARATOR(system delimiter) orrtrim:
$dir = "/var/www/html/"; $file = "index.php"; //Universal splicing method $full_path = rtrim($dir, '/\\') . DIRECTORY_SYSTEM_SEPARATOR . $file;
$allowed = ['jpg', 'png', 'gif'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (in_array($ext, $allowed)) {
echo "Correct format";
}
---
| function | Input example:/data/web/test.php |
Return results |
|---|---|---|
| pathinfo() | pathinfo($p) |
Returns an associative array (Array) containing all information |
| basename() | basename($p) |
test.php(Pure file name) |
| dirname() | dirname($p) |
/data/web(Table of contents) |
| realpath() | realpath("./test.php") |
/absolute/path/to/test.php(real path) |
To get the exact top-level directory name from a path string (e.g.var), the most robust method is to first convert the pathnormalization, and then useexplode()Deconstruct the string. Since the path usually starts with a slash, the first element of the disassembled array is often empty, which requires special handling.
This is the most common way, throughltrim()Remove the leading slash before splitting, and make sure the first position in the array is the name you want.
$path = "/var/www/html/assets/img/logo.png";
// 1. Remove the leftmost slash first to avoid the empty first element produced by explode
// 2. Split into arrays according to slashes
$parts = explode('/', ltrim($path, '/'));
// 3. Get the first element of the array
$rootDir = $parts[0];
echo $rootDir; // Output: var
If your path may come from Windows or Linux, it is recommended to unify the slash format first and filter out duplicate slashes.
$path = "/var/www/html/assets/img/logo.png";
//Convert to forward slashes uniformly and filter out empty elements
$parts = array_values(array_filter(explode('/', $path)));
$rootDir = $parts[0] ?? '';
echo $rootDir; // Output: var
If you don't want to process "specific strings", but want to know the root folder name of the web server, you can use$_SERVER:
// Assume DOCUMENT_ROOT is /var/www/html
$rootParts = explode('/', ltrim($_SERVER['DOCUMENT_ROOT'], '/'));
echo $rootParts[0]; // Output: var
---
| Target | Corresponding code | Example of results |
|---|---|---|
| top-level directory | explode('/', ltrim($path, '/'))[0] |
var |
| Previous directory | basename(dirname($path)) |
img |
| full directory path | dirname($path) |
/var/www/html/assets/img |
When working with paths, be sure to pay attention to whether there is a slash at the beginning of the path."/var"After splitting it will become["", "var"],and"var"After splitting it will become["var"]. useltrim($path, '/')This ensures that the result is consistent regardless of whether there is a slash at the beginning.
| Priority | illustrate |
|---|---|
| 1. | Specified absolute path or relative path: Directly specify the path of the file, and PHP will first search for the file under this path. |
| 2 | The current directory of the executable file: If the full path is not specified, PHP will first look for the file in the directory where the executable file is located. |
| 3 | include_path setting: If the file cannot be found in the execution directory, PHP will checkphp.iniset ininclude_pathpath. |
| 4 | File does not exist: If the file cannot be found in any of the above paths, a warning will be generated (Warning), and returnfalse。 |
can pass through$_SERVER['PHP_SELF']Get the file path of the current execution and then usebasenameGet file name:
<?php
$current_page = basename($_SERVER['PHP_SELF']);
echo "Current page name:" . $current_page;
?>
through$_SERVER['REQUEST_URI']Get the full URL path and then useparse_urlandbasenameParse file name:
<?php
$url_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$current_page = basename($url_path);
echo "Current page name:" . $current_page;
?>
If the URL contains query parameters, they can be processed separately:
<?php
$url_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$query_string = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
$current_page = basename($url_path);
echo "File name:" . $current_page . "<br>";
echo "Query parameters:" .$query_string;
?>
Assume the current URL ishttps://example.com/page.php?id=123:
Current page name: page.php
File name: page.php
Query parameters: id=123
In PHP, whenmain.phpuseincludeintroducesubpage.phpAt this time, the two files are actually "merged and executed". To obtain the "main program path" and "introduced file path" respectively, you need to use different super-global variables and constants.
Regardless of who imported the file, use the magic constant__FILE__Always points to the path of "the file where this code resides".
//Writing in subpage.php $thisFilePath = __FILE__; echo "Current file path: " . $thisFilePath; //Output similar to: /var/www/html/fullpath/subpage.php
when you aresubpage.phpWhen trying to figure out who the original entry point was, there are a few ways:
$_SERVER['SCRIPT_FILENAME'](most accurate)$mainPath = $_SERVER['SCRIPT_FILENAME'];
get_included_files()(advanced tracking)0This is the initial entry file.$allFiles = get_included_files(); $mainPath = $allFiles[0];
Please put the following code in yoursubpage.phpMedium test:
<?php
// 1. The path to the file itself that is introduced
$sub_page_path = str_replace('\\', '/', __FILE__);
// 2. The path of the main execution file
$main_page_path = str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']);
echo "Subpage Path: " . $sub_page_path . "<br>";
echo "Main Page Path: " . $main_page_path . "<br>";
?>
Tips: str_replace('\\', '/', ...)It is to unify the path formats of Windows (backslash) and Linux (forward slash), which is very practical in cross-platform development.
---
If you are not referring to the server hard drive path (Full Path), but the URL path on the browser, you should use:
| Target | grammar | illustrate |
|---|---|---|
| URL path | $_SERVER['REQUEST_URI'] |
Get as/project/main.php?id=1URL fragment. |
| script virtual path | $_SERVER['PHP_SELF'] |
Get the path of the main program on the web page (without parameters). |
Writing$mainTableView__whereclause, if you need to switch SQL conditions based on different main pages, you can write like this:
if (basename($_SERVER['SCRIPT_FILENAME']) == 'main.php') {
// Logic that is only executed when entering from main.php
}
includethe essence ofIn PHP, useincludeorrequire, you can think of it asDirectly "copy and paste" the code imported into the file into the current file. Therefore, both will share the same execution environment (Scope).
global?it's up to youlocation of call variable:
main.phpDefine variables and put them inlibrary.phpThe outermost layer uses it directly without any additional declaration.// main.php $var1 = "Apple"; include 'library.php'; // library.php echo $var1; // Output: Apple
library.phpinsideFunctionTo access it, you must declare it.
// library.php
function printVar() {
global $var1;
echo $var1;
}
include_oncemisunderstanding of passing parametersSpecial attention:PHPinclude_once Not supportedPass a second argument (like an array). Its only parameter is the file path string.
| Incorrect usage (❌) | Correct usage (✅) |
|---|---|
include_once('lib.php', ['v1' => $v1]); |
$v1 = "Data"; include_once 'lib.php'; |
| PHP will report an error because the number of parameters does not match. | Variables will automatically flow to the imported file. |
In order to avoid variable naming conflicts (namespace pollution), it is recommended to abandon the "directly dependent on global variables" writing method and use the following two methods instead:
Willlibrary.phpAs a pure toolbox, only functions are written in it, and variables are passed in through parameters.
// library.php
<?php
function processStock($name) {
return "Processing stocks: " . $name;
}
?>
// main.php
<?php
include_once 'library.php';
echo processStock("TSLA"); // Pass variables explicitly
?>
This is more common in modern PHP development (such as Laravel concepts) and can effectively organize the code.
// library.php
class StockTool {
public static function handle($var) {
return "Result: " . $var;
}
}
// main.php
include_once 'library.php';
echo StockTool::handle($var1);
1. don't wantexistincludePassing parameters in the statement is invalid.
2. Try to avoidglobal, use insteadfunction parametersPass, so that the code is easier to debug and maintain.
In PHP, there are three main core functions to check whether a variable has been set (defined):isset()、empty()andarray_key_exists(). Their operating logic is slightly different, and choosing the wrong one may lead to logic holes.
used to determine variablesHas it been declaredandIts value is notNULL。
$var = "Gemini";
if (isset($var)) {
echo "The variable has been set and is not NULL";
}
$var = null;,isset($var)Will send backfalse。Used to determine whether a variabledoes not exist, or its value is equivalent tofalse. it is equivalent to!isset($var) || $var == false。
The following values will beempty()regarded astrue:
""(empty string)0(integer 0)0.0(floating point number 0)"0"(String 0)nullfalse[](empty array)| grammar | Check target | Suitable for the scene |
|---|---|---|
isset($var) |
Whether the variable exists and is not NULL | Check the optional fields to make sure the variables are defined. |
empty($var) |
Does the variable have content? | Form validation (make sure the message is not empty and the quantity is not 0). |
is_null($var) |
Whether the variable is exactly NULL | When you just need to know if a variable was intentionally set to null. |
If you are inmain.phpPass variables tolibrary.php, it is recommended tolibrary.phpDo internal error-proofing checks:
// library.php
if (isset($var1)) {
echo "The received variable is:" . $var1;
} else {
echo "Warning: Variable var1 is not defined yet.";
}
This is a more concise way of writing it. If the variable is not set, it is given a default value.
// If $var1 is not set, $data is equal to 'default value' $data = $var1 ?? 'Default value';
If you pass the value from the front end, the check method is as follows:
if (isset($_GET['var1'])) {
$v1 = $_GET['var1'];
}
Tips:During the development phase, it is recommended to adderror_reporting(E_ALL);, so that if you access an undefined variable, PHP will directly spit outNotice: Undefined variableMind you.
debug_backtrace()It is a function used by PHP to obtain the current execution stack (call path). It is often used for debugging and recording call sources.
$trace = debug_backtrace();
print_r($trace);
debug_backtrace()An array will be returned, arranged in the order of the call:
file:File pathline:Program line numberfunction:The function name calledclass: Category name (if any)args: Pass in parametersfunction showCaller() {
$trace = debug_backtrace();
echo 'From: ' . $trace[1]['file'] . ' No. ' . $trace[1]['line'] . ' line';
}
include 'subpageA.php'; // Call showCaller() within subpageA.php
main.php include subA.phpsubA.php include subB.phpsubB.phpuse:$trace = debug_backtrace();
echo 'Current file:' . $trace[0]['file'] . "\n";
echo 'Previous level:' . $trace[1]['file'] . "\n"; // subA.php
echo 'Homepage:' . $trace[2]['file'] . "\n"; // main.php
debug_backtrace()Is the most practical way to view the source of include/function callserror_log()Is a function used by PHP to log errors or custom messages.
It is often used for debugging, tracking program flow, and recording exceptions without affecting screen output.<?php
error_log("This is a test message");
?>
<?php
$data = ["a" => 1, "b" => 2];
error_log(print_r($data, true));
?>
<?php
error_log("Write custom file", 3, "D:/logs/php_debug.log");
?>
<?php
error_log("[INFO] program starts execution");
error_log("[WARN] parameter is empty");
error_log("[ERROR] Database connection failed");
?>
php.inicontrol:log_errors = On
error_log = "D:/logs/php_errors.log"
If not seterror_log, the default will be:<?php
try {
throw new Exception("Exception occurred");
} catch (Exception $e) {
error_log($e->getMessage());
}
?>
display_errors, just useerror_logWhen you use error_log() in PHP to record strings containing Chinese characters, the log file will often appear in hexadecimal encoding such as \xe6\xb2\x92 format. This is usually not a programming error, but the result of the server (Apache/Nginx) forcing non-ASCII characters to be escaped for security or compatibility reasons.
This is the simplest and most effective way to do it. By directly manipulating files, the server's filtering mechanism for error_log() can be bypassed.
function write_utf8_log($message) { $log_file = DIR . '/debug.log'; $timestamp = date('Y-m-d H:i:s'); // Use FILE_APPEND mode to write raw bytes file_put_contents($log_file, "[$timestamp] $message" . PHP_EOL, FILE_APPEND | LOCK_EX); }
// Calling example $title = $_GET["title"]; write_utf8_log("Title content: " . $title);
If you want to retain the path setting of error_log(), you can use json_encode with the JSON_UNESCAPED_UNICODE parameter. This will force PHP to output in UTF-8 format, but it may still be escaped twice in some server environments.
$title = $_GET["title"]; error_log('title: ' . json_encode($title, JSON_UNESCAPED_UNICODE));
If you are using Apache 2.4+, you can try modifying ErrorLogFormat to adjust the escaping behavior of log output.
1. Define the format in the Apache configuration file (such as httpd.conf):
ErrorLogFormat "[%t] [%l] [pid %P] %F: %E: [client %a] %M"
2. Make sure the operating system language supports UTF-8. Modify /etc/apache2/envvars in Ubuntu:
export LANG=en_US.UTF-8 export LC_ALL=en_US.UTF-8
If the log has been generated and you cannot change the server settings, you can use the following method to view the original Chinese:
| method | advantage | shortcoming |
|---|---|---|
| Custom log (file_put_contents) | 100% display in Chinese, no permission required | Requires manual management of file size and permissions |
| JSON_UNESCAPED_UNICODE | Minimal code changes | Still affected by server global configuration |
| Modify Apache configuration | Solve all system log problems from the root cause | Administrator rights are required, restart the service |
parse_url()function collocationPHP_URL_QUERYConstant to retrieve the query string portion from the complete URL. For example:$url = "https://example.com/page.php?name=John&age=30&lang=php";
$query = parse_url($url, PHP_URL_QUERY); // The result is "name=John&age=30&lang=php"
parse_str()The function parses a query string into an associative array, where each set of names and values is automatically decoded and converted into array elements:parse_str($query, $params);
at this time$paramsThe content is:[
"name" => "John",
"age" => "30",
"lang" => "php"
]
<?php
$url = "https://example.com/page.php?name=John&age=30&lang=php";
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);
foreach ($params as $key => $value) {
echo "$key = $value\n";
}
?>
name = John
age = 30
lang = php
parse_url()Only the query part will be retrieved and the content will not be parsed.parse_str()Can handle URL encoding, e.g.%20will be converted to spaces.tags[]=php&tags[]=htmlwill be converted into an array.Get using JavaScript<h1>content and then send it to PHP:
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>Get H1 content</title>
<script>
function sendH1Content() {
var h1Content = document.querySelector('h1').innerText;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'process.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('h1Content=' + encodeURIComponent(h1Content));
}
window.onload = sendH1Content;
</script>
</head>
<body>
<h1>This is the title of the page</h1>
</body>
</html>
existprocess.phpReceive and process H1 content in:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$h1Content = $_POST['h1Content'] ?? '';
// Process $h1Content, such as storing it in the database or performing other operations
echo "Received H1 content: " . htmlspecialchars($h1Content);
}
?>
If the HTML file is static, you can use PHP to read the file and parse it:
<?php
$htmlContent = file_get_contents('path/to/your/file.html');
preg_match('/<h1>(.*?)<\/h1>/', $htmlContent, $matches);
$h1Content = $matches[1] ?? '';
// handle $h1Content
echo "H1 content: " . htmlspecialchars($h1Content);
?>
The most common way is to use JavaScript to get the content on the client side and then send it to PHP for processing via AJAX. Server-side parsing is typically used for static content and is not recommended for dynamically generated pages.
abc.phpSeveral have been printed<h2>, then includesubpage.phpWhen , the content cannot be captured from the output HTML.
The correct way is to ─ **pass the content of the last <h2> into subpage.php** (variable) from abc.php before include, and it will be used by subpage.php.<!-- abc.php -->
<h2>AAA</h2>
<h2>BBB</h2>
<h2>lasth2</h2>
<?php
$last_h2 = "lasth2";
include "subpage.php";
?>
<!-- subpage.php -->
<?php
echo "The last H2 on the homepage is: " . $last_h2;
?>
<!-- abc.php -->
<?php
ob_start(); // Start buffering
?>
<h2>AAA</h2>
<h2>BBB</h2>
<h2>lasth2</h2>
<?php
$html = ob_get_clean(); // Get all output and clear the buffer
preg_match_all('/<h2>(.*?)<\\/h2>/i', $html, $matches);
$last_h2 = end($matches[1]); //The content of the last h2
include "subpage.php";
//Finally print out the original HTML
echo $html;
?>
<!-- abc.php -->
<?php
$h2_list = ["AAA", "BBB", "lasth2"];
?>
<h2>AAA</h2>
<h2>BBB</h2>
<h2>lasth2</h2>
<?php
$last_h2 = end($h2_list);
include "subpage.php";
?>
ob_start()+ Regular expression parsingurlencode()Function is used to URL encode (Percent-encoding) a string. When passing data as URL parameters, this is a required step to ensure that all special characters are transferred and parsed correctly.
string urlencode(string $string): stringThis function converts the given string into a URL-safe format. It replaces all non-alphanumeric characters except the minus sign (-), bottom line (_), period (.) and tilde (~) outside.
Replaced special characters will be replaced with percent signs (%) followed by the two-digit hexadecimal representation of the character's ASCII value (for example, a space $\rightarrow$%20)。
?、&、=、/) has a special meaning. If these characters are included in the parameters, the browser or server may misunderstand the structure of the URL.urlencode()These characters are encoded in UTF-8 format.urlencode()will convert spaces to plus signs (+) or%20(Althoughurlencode()What is produced is+, but in URL parameters, both representations represent spaces).$data = "PHP Array with $100 & 50% off"; $encoded_data = urlencode($data); echo "<h3>Special characters and Chinese examples</h3>"; echo "<p>Original string: " . htmlspecialchars($data) . "</p>"; echo "<p>Encoding result: " . htmlspecialchars($encoded_data) . "</p>"; // Output results are similar: PHP+array and +%24100+%26+50%25+offer // (Chinese 'array' will be encoded as %E9%99%A3%E5%88%97, etc.)
Suppose you need to change the query stringq_strSecurely appended to API URL.
$api_base = "http://api.example.com/search"; $search_query = "Mobile Photography Tips (2025)"; // Ensure query string security $encoded_query = urlencode($search_query); //Construct the final URL $final_url = $api_base . "?q_str=" . $encoded_query; echo "<h3>Construction URL Example</h3>"; echo "<p>Query string: " . htmlspecialchars($search_query) . "</p>"; echo "<p>Final URL: " . htmlspecialchars($final_url) . "</p>"; // The final URL is similar: http://api.example.com/search?q_str=%E6%89%8B%E6%A9%9F%E6%94%9D%E5%BD%B1%E6%8A%80%E5%B7%A7+%282025+%E5%B9%B4%29
PHP has another similar functionrawurlencode(), the main difference between them is the handling of spaces:
urlencode(): Convert spaces to plus signs (+). This is typically used to encode the value of a **GET parameter** (e.g.?key=valueinvaluepart).rawurlencode(): Convert spaces to%20. This is consistent withRFC 3986A more restrictive definition, typically used to encode the **Path Segments** (Path Segments) of a URL, or when you need precise%20rather than+hour.$space_test = "This is a test"; echo "<h3>urlencode() vs rawurlencode()</h3>"; echo "<p>urlencode(): " . urlencode($space_test) . "</p>"; // Output: This+is+a+test echo "<p>rawurlencode(): " . rawurlencode($space_test) . "</p>"; // Output: This%20is%20a%20test
ob_start(): Enable output buffering.ob_get_contents(): Get the current buffered content.ob_end_clean(): End buffering and clear without output.ob_end_flush(): End buffering and output content.ob_get_clean(): Get the content and end buffering.<?php
ob_start(); // Start output buffering
echo "Hello World!";
$content = ob_get_clean(); // Get and clear buffer content
echo strtoupper($content); // Output the modified content: HELLO WORLD!
?>
<?php
ob_start();
register_shutdown_function(function () {
$html = ob_get_clean();
echo "<div class='container'>" . $html . "</div>";
});
?>
<h1>Content title</h1>
<p>This is the content paragraph. </p>
<h2>Title and the block below it, and add the corresponding image on the right. The image files are named in orderh2-1.jpg、h2-2.jpg... and so on, it needs to be placed in the designated image file folder in advance.h2-image-right.php):
<?php
ob_start();
function add_images_next_to_h2($html) {
$pattern = '/(<h2.*?>.*?<\/h2>)(.*?)(?=<h2|\z)/is';
$index = 1;
return preg_replace_callback($pattern, function($matches) use (&$index) {
$h2 = $matches[1];
$body = $matches[2];
$imgPath = "/images/h2-$index.jpg";
$imgFile = $_SERVER['DOCUMENT_ROOT'] . $imgPath;
if (file_exists($imgFile)) {
$output = "<div style='display: flex; align-items: flex-start; gap: 20px; margin-bottom: 1.5em;'>";
$output .= "<div style='flex: 1;'>" . $h2 . $body . "</div>";
$output .= "<img src='$imgPath' style='max-width: 200px; height: auto; border: 1px solid #ccc;'>";
$output .= "</div>";
} else {
$output = $h2 . $body;
}
$index++;
return $output;
}, $html);
}
register_shutdown_function(function() {
$html = ob_get_clean();
echo add_images_next_to_h2($html);
});
?>
/images/folder, for example:/images/h2-1.jpg/images/h2-2.jpg/images/h2-3.jpg<?php include "h2-image-right.php"; ?>
<h2>First paragraph title</h2>
<p>This is the content of the first paragraph. </p>
<h2>Second paragraph title</h2>
<p>This is the content of the second paragraph. </p>
<h2>The order of appearance corresponds to that, please name accordingly.<h2> ~ Content belowIt is a flex block, suitable for pure content pages.ob_start()。Checking server logs is an important way to identify search engine bots. Here are some examples of User-Agent for search engine robots:
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)
Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)Check the websiterobots.txtFile that lets you learn which search engine robots are allowed or blocked from accessing certain parts of your website. For example:
User-agent: *
Disallow: /private/
Search engine bots usually have IP addresses from a specific range. You can compare whether the visitor's IP address falls within these ranges. For example:
Tools can be used to verify whether the visitor's IP actually comes from a search engine.
The following is an example of how to use PHP on the server side to perform User-Agent checking:
<?php
$userAgent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($userAgent, 'Googlebot') !== false) {
echo "This is Googlebot traffic";
} else {
echo "This is not search engine robot traffic";
}
?>
Use Google Analytics or other website analytics tools to help track traffic sources. These tools typically filter most bot traffic automatically.
The hash value of a URL refers to the part after the "#" symbol in the URL, also known as the fragment identifier (Fragment Identifier). It is typically used to identify a location or state within a page.
Here are some common URL Hash examples:
https://example.com/page#section1https://example.com/app#/dashboardhttps://example.com/search#filter=activeid。<script>
// Get the Hash value of the URL
const hashValue = window.location.hash.substring(1);
//Display Hash value
console.log("Hash value is:", hashValue);
</script>
<?php
//Mock URL
$url = "http://example.com/page#section2";
// Use parse_url to parse Hash values
$parsedUrl = parse_url($url);
$hash = isset($parsedUrl['fragment']) ? $parsedUrl['fragment'] : null;
// Output Hash value
if ($hash) {
echo "The Hash value is: " . htmlspecialchars($hash, ENT_QUOTES, 'UTF-8');
} else {
echo "There is no Hash part in the URL.";
}
?>
window.location.hash。namepropertyAlthough less commonly used, it is possible tonameAdd an attribute<a>tag and place it before the target tag.
<a name="specific-heading1"></a> <h3>Target title 1</h3> <a href="#specific-heading1">Link to specific heading</a>
Effect:
data-attributeWith JavaScriptBy setting custom properties, such asdata-anchor, and use JavaScript to handle the jump behavior.
<h3 data-anchor="heading-1">Target heading 3</h3>
<a href="#" onclick="jumpToHeading('heading-1')">Link to specific heading</a>
<script>
function jumpToHeading(anchor) {
const target = document.querySelector(`[data-anchor="${anchor}"]`);
if (target) {
target.scrollIntoView({ behavior: 'smooth' });
}
}
</script>
Effect:
h2text content with JavaScriptby searchh2text content to target, using JavaScript to dynamically target the target.
<h3>Target title 5</h3>
<a href="#" onclick="jumpToText('Target Title')">Link to specific title</a>
<script>
function jumpToText(text) {
const target = Array.from(document.querySelectorAll('h2')).find(el => el.textContent === text);
if (target) {
target.scrollIntoView({ behavior: 'smooth' });
}
}
</script>
Effect:
cURL is a library used in PHP to send HTTP requests. It supports GET, POST, PUT, DELETE and other methods, and is often used for API data access.
curl_init()curl_setopt()curl_exec()curl_close()<?php
$url = "https://api.example.com/data";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
<?php
$url = "https://api.example.com/post";
$data = ['name' => 'Test', 'email' => '[email protected]'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
<?php
$url = "https://api.example.com/json";
$data = json_encode(['id' => 123]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
CURLOPT_URL: Set destination URLCURLOPT_RETURNTRANSFER: Whether to return the result (not output directly)CURLOPT_POSTFIELDS:Sent informationCURLOPT_HTTPHEADER: Custom HTTP headers<?php
if(curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
?>
In PHP, check whether a specific network port (Port) is listening, usually to confirm whether the local or remote service is running and accepting connections. The most common method is to use Socket related functions to try to establish a TCP connection.
fsockopen()Function is used to open a network connection or Unix domain Socket connection. If the connection is successful, it means that the port is listening; if the connection fails, it usually means that the port is not open or blocked by a firewall.
/**
* Check if the port on the specified IP/hostname is listening
*
* @param string $host The host name or IP address to check
* @param int $port The port number to be checked
* @param int $timeout Connection timeout seconds
* @return bool If the connection is successful, return true; otherwise return false
*/
function is_port_listening(string $host, int $port, int $timeout = 2): bool {
// Establish a Socket connection. The @ symbol is used to suppress connection error messages.
$connection = @fsockopen($host, $port, $errno, $errstr, $timeout);
if (is_resource($connection)) {
// If $connection is a resource type, it means the connection is successful
fclose($connection); //Close the connection immediately after success
return true;
} else {
// The connection failed. The port may not be open or the service may not be running.
// Optional: You can print $errstr and $errno here for debugging
// echo "Connection failed: $errstr ($errno)<br>";
return false;
}
}
// --- Test example ---
$remote_host = 'www.google.com';
$remote_port = 80; // Check Google's HTTP port
$local_host = '127.0.0.1';
$local_web_port = 80; // Check the port of the local web server
$unoccupied_port = 65432; // Assume this port is not in use
echo "<h3>Port monitoring check results</h3>";
// Check the remote service
if (is_port_listening($remote_host, $remote_port)) {
echo "<p>{$remote_host}:{$remote_port} is listening (connection successful).</p>";
} else {
echo "<p>{$remote_host}:{$remote_port} is not open or the connection failed.</p>";
}
// Check the local web server (if your web server is running on port 80)
if (is_port_listening($local_host, $local_web_port)) {
echo "<p>{$local_host}:{$local_web_port} is listening (Web server running).</p>";
} else {
echo "<p>{$local_host}:{$local_web_port} is not listening.</p>";
}
// Check for an unoccupied port
if (is_port_listening($local_host, $unoccupied_port)) {
echo "<p>{$local_host}:{$unoccupied_port} is listening.</p>";
} else {
echo "<p>{$local_host}:{$unoccupied_port} is not listening (expected result).</p>";
}
If you need lower-level Socket operations (such as setting options, non-blocking mode, etc.), you can use PHP's Socket function library (need to enablephp_socketsextension).
function is_port_listening_socket(string $host, int $port): bool {
// Create a TCP/IP Socket
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
// echo "socket_create failed: " . socket_strerror(socket_last_error()) . "<br>";
return false;
}
//Try to connect
// socket_connect() will try to establish a connection on the specified host and port
$result = @socket_connect($socket, $host, $port);
socket_close($socket);
return ($result !== false);
}
$timeoutvalue (e.g. 2-5 seconds). Without this setting, your script may block for a long time when the target host is unreachable.fsockopen()It will still fail.fsockopen()Functions are generally not included in PHP configuration filesallow_url_fopenA limitation of the command because it operates directly on network Sockets.$hostset to127.0.0.1orlocalhost。
In PHP, to get the results of a Web API and parse JSON, you typically usefile_get_contents()or cURL library to send HTTP requests, and then usejson_decode()Function to parse the returned JSON string.
For a simple GET request,file_get_contents()is a quick method. But if the API requires specific HTTP headers or more complex requests, cURL is more suitable.
$api_url = 'https://jsonplaceholder.typicode.com/posts/1'; // Sample API URL
// Get the content returned by the API (JSON format string)
$json_data = @file_get_contents($api_url);
if ($json_data === FALSE) {
echo "Unable to obtain API data or API request failed.";
} else {
// Parse JSON string into PHP array or object
// The second parameter is set to true and it will be parsed into an associative array.
// Set to false (default) to parse into an object.
$data = json_decode($json_data, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
echo "JSON parsing error:" . json_last_error_msg();
} else {
echo "<h3>API return data (associated array)</h3>";
//Example: access specific fields in data
echo "<p>title (title): " . htmlspecialchars($data['title']) . "</p>";
echo "<p>Content (body): " . htmlspecialchars($data['body']) . "</p>";
// Output the complete structure for inspection
echo "<h4>Complete data structure (print_r)</h4>";
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
cURL provides more control, such as setting request methods (POST, PUT, DELETE), headers, timeouts, etc.
$api_url = 'https://jsonplaceholder.typicode.com/posts/2';
//Initialize cURL session
$ch = curl_init();
//Set cURL options
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the result as a string instead of outputting it directly
//Execute cURL session and get the results
$json_data = curl_exec($ch);
// Check if an error occurred
if (curl_errno($ch)) {
echo "cURL error:" . curl_error($ch);
$data = null;
} else {
// Parse JSON
$data = json_decode($json_data, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
echo "JSON parsing error:" . json_last_error_msg();
}
}
// Close cURL session
curl_close($ch);
if ($data !== null) {
echo "<h3>API return data (cURL example)</h3>";
echo "<p>title (title): " . htmlspecialchars($data['title']) . "</p>";
echo "<p>User ID (userId): " . htmlspecialchars($data['userId']) . "</p>";
}
json_decode($json_string, $associative)true, then return the associated array; iffalse(default), the object is returned.PHPexec()function andshell_exec()、system()Similarly, it is essentially synchronous blocking, that is, the PHP script will wait for the external command to complete before continuing. To execute external commands without blocking the main PHP program (implementing "asynchronous" or "background execution"), we must rely on the characteristics of the Shell itself to separate the commands.
The key to achieving non-blocking execution is when you passexec()Add specific Shell syntax to the command string:
&:** This is the core symbol for pushing commands to background execution.> /dev/null 2>&1:** This is key to preventing PHP from blocking. It redirects both standard output (STDOUT) and standard error output (STDERR) to an empty device/dev/null. Without redirection, even if using&symbol, some versions of PHP may still wait for the I/O stream to close, causing spurious blocking.nohup(Optional but recommended): ** On Linux/Unix systems, usenohupThis ensures that the process continues to run after the web server terminates, such as when the HTTP request ends or the user closes the browser.This example is suitable for short-lived background tasks that do not need to run after the HTTP request is completed.
$command_to_run = 'php /path/to/my_long_task.php arg1 arg2'; // Combine non-blocking commands // 1. The command itself // 2. Direct STDOUT to /dev/null // 3. Direct STDERR (2) to STDOUT (&1) // 4. Use the & symbol to push the background $async_command = $command_to_run . ' > /dev/null 2>&1 &'; $output = []; $return_var = 0; //Execute non-blocking commands exec($async_command, $output, $return_var); echo "<h3>Asynchronous execution result (exec)</h3>"; echo "<p>The command has been sent to background execution.</p>"; echo "<p>PHP scripts will continue execution immediately and will not wait for external scripts to complete.</p>"; echo "<p>The output array (\$output) returned by exec() will be almost empty.</p>";
This example usesnohupTo ensure that background tasks are completely separated from the PHP web server's parent process, the tasks will continue to run even if the web server is shut down.
$command_to_run = '/usr/bin/python3 /path/to/process_data.py'; $log_file = '/var/log/my_app/task_log.log'; // Special log file // Ensure command parameters are properly escaped to prevent shell injection attacks $safe_command = escapeshellcmd($command_to_run); // Direct output and error output to the log file instead of /dev/null $detached_command = 'nohup ' . $safe_command . ' >> ' . escapeshellarg($log_file) . ' 2>&1 &'; exec($detached_command); echo "<h3>Use nohup to detach the process</h3>"; echo "<p>The command was started using nohup and directed output to a log file.</p>"; echo "<p>The task will continue to run in the background until completed.</p>";
Security is the most important consideration when you execute external commands. **Never** pass unsanitized or escaped user input toexec()or other shell executable functions. PHP provides two functions to assist in processing:
escapeshellcmd($command): Escape **the entire command string** to prevent malicious users from inserting multiple commands.escapeshellarg($arg):Escape **single parameter** to ensure that the parameter is treated as a single string.$user_input = "test; rm -rf /"; // Potentially malicious input
// Error: Unsafe practice
// exec('my_script.sh ' . $user_input);
// Correct: safe approach
$safe_input = escapeshellarg($user_input);
$safe_command = 'my_script.sh ' . $safe_input;
//Execution result: my_script.sh 'test; rm -rf /' (treated as a single parameter)
exec()shell_exec()passthru()proc_open()(Advanced)<?php
$cmd = "python3 myscript.py 123";
$output = shell_exec($cmd);
echo $output;
?>
<?php
$arg1 = 100;
$arg2 = "hello";
$cmd = "python3 script.py " . escapeshellarg($arg1) . " " . escapeshellarg($arg2);
$result = shell_exec($cmd);
echo $result;
?>
#script.py
importsys
a = sys.argv[1]
b = sys.argv[2]
print(f"Input parameters: {a}, {b}")
<?php
exec("python3 test.py", $output_lines, $status);
echo "<pre>";
print_r($output_lines);
echo "</pre>";
?>
<?php
$descriptor = [
0 => ["pipe", "r"],
1 => ["pipe", "w"],
2 => ["pipe", "w"]
];
$process = proc_open("python3 calc.py", $descriptor, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], "50\n");
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[2]);
proc_close($process);
echo "Output: $output<br>";
echo "Error: $error<br>";
}
?>
/usr/bin/python3orC:\\Python39\\python.exeescapeshellarg()Prevent command injectionphp -mConfirm loadingphp-gtkMods.<?php
if (!class_exists('gtk')) {
die("PHP-GTK has not been installed\n");
}
$window = new GtkWindow();
$window->set_title("PHP-GTK Example");
$window->set_size_request(300, 200);
$window->connect_simple('destroy', array('Gtk', 'main_quit'));
$button = new GtkButton("Click me");
$button->connect_simple('clicked', function() {
echo "Button clicked!\n";
});
$window->add($button);
$window->show_all();
Gtk::main();
?>
Electron(Based on Chromium and Node.js) Create a desktop GUI, and the backend can still call PHP programs.
This allows you to build beautiful cross-platform applications using HTML/CSS/JavaScript and communicate with PHP via API.php -S localhost:8000),
Then use the browser to open the page, and it will look like a desktop application. With PWA (Progressive Web App), it can also be installed as a desktop icon.A Single Page Application (SPA) is a web application or website model that interacts with users by dynamically rewriting the current page instead of loading an entire new page from the server. This approach avoids interruptions between page switches and brings the user experience closer to a desktop application.
In the traditional model, each time a link is clicked, a new HTML file is requested from the server; in SPA, the necessary HTML, CSS, and JavaScript are downloaded only on the first load, and subsequent data exchange is completed through AJAX or Fetch API.
| characteristic | SPA (Single Page Application) | MPA (Multiple Page Application) |
|---|---|---|
| Page loading | Load only once, partially updated | Reload the entire page with each operation |
| User experience | Smooth, no jump feeling | There is an obvious white screen and a sense of waiting |
| Server load | Lower (transmits JSON data only) | Higher (HTML must be rendered every time) |
| SEO optimization | More difficult and requires additional processing | Easy and naturally search engine friendly |
This is a framework-independent, using only native JavaScript to simulate the logic of SPA switching content:
<!-- index.html -->
<nav>
<a href="#home" onclick="route()">Homepage</a>
<a href="#trading" onclick="route()">Trading charts</a>
</nav>
<div id="content">
<!-- Dynamic content will be injected here -->
</div>
<script>
const routes = {
"#home": "<h2>Welcome back</h2><p>This is your dashboard.</p>",
"#trading": "<h2>Real-time Quotes</h2><div id='tv-container'>Chart loading...</div>"
};
function route() {
const hash = window.location.hash || "#home";
const contentDiv = document.querySelector("#content");
contentDiv.innerHTML = routes[hash];
// If you switch to the trading page, you can initialize the previous TradingView Widget here
if (hash === "#trading") {
// initTradingView();
}
}
// Monitor URL changes
window.addEventListener("hashchange", route);
// initial load
route();
</script>
advantage:Fast speed, reduced bandwidth consumption, and separate front-end and back-end development (the back-end only needs to provide API).
shortcoming:The initial loading time is long (First Load), and SEO needs to be compensated through SSR (server-side rendering) or pre-rendering technology.
When developing a single-page application (SPA), choosing an appropriate framework solution can significantly improve development efficiency and code maintainability. The current market is dominated by three mainstream frameworks, with many emerging up-and-comers.
Developed and maintained by Meta (Facebook), it is currently the most used UI function library in the world. It introduces Virtual DOM (Virtual DOM) and JSX syntax, emphasizing componentization and one-way data flow.
Developed by You Yuxi, it is famous for its "progressive" framework. Its learning curve is relatively gentle, and the official provides a very complete tool chain, which is very suitable for projects that pursue development efficiency.
A complete framework maintained by Google, written in TypeScript. It provides a "Family Bucket" solution, including all necessary functions such as routing, form verification, and HTTP clients.
In addition to the above three major frameworks, many alternatives for performance optimization have emerged in recent years:
| Frame name | Features |
|---|---|
| Svelte | No virtual DOM, the program code is converted into efficient native JS during the compilation phase. |
| SolidJS | Similar to React syntax, but with ultimate running performance. |
| Preact | A lightweight version of React, only about 3KB in size and highly compatible. |
When choosing a framework, it is generally recommended to consider the following benchmarks:
In the Python ecosystem, SPA (Single Page Application) development solutions are mainly divided into two categories: one uses Python as a back-end API, and the other uses a specific framework that allows developers to automatically generate a front-end interface with SPA features by simply writing Python code.
These frameworks are the most popular because they do not require developers to have HTML/CSS/JS knowledge to develop instantly interactive single-page web pages.
This type of framework attempts to challenge the traditional React/Vue + FastAPI model and make full-end development more unified.
| Frame name | Features | Technical architecture |
|---|---|---|
| Reflex (formerly known as Pynecone) | Written in pure Python and compiled into a React application. | Python + Next.js / Tailwind |
| NiceGUI | Extremely simple syntax, suitable for controlling hardware, gadgets or simple web pages. | Python + Vue / Quasar |
| Flet | A Python framework based on Flutter that can be published as a web SPA and desktop application at the same time. | Python + Flutter |
This is the most standard commercial software development model. Python is only responsible for logic and data, and the front-end is left to the professional JavaScript framework.
// Architecture diagram Backend (Python): FastAPI / Django Ninja / Flask Transport protocol: RESTful API or WebSocket Front-end (JavaScript): Vue.js / React / Svelte (responsible for rendering SPA)
This is a very popular trend in recent years. HTMX allows traditional Python web frameworks (such as Django or Flask) to achieve the effect of AJAX partial page update without writing complex JavaScript.
# Django + HTMX example (partial update button)
# After clicking, only the #result area will be replaced and the web page will not be refreshed.
<button hx-post="/get-data/" hx-target="#result">
Click me to get data
</button>
<div id="result">Waiting...</div>
The core concept of this type of solution is "return to HTML". They advocate that there is no need to write complex JavaScript frameworks to achieve the dynamic effects of SPA.
WebAssembly allows developers to write browser-side logic using high-performance languages such as C++, Rust or Go, breaking the monopoly of JavaScript.
| language | main frame | feature |
|---|---|---|
| C# / .NET | Blazor WebAssembly | Allow .NET developers to write front-ends in C# instead of JS. |
| Rust | Yew / Leptos | Extreme execution performance and strong type safety. |
| Go | Hugo / TinyGo | Compilation is extremely fast and suitable for performing logically complex operations. |
This type of solution generates all pages into static HTML files at "build time", which loads very quickly and is very SEO-friendly.
The solution launched by Google uses Dart language. It does not use the standard HTML/CSS rendering path, but draws the entire interface through Canvas.
// Flutter logic example
void main() {
runApp(const MyApp());
}
// The interface is completely drawn by Canvas, which is suitable for transplanting apps with high visual consistency.
For internal enterprise tools or quick launch requirements, SPA can be created without handwriting coding.
| plan | Applicable situations | Technical threshold |
|---|---|---|
| HTMX | Upgrading traditional websites with a sense of interactivity | Low (only backend language required) |
| WebAssembly | Image processing, complex operations, games | High (requires compilation language foundation) |
| Astro (SSG) | Blog, documents, official website | middle |
| Flutter for Web | App is published simultaneously to the web page | Medium (requires Dart) |
Traditional web architectures such as PHP + JavaScript are commonly used in server-side deployments, but cannot effectively prevent source code from being accessed or copied, so they are not suitable for commercial licensing and deployment in untrusted environments. To solve this problem, the "Self-hosted Web Application" architecture emerged. It compiles the back-end logic into an unreadable executable file and has built-in HTTP service capabilities, allowing the front-end to still interact with HTML/JS, while the back-end can implement encryption, security, authorization control and other requirements.
| name | Use language | Whether to support License management | Does it support C#? | Can generate Binary | fit for purpose | Usage rate/market share |
|---|---|---|---|---|---|---|
| Electron | JavaScript + Node.js | Can be used with verification system | no | Yes (desktop app) | Cross-Platform Desktop Web App | very high |
| Node.js + pkg | JavaScript | Can be used with JWT / Key verification | no | yes | Encapsulating Web API applications | high |
| ASP.NET Core + Kestrel | C# | Native support | yes | Yes (.exe/.dll) | Enterprise Web API/Tools | high |
| Go HTTP Server | Go | Built-in or custom | no | yes | High performance web backend | high |
| Blazor WebAssembly + ASP.NET | C# | Support authorization verification | yes | yes | SPA + Web API integration | Medium to high |
| Gradio | Python | Can be used with third parties | no | Can (PyInstaller) | ML/AI Web UI | middle |
| Streamlit | Python | Can be used with third parties | no | Can (PyInstaller) | Data visualization Web UI | middle |
| Tauri | Rust + JS | Support custom verification | no | yes | Ultra lightweight desktop app | middle |
| Mongoose / Civetweb | C / C++ | Embedded validation logic | Yes (with CLI) | yes | Embedded Web Server | middle |
ASP.NET Core is a cross-platform, open source, high-performance web application framework developed by Microsoft and supports Windows, Linux and macOS. It is part of the .NET platform and is designed for modern Web APIs, Web Apps, and Microservices. Compared with traditional ASP.NET, the Core version is more lightweight, modular, and can be compiled into an independent executable file (.exe), which is very suitable for self-encapsulated web application architecture.
dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true
This command can compile the ASP.NET Core application into a stand-alone executable file (such as `MyApp.exe`), which can be executed directly on the target system without installing .NET Runtime.
ASP.NET Core can be used as the backend of .NET MAUI + Blazor to provide data and API.
If you already have a Blazor Web project, you can move it to a MAUI app almost painlessly and reuse a lot of code.
ASP.NET Core focuses on backend and web architecture, and is suitable for developing cloud and API.
.NET MAUI + Blazor focuses on user-side cross-platform applications and is especially suitable for teams that already have Blazor front-end technology stack.
When the two are combined, a complete solution of "back-end service + front-end cross-platform app" can be achieved.
| IDE | Support platform | feature | Is it free? | Suitable for objects |
|---|---|---|---|---|
| Visual Studio | Windows | Full functionality, best official support | Community free (other fees apply) | Enterprise and full-end developers |
| Visual Studio Code | Windows / Linux / macOS | Lightweight and highly scalable | free | Cross-platform developers, students |
| JetBrains Rider | Windows / Linux / macOS | ReSharper integration, cross-platform | Fee required | Advanced Developers and Cross-Platform Teams |
Ctrl + `)。dotnet new webapp -o MyAspNetApp
webapp: Build ASP.NET Core web applications with Razor Pages.-o MyAspNetApp:Specify the name of the project folder.cd MyAspNetApp
dotnet run
https://localhost:5001orhttp://localhost:5000implement.File → Open folder, load the newly createdMyAspNetApp。dotnet add package package name
dotnet new webapp → Razor Pages Web Appdotnet new mvc→ MVC architecturedotnet new webapi→ Web API ProjectCtrl + Shift + P, enter and selectDebug: Open launch.json。.vscode/launch.json。{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/net8.0/MyAspNetApp.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
}
]
}
.vscodeFolder generationtasks.json。{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/MyAspNetApp.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
F5Or select from the "Execution and Debug" panel on the left.NET Core Launch (web)。https://localhost:5001。dotnet new webapi -o MyWebApiApp
cd MyWebApiApp
code .
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web API)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/net8.0/MyWebApiApp.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
}
]
}
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/MyWebApiApp.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
F5Or select from the Execution and Debug panel.NET Core Launch (web API)。https://localhost:5001orhttp://localhost:5000。.httpor.restArchive testing API.### Test GET API
GET https://localhost:5001/weatherforecast
Accept: application/json
###
### Test POST API example
POST https://localhost:5001/api/sample
Content-Type: application/json
{
"id": 1,
"name": "Test data"
}
test.http。Send Requestbutton.Kestrel isASP.NET CoreA built-in cross-platform web server developed by Microsoft. It is designed with high performance and lightweight, supports HTTP/1.1 and HTTP/2, and is the default server for ASP.NET Core applications. Using Kestrel allows developers to directly wrap web applications asself-packaging executable file, you can start and provide HTTP services locally without relying on external servers such as IIS, Apache or Nginx.
UseUrlsSet the local port and path of the servicepublic class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseKestrel()
.UseUrls("http://localhost:5000");
var app = builder.Build();
app.MapGet("/", () => "Hello from Kestrel!");
app.Run();
}
}
dotnet publishPackage the application with Kestrel into a single executable| project | Kestrel | IIS / Nginx |
|---|---|---|
| Whether built-in | Yes (built-in to ASP.NET Core) | No (needs to be installed separately) |
| Support platform | Windows / Linux / macOS | Varies by server |
| Do you need administrator rights? | no | Depends on platform and settings |
| Is it suitable for self-encapsulation? | very suitable | Not suitable |
| Performance | high | High (but the setting is more complicated) |
ASP.NET Core supports integrating front-end resources (HTML, CSS, JavaScript, SPA, etc.) and back-end API services into a single application and deploying it as an independent execution unit (Self-contained application) to achieve the goals of simple deployment, source code protection and license control.
wwwroot/A folder for ASP.NET Core to serve as static resources.wwwroot/。wwwroot,For example:npm run buildlaterdist/Copy intowwwroot/npm run buildlaterbuild/Copy intowwwroot/Program.csStatic file service is enabled in:app.UseStaticFiles();
app.MapFallbackToFile("index.html");
dotnet publish -c Release -r win-x64 --self-contained
ASP.NET Core MVC is a cross-platform web application framework launched by Microsoft. It is based on the Model-View-Controller (model-view-controller) design pattern and provides a structured and modular way to develop dynamic websites and Web APIs.
// Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
//Controller
public class ProductsController : Controller
{
public IActionResult Index()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "laptop", Price = 29999 },
new Product { Id = 2, Name = "Mouse", Price = 499 },
new Product { Id = 3, Name = "Keyboard", Price = 899 }
};
return View(products);
}
}
// View (Index.cshtml)
@model List<Product>
<table border="1" cellpadding="6" cellspacing="0">
<thead>
<tr>
<th>Number</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach(var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Price.ToString("C")</td>
</tr>
}
</tbody>
</table>
<!-- Product.cs - Data Model -->
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
<!-- ProductsController.cs - Controller (ASP.NET Core MVC) -->
public class ProductsController : Controller
{
public IActionResult Index()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "laptop", Price = 29999 },
new Product { Id = 2, Name = "Mouse", Price = 499 },
new Product { Id = 3, Name = "Keyboard", Price = 899 }
};
return View(products);
}
}
<!-- Views/Products/Index.cshtml - Razor View page -->
@model List<Product>
<table border="1" cellpadding="6" cellspacing="0">
<thead>
<tr>
<th>Number</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Price.ToString("C")</td>
</tr>
}
</tbody>
</table>
Razor is a markup language developed by Microsoft for ASP.NET Core that allows developers to embed C# code in HTML pages. It combines standard HTML and C# to make dynamically generating web pages simple and intuitive.
@page
@model IndexModel
<h1>Welcome to the Razor page</h1>
<p>Today’s date: @DateTime.Now.ToString("yyyy-MM-dd")</p>
@if(Model.Items != null && Model.Items.Any())
{
<ul>
@foreach(var item in Model.Items)
{
<li>@item</li>
}
</ul>
}
else
{
<p>No data displayed</p>
}
Use in Razor View:
@foreach(var item in Model)
{
<div>@item</div>
}
If the following error occurs:
System.NullReferenceException: Object reference not set to an instance of an object.
expressModelfornull, resulting in the inability to loop.
public IActionResult Index()
{
var data = new List<string> { "A", "B", "C" };
return View(data);
}
@model IEnumerable<string>
@if (Model != null)
{
foreach (var item in Model)
{
<div>@item</div>
}
}
else
{
<div>No data</div>
}
Best practice isMake sure the Model must have a value in the controller(even an empty collection) to avoid View handling null situations. For example:
return View(data ?? new List<string>());
In ASP.NET Core MVC, a project can have multiple Controllers, each Controller is responsible for different functions or areas. For example:
HomeController— Processing homepage and static pagesProductController— Handle product managementEvery Controller must inheritControllercategory and stored inControllersfolder.
// HomeController.cs
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
// ProductController.cs
public class ProductController : Controller
{
public IActionResult List()
{
var products = new List<string> { "Computer", "Mobile phone", "Tablet" };
return View(products);
}
}
MVC's View will create folders based on the Controller name by default, for example:
Views/Home/Index.cshtmlViews/Product/List.cshtmlCan be usedasp-controllerandasp-actionTag Helpers:
<a asp-controller="Home" asp-action="Index">Back to homepage</a>
<a asp-controller="Product" asp-action="List">Product List</a>
existProgram.csorStartup.cs, the default route is usually:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
This means that if the URL is/, will automatically guideHomeController.Index().
If the URL is/Product/List, it will be executedProductController.List()。
You can have multiple Controllers at the same time in MVC as long as:
ControllerViewsCreate corresponding folders and files inasp-controllerandasp-actionCorrect callModel(or a composite ViewModel), but can display or link to data/Actions from multiple Controllers on the same page.// Models/ViewModels.cs
public class HomePageViewModel {
public IEnumerable<Product> Products { get; set; }
public IEnumerable<Order> RecentOrders { get; set; }
}
// HomeController.cs
public IActionResult Index() {
var vm = new HomePageViewModel {
Products = productService.GetTopProducts(),
RecentOrders = orderService.GetRecentOrders()
};
return View(vm);
}
// Views/Home/Index.cshtml
@model HomePageViewModel
<h2>Product</h2>
@foreach(var p in Model.Products){ <div>@p.Name</div> }
<h2>Recent Orders</h2>
@foreach(var o in Model.RecentOrders){ <div>@o.Id</div> }
// Views/Product/_ProductList.cshtml (partial)
@model IEnumerable<Product>
@foreach(var p in Model){ <div>@p.Name</div> }
// Views/Home/Index.cshtml (parent View)
@model HomePageViewModel
<div>
@Html.Partial("_ProductList", Model.Products)
</div>
// Components/ProductListViewComponent.cs
public class ProductListViewComponent : ViewComponent {
private readonly IProductService _svc;
public ProductListViewComponent(IProductService svc){ _svc = svc; }
public IViewComponentResult Invoke(int count) {
var products = _svc.GetTopProducts(count);
return View(products); // Views/Shared/Components/ProductList/Default.cshtml
}
}
// used in Razor
@await Component.InvokeAsync("ProductList", new { count = 5 })
<!-- Views/Home/Index.cshtml -->
<div id="product-area">Loading...</div>
<script>
fetch('/api/product/top5')
.then(r => r.json())
.then(data => {
document.getElementById('product-area').innerHTML =
data.map(p => `${p.name}`).join('');
});
</script>
<a asp-controller="Product" asp-action="List">Product List</a>
<a asp-controller="Order" asp-action="History">Order History</a>
ViewModelorViewComponent(more modular).Partial VieworViewComponent。A Java Applet is a small application written in the Java language that can be executed through a web browser and embedded into an HTML page. It was first widely used in the 1990s to create interactive web pages, such as animations, games, and chart visualizations.
Applet must be executed on a browser that supports Java Plugin, through<applet>or<object>Tags are embedded in HTML and are loaded and executed by the user-side JVM (Java Virtual Machine).
Since Applets can be executed on the client side, in order to prevent malicious behavior, the execution environment adopts a "sandbox mechanism" for security isolation, such as prohibiting access to the local file system or execution of external programs.
Oracle has announced the removal of Applet API since Java 9, and will completely abolish Applet in Java 11. Java Web Start, another desktop execution technology, is also out of maintenance.
Java Applets have entered the phase of elimination, and modern web development trends tend to use open standard technologies such as HTML5, JavaScript and WebAssembly. Developers should avoid using applets and move existing applications to modern technology platforms.
The following is an example Java Applet that displays a simple message:
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>Java Applet Example</title>
</head>
<body>
<h1>Java Applet Example</h1>
<applet code="HelloWorldApplet.class" width="300" height="300>
<param name="message" value="Hello, world! ">
Your browser does not support Java Applets.
</applet>
</body>
</html>
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet {
String message;
public void init() {
message = getParameter("message");
}
public void paint(Graphics g) {
g.drawString(message, 20, 20);
}
}
1. Save the Java code asHelloWorldApplet.java, and execute it in the command linejavac HelloWorldApplet.javato compile.
2. Make sure the generated.classThe file is in the same directory as the HTML file.
3. Use an environment that supports Java Applets to execute the HTML file.
Since most modern browsers no longer support Java Applets, it is recommended to consider using other technologies (such as JavaFX or web applications) to achieve similar functionality.
email: [email protected]