热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
本提示词专为PHP开发者设计,提供专业级的表单数据处理解决方案。通过精确的方法选择、数据类型定义和安全验证机制,能够生成高质量、安全的PHP代码。支持多种应用场景,包括用户注册、数据查询、文件上传等,确保代码的准确性和安全性,同时提供清晰的技术文档和最佳实践建议,帮助开发者快速实现功能并避免常见安全漏洞。
<?php
declare(strict_types=1);
/**
* POST: 接收并严格验证字符串参数 `prompt`
* 要求:
* - 仅允许 POST 方法
* - 参数必须是字符串且非空(去除首尾空白后)
* - UTF-8 合法编码
* - 禁止包含控制字符(允许 \n \r \t)
* - 长度限制(字符数 1..2000,字节数 <= 8192)
*
* 返回:
* - JSON 响应(success/error),并附带验证后的安全数据或错误信息
*
* 注意:
* - 本示例只做数据层面的验证与规范化,不对数据库/HTML/命令行等上下文做具体转义。
* - 如需在 HTML 中输出,请使用 htmlspecialchars 进行上下文转义(见下方示例)。
*/
// 配置区(可按需调整)
const PROMPT_MIN_LENGTH_CHARS = 1;
const PROMPT_MAX_LENGTH_CHARS = 2000;
const PROMPT_MAX_LENGTH_BYTES = 8192;
const RESPONSE_CHARSET = 'UTF-8';
// 推荐的 HTTP 安全响应头
header('Content-Type: application/json; charset=' . RESPONSE_CHARSET);
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: no-referrer');
header('Cache-Control: no-store');
// 将 PHP 错误转为异常,便于统一处理(可选)
set_error_handler(static function (int $severity, string $message, string $file, int $line): void {
if (!(error_reporting() & $severity)) {
return;
}
throw new ErrorException($message, 0, $severity, $file, $line);
});
try {
enforceRequestMethod('POST');
// 确保参数存在且不是数组(防止多值注入)
if (!array_key_exists('prompt', $_POST)) {
throw new HttpException(400, 'Missing required parameter: prompt');
}
$raw = $_POST['prompt'];
if (!is_string($raw)) {
// 例如 prompt[]=a 这种会成为数组
throw new HttpException(400, 'Invalid type for "prompt": expected string');
}
// 规范化与严格校验
$prompt = validateAndNormalizePrompt($raw);
// 成功响应(示例中返回已验证/规范化后的值与长度信息)
jsonResponse(200, [
'success' => true,
'data' => [
'prompt' => $prompt,
'length' => [
'chars' => mb_strlen($prompt, RESPONSE_CHARSET),
'bytes' => strlen($prompt),
],
],
]);
} catch (HttpException $e) {
jsonResponse($e->getCode(), [
'success' => false,
'error' => [
'code' => $e->getCode(),
'message' => $e->getMessage(),
],
]);
} catch (Throwable $e) {
// 未预期错误:避免暴露具体堆栈信息
jsonResponse(500, [
'success' => false,
'error' => [
'code' => 500,
'message' => 'Internal Server Error',
],
]);
}
/**
* 仅允许指定的请求方法
*/
function enforceRequestMethod(string $expectedMethod): void
{
$method = $_SERVER['REQUEST_METHOD'] ?? '';
if (strcasecmp($method, $expectedMethod) !== 0) {
// 明确告知允许的方法
header('Allow: ' . strtoupper($expectedMethod));
throw new HttpException(405, 'Method Not Allowed');
}
}
/**
* 验证并规范化 prompt 字段
*/
function validateAndNormalizePrompt(string $value): string
{
// 去除 UTF-8 BOM
$value = stripUtf8Bom($value);
// 初步修剪空白(不移除内部空白)
$value = trim($value);
// 空值校验
if ($value === '') {
throw new HttpException(422, 'Prompt must not be empty');
}
// UTF-8 编码合法性校验
if (!mb_check_encoding($value, RESPONSE_CHARSET)) {
throw new HttpException(422, 'Prompt must be valid UTF-8 text');
}
// 可选:进行 Unicode 规范化(NFC),依赖 intl 扩展
if (function_exists('normalizer_is_normalized') && function_exists('normalizer_normalize')) {
if (!normalizer_is_normalized($value, Normalizer::FORM_C)) {
$value = normalizer_normalize($value, Normalizer::FORM_C) ?: $value;
}
}
// 拒绝控制字符(允许 \n \r \t)
if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', $value) === 1) {
throw new HttpException(422, 'Prompt contains disallowed control characters');
}
// 长度限制(字符数)
$lenChars = mb_strlen($value, RESPONSE_CHARSET);
if ($lenChars < PROMPT_MIN_LENGTH_CHARS) {
throw new HttpException(422, 'Prompt is too short');
}
if ($lenChars > PROMPT_MAX_LENGTH_CHARS) {
throw new HttpException(422, 'Prompt is too long');
}
// 长度限制(字节数,防滥用/DoS)
$lenBytes = strlen($value);
if ($lenBytes > PROMPT_MAX_LENGTH_BYTES) {
throw new HttpException(413, 'Prompt exceeds allowed byte size');
}
// 可选的额外约束(示例:禁止 NUL 字节)
if (strpos($value, "\0") !== false) {
throw new HttpException(422, 'Prompt contains null bytes');
}
// 如需进一步限制字符集,可启用如下白名单示例(根据业务调整)
// if (preg_match('/^[\p{L}\p{N}\p{P}\p{Zs}\r\n\t]+$/u', $value) !== 1) {
// throw new HttpException(422, 'Prompt contains unsupported characters');
// }
return $value;
}
/**
* 去除 UTF-8 BOM
*/
function stripUtf8Bom(string $s): string
{
if (strncmp($s, "\xEF\xBB\xBF", 3) === 0) {
return substr($s, 3);
}
return $s;
}
/**
* 统一 JSON 响应
*/
function jsonResponse(int $statusCode, array $payload): void
{
http_response_code($statusCode);
$json = json_encode(
$payload,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
// 理论上不会失败;如失败,返回兜底的 JSON
if ($json === false) {
$fallback = json_encode(
['success' => false, 'error' => ['code' => 500, 'message' => 'Encoding Error']],
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
) ?: '{"success":false,"error":{"code":500,"message":"Encoding Error"}}';
echo $fallback;
return;
}
echo $json;
}
/**
* 用于可控的 HTTP 异常
*/
final class HttpException extends RuntimeException
{
}
curl 调用
表单方式
curl -X POST https://example.com/endpoint.php
-H "Content-Type: application/x-www-form-urlencoded"
--data-urlencode "prompt=这是一个测试\n第二行"
multipart 方式
curl -X POST https://example.com/endpoint.php
-F "prompt=Hello, world!"
HTML 表单示例(提交到同一 PHP 脚本)
在 HTML 中安全输出(例如服务端渲染页面)
' . $safeHtml . '';数据库写入(PDO 参数化示例)
prepare('INSERT INTO prompts (content) VALUES (:content)'); $stmt->bindParam(':content', $validatedPrompt, PDO::PARAM_STR); $stmt->execute();<?php
declare(strict_types=1);
/**
* 安全获取并验证 GET 数组参数:keywords
* 要求:
* - 请求方法:GET
* - 参数名称:keywords
* - 数据类型:数组(例如:?keywords[]=foo&keywords[]=bar)
* - 验证要求:基础验证(数量、长度、字符集)
*
* 返回:JSON
* - 成功:{ success: true, data: { keywords: [ ... ] }, meta: { count: n } }
* - 失败:{ success: false, errors: [ ... ] }
*
* 注意:本示例仅处理参数获取与验证,不包含业务查询逻辑。
*/
header('Content-Type: application/json; charset=utf-8');
const MAX_KEYWORDS = 10; // 最多关键词数量
const MAX_KEYWORD_LEN = 64; // 单个关键词最大长度(按字符计)
const ALLOWED_PATTERN = '/^[\p{L}\p{N}\s\-_]+$/u'; // 允许:字母、数字、空格、连字符、下划线(支持多语言)
/**
* 统一 JSON 响应
*/
function respond(array $body, int $status = 200, array $headers = []): void
{
http_response_code($status);
foreach ($headers as $name => $value) {
header($name . ': ' . $value, true);
}
echo json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
/**
* 异常:参数校验失败
*/
final class ValidationException extends RuntimeException
{
/** @var array<int|string, mixed> */
private array $errors;
/**
* @param array<int|string, mixed> $errors
*/
public function __construct(array $errors, string $message = 'Validation failed', int $code = 422)
{
parent::__construct($message, $code);
$this->errors = $errors;
}
/**
* @return array<int|string, mixed>
*/
public function getErrors(): array
{
return $this->errors;
}
}
/**
* 多字节长度安全函数
*/
function mb_len(string $str): int
{
return function_exists('mb_strlen') ? mb_strlen($str, 'UTF-8') : strlen($str);
}
/**
* 关键词规范化:
* - 去首尾空白
* - 合并连续空白为单个空格
*/
function normalize_keyword(string $keyword): string
{
$keyword = trim($keyword);
// 合并任意空白字符为一个空格(支持多字节)
$keyword = preg_replace('/\s+/u', ' ', $keyword) ?? $keyword;
return $keyword;
}
/**
* 对 keywords 参数进行获取、验证与过滤
*
* @return array<int, string> 通过校验的关键词列表
* @throws ValidationException
*/
function get_and_validate_keywords(): array
{
$errors = [];
// 仅允许 GET
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') {
respond(
[
'success' => false,
'errors' => [
[
'field' => 'method',
'message' => 'Only GET method is allowed.',
'code' => 'method_not_allowed',
],
],
],
405,
['Allow' => 'GET']
);
}
// 判断参数是否存在及是否为数组
$hasParam = array_key_exists('keywords', $_GET);
if (!$hasParam) {
$errors[] = [
'field' => 'keywords',
'message' => 'Parameter "keywords" is required and must be an array (e.g., ?keywords[]=foo&keywords[]=bar).',
'code' => 'required',
];
throw new ValidationException($errors);
}
if (!is_array($_GET['keywords'])) {
$errors[] = [
'field' => 'keywords',
'message' => 'Parameter "keywords" must be an array. Use repeated keys like keywords[]=value.',
'code' => 'type_array_required',
];
throw new ValidationException($errors);
}
// 使用 filter_input 获取并初步过滤为数组
$rawKeywords = filter_input(INPUT_GET, 'keywords', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
// 防御性判断(极端情况下 $rawKeywords 可能为 null)
if (!is_array($rawKeywords)) {
$errors[] = [
'field' => 'keywords',
'message' => 'Failed to read "keywords" as array.',
'code' => 'read_failure',
];
throw new ValidationException($errors);
}
// 数量限制
if (count($rawKeywords) > MAX_KEYWORDS) {
$errors[] = [
'field' => 'keywords',
'message' => 'Too many keywords. At most ' . MAX_KEYWORDS . ' items are allowed.',
'code' => 'too_many_items',
];
throw new ValidationException($errors);
}
$valid = [];
foreach ($rawKeywords as $index => $value) {
// 禁止嵌套数组
if (is_array($value)) {
$errors[] = [
'field' => "keywords[$index]",
'message' => 'Nested arrays are not allowed. Each keyword must be a scalar string.',
'code' => 'nested_array_not_allowed',
];
continue;
}
// PHP 在 GET 中通常只会得到字符串,这里仍做防御性检查
if (!is_string($value)) {
$errors[] = [
'field' => "keywords[$index]",
'message' => 'Keyword must be a string.',
'code' => 'type_string_required',
];
continue;
}
$value = normalize_keyword($value);
// 空字符串直接跳过(不计入错误,允许用户提交空项但最终至少要有一个有效关键字)
if ($value === '') {
continue;
}
// 长度校验
if (mb_len($value) > MAX_KEYWORD_LEN) {
$errors[] = [
'field' => "keywords[$index]",
'message' => 'Keyword length must be <= ' . MAX_KEYWORD_LEN . ' characters.',
'code' => 'too_long',
];
continue;
}
// 字符集校验(允许:字母、数字、空格、连字符、下划线;多语言支持)
if (!preg_match(ALLOWED_PATTERN, $value)) {
$errors[] = [
'field' => "keywords[$index]",
'message' => 'Keyword contains invalid characters. Only letters, numbers, spaces, hyphen, underscore are allowed.',
'code' => 'invalid_charset',
];
continue;
}
$valid[] = $value;
}
// 去重(保持第一次出现的顺序)
$valid = array_values(array_unique($valid, SORT_STRING));
// 至少需要一个有效关键词
if (count($valid) === 0) {
$errors[] = [
'field' => 'keywords',
'message' => 'At least one non-empty, valid keyword is required.',
'code' => 'no_valid_keyword',
];
}
if (!empty($errors)) {
throw new ValidationException($errors);
}
return $valid;
}
// 执行
try {
$keywords = get_and_validate_keywords();
respond([
'success' => true,
'data' => [
'keywords' => $keywords,
],
'meta' => [
'count' => count($keywords),
],
]);
} catch (ValidationException $e) {
respond([
'success' => false,
'errors' => $e->getErrors(),
], 422);
} catch (Throwable $e) {
// 生产环境请记录日志(勿输出敏感信息)
respond([
'success' => false,
'errors' => [
[
'message' => 'Internal server error.',
'code' => 'internal_error',
],
],
], 500);
}
// $keywords 已通过上述验证
$pdo = new PDO('mysql:host=localhost;dbname=app;charset=utf8mb4', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// 构造 (name LIKE ? OR name LIKE ? ...) 形式,使用绑定参数
$placeholders = [];
$params = [];
foreach ($keywords as $kw) {
$placeholders[] = 'name LIKE ?';
$params[] = '%' . $kw . '%';
}
$sql = 'SELECT id, name FROM products WHERE ' . implode(' OR ', $placeholders) . ' LIMIT 50';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
curl -G "http://localhost/search.php" \
--data-urlencode "keywords[]=iphone" \
--data-urlencode "keywords[]=13 Pro" \
--data-urlencode "keywords[]=保护壳"
const params = new URLSearchParams();
['iphone', '13 Pro', '保护壳'].forEach(v => params.append('keywords[]', v));
fetch('/search.php?' + params.toString(), { method: 'GET' })
.then(r => r.json())
.then(console.log)
.catch(console.error);
{
"success": true,
"data": { "keywords": ["iphone", "13 Pro", "保护壳"] },
"meta": { "count": 3 }
}
{
"success": false,
"errors": [
{
"field": "keywords",
"message": "Too many keywords. At most 10 items are allowed.",
"code": "too_many_items"
}
]
}
将业务中的表单需求(如注册登录、搜索筛选、文件上传、联系表单等)快速转化为安全、规范、可复用的PHP实现与配套说明;默认内置严谨的数据校验、输入清洗与错误处理,显著降低安全与线上故障风险;统一团队代码风格与说明格式,减少沟通和评审时间;让新人也能稳定产出资深水准的结果,加速从原型到上线的节奏,助力团队在试用期就看到可验证的成效并自然转化为付费。
用它在半小时内搭建安全的注册/登录表单;自动生成字段校验、过滤与提示;复制即用,快速建立正确编码习惯。
批量生成联系表单、搜索筛选、文件上传的处理逻辑;统一风格减少返工,压缩上线周期与维护成本。
快速适配不同站点的参数命名与请求方式;一键产出代码、说明与示例,支持多环境复用与版本迭代。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期