PHP是一种广泛应用于Web开发的服务器端脚本语言,以其简洁的语法和强大的数据库交互能力而著称。以下是一些精选的PHP实战代码示例,旨在帮助初学者和进阶者快速提升PHP编程技能。1. 变量和数据类型p...
PHP是一种广泛应用于Web开发的服务器端脚本语言,以其简洁的语法和强大的数据库交互能力而著称。以下是一些精选的PHP实战代码示例,旨在帮助初学者和进阶者快速提升PHP编程技能。
<?php
$age = 25;
$name = "Alice";
$height = 5.7; // 英尺
echo "My name is $name and I am $age years old.";
?><?php
$x = 10;
$y = 20;
if ($x < $y) { echo "x is less than y";
} else { echo "x is greater than or equal to y";
}
?><?php
for ($i = 0; $i < 5; $i++) { echo "Number $i <br>";
}
?><?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) { echo $color . "<br>";
}
?><?php
function greet($name) { echo "Hello, $name!";
}
greet("Alice");
?><?php
$string = "Hello, world!";
echo strlen($string) . " characters long.<br>";
echo substr($string, 7) . "<br>";
?><?php
$file = fopen("example.txt", "r");
while (!feof($file)) { echo fgets($file) . "<br>";
}
fclose($file);
?><?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) { echo "New record created successfully";
} else { echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?><?php
session_start();
$_SESSION["username"] = "Alice";
echo "Hello, " . $_SESSION["username"];
?><?php
try { // Some code that may throw an exception throw new Exception("This is an error message.");
} catch (Exception $e) { echo 'Message: ' . $e->getMessage();
}
?><?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); if (empty($name)) { echo "Name is required"; } else { echo "Hello, " . $name; }
}
function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data;
}
?><?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = test_input($_POST["email"]); $message = test_input($_POST["message"]); echo "Email: " . $email . "<br>"; echo "Message: " . $message;
}
?><?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) { $filename = $_FILES["file"]["name"]; $filetmpname = $_FILES["file"]["tmp_name"]; $filetype = $_FILES["file"]["type"]; $fileerror = $_FILES["file"]["error"]; $fileext = strtolower(end(explode(".", $filename))); $allowedexts = array("jpg", "jpeg", "png", "gif"); if (in_array($fileext, $allowedexts) && $fileerror === 0) { $filenameNew = uniqid("", true) . "." . $fileext; move_uploaded_file($filetmpname, "uploads/" . $filenameNew); echo "The file " . htmlspecialchars($filename) . " has been uploaded."; } else { echo "Invalid file type or error uploading file."; }
}
?><?php
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";
mail($to, $subject, $message, $headers);
?><?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { $data = $_POST["data"]; echo "Received data: " . $data;
}
?><?php
$json = '{"name":"Alice", "age":25}';
$data = json_decode($json, true);
echo "Name: " . $data["name"] . "<br>";
echo "Age: " . $data["age"];
?><?php
require_once('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(40, 10, 'Hello World!');
$pdf->Output();
?><?php
$image = imagecreatefromjpeg("example.jpg");
imagejpeg($image, "output.jpg");
imagedestroy($image);
?><?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; }
} else { echo "0 results";
}
$conn->close();
?><?php
$host = 'localhost';
$db = 'myDB';
$user = 'username';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false,
];
try { $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) { throw new PDOException($e->getMessage(), (int)$e->getCode());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$stmt = $pdo->query($sql);
while ($row = $stmt->fetch()) { echo $row['id'] . " " . $row['firstname'] . " " . $row['lastname'] . "<br>";
}
?><?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
$mail = new PHPMailer(true);
try { $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'username@example.com'; $mail->Password = 'password'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; $mail->setFrom('from@example.com', 'Mailer'); $mail->addAddress('recipient@example.com', 'Recipient Name'); $mail->isHTML(true); $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; $mail->send(); echo 'Message has been sent';
} catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?><?php
require 'path/to/Stripe/autoload.php';
StripeStripe::setApiKey('your_secret_key');
$token = $_POST['stripeToken'];
try { $charge = StripeCharge::create([ 'amount' => 1000, 'currency' => 'usd', 'description' => 'Example charge', 'source' => $token, ]); echo 'Charge ID: ' . $charge->id;
} catch (StripeErrorCard $e) { echo 'Card error: ' . $e->getMessage();
} catch (StripeErrorRateLimit $e) { echo 'Rate limit error: ' . $e->getMessage();
} catch (StripeErrorInvalidRequest $e) { echo 'Invalid request error: ' . $e->getMessage();
} catch (StripeErrorAuthentication $e) { echo 'Authentication error: ' . $e->getMessage();
} catch (StripeErrorApiConnection $e) { echo 'API connection error: ' . $e->getMessage();
} catch (StripeErrorBase $e) { echo 'Base error: ' . $e->getMessage();
}
?><?php
session_start();
if (isset($_POST['submit'])) { $_SESSION['username'] = $_POST['username'];
}
if (isset($_SESSION['username'])) { echo 'Hello, ' . $_SESSION['username'];
} else { echo '<form method="post">'; echo 'Username: <input type="text" name="username">'; echo '<input type="submit" name="submit" value="Submit">'; echo '</form>';
}
?><?php
$xml = simplexml_load_file("example.xml");
foreach ($xml->children() as $child) { echo $child->name . " " . $child->value . "<br>";
}
?><?php
$data = array( array("name", "age", "email"), array("Alice", 25, "alice@example.com"), array("Bob", 30, "bob@example.com"),
);
$fp = fopen("example.csv", "w");
foreach ($data as $fields) { fputcsv($fp, $fields);
}
fclose($fp);
?><?php
$json = '{"name":"Alice", "age":25}';
$data = json_decode($json);
echo "Name: " . $data->name . "<br>";
echo "Age: " . $data->age;
?><?php
$yaml = <<<EOT
name: Alice
age: 25
children: - name: Bob age: 5
EOT;
$data = yaml_parse($yaml);
echo $data['name'] . " " . $data['age'] . "<br>";
foreach ($data['children'] as $child) { echo $child['name'] . " " . $child['age'] . "<br>";
}
?>”`php <?php require ‘path/to/PHPExcel.php’;
(objPHPExcel = new PHPExcel(); )objPHPExcel->getProperties()->setCreator(“Alice”); $objPHPExcel->getProperties()->setTitle(“Office 2007 XLSX Test Document”);
(objPHPExcel->setActiveSheetIndex(0); )sheet = (objPHPExcel->getActiveSheet(); )sheet->setCellValue(‘A1’, ‘Hello World !’); $sheet->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘test’);
(objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World !'); )objPHPExcel->getActiveSheet()->setCellValue(‘B2’,