-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreload.php
More file actions
163 lines (145 loc) · 4.66 KB
/
Copy pathpreload.php
File metadata and controls
163 lines (145 loc) · 4.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<?php
/**
* OPcache Preload Script for WordPress
*
* Este arquivo é usado pelo opcache.preload para pré-carregar
* classes e funções do WordPress na memória compartilhada.
*
* Benefícios:
* - Reduz tempo de execução ao eliminar compilação repetida
* - Melhora performance em sites de alto tráfego
* - Classes ficam sempre em memória compartilhada
*
* IMPORTANTE:
* - Este arquivo é executado UMA VEZ quando o PHP-FPM inicia
* - Alterações requerem reinício do PHP-FPM
* - Use apenas em produção com opcache.validate_timestamps=0
*
* Configuração necessária no php.ini:
* opcache.preload=/var/www/DOMAIN/preload.php
* opcache.preload_user=www-data
*/
// Define o caminho base do WordPress
define('PRELOAD_BASE_PATH', __DIR__);
// Habilita error reporting para debug durante desenvolvimento
// Descomente para ver erros durante testes
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
/**
* Lista de arquivos core do WordPress para pré-carregar
* Adicione aqui os arquivos mais usados do seu site
*/
$preload_files = [
// Core WordPress files
'/wp-load.php',
'/wp-includes/version.php',
'/wp-includes/compat.php',
'/wp-includes/functions.php',
'/wp-includes/class-wp.php',
'/wp-includes/class-wp-error.php',
'/wp-includes/plugin.php',
'/wp-includes/pomo/mo.php',
'/wp-includes/l10n.php',
'/wp-includes/formatting.php',
'/wp-includes/meta.php',
'/wp-includes/post.php',
'/wp-includes/user.php',
'/wp-includes/link-template.php',
'/wp-includes/general-template.php',
'/wp-includes/class-wp-query.php',
'/wp-includes/query.php',
'/wp-includes/theme.php',
'/wp-includes/class-wp-theme.php',
'/wp-includes/class-wp-widget.php',
'/wp-includes/class-wp-widget-factory.php',
'/wp-includes/widgets.php',
// WordPress Database
'/wp-includes/wp-db.php',
'/wp-includes/class-wpdb.php',
// WordPress Options
'/wp-includes/option.php',
// WordPress Caching
'/wp-includes/cache.php',
'/wp-includes/class-wp-object-cache.php',
// Adicione aqui plugins críticos que são sempre carregados
// Exemplo:
// '/wp-content/plugins/seu-plugin/seu-plugin.php',
// Adicione aqui classes do seu tema (se aplicável)
// Exemplo:
// '/wp-content/themes/seu-tema/functions.php',
];
/**
* Função para pré-carregar arquivo com tratamento de erros
*/
function preload_file($file) {
$full_path = PRELOAD_BASE_PATH . $file;
if (!file_exists($full_path)) {
// Log para syslog em caso de arquivo não encontrado
error_log("OPcache Preload: Arquivo não encontrado: {$full_path}");
return false;
}
try {
// Tenta incluir o arquivo
opcache_compile_file($full_path);
return true;
} catch (Throwable $e) {
// Log de erro caso haja problema ao compilar
error_log("OPcache Preload: Erro ao compilar {$full_path}: " . $e->getMessage());
return false;
}
}
/**
* Pré-carrega todos os arquivos da lista
*/
$loaded = 0;
$failed = 0;
foreach ($preload_files as $file) {
if (preload_file($file)) {
$loaded++;
} else {
$failed++;
}
}
// Log de estatísticas para syslog
error_log(sprintf(
"OPcache Preload: Concluído - %d arquivos carregados, %d falharam",
$loaded,
$failed
));
/**
* AVANÇADO: Pré-carrega classes automaticamente via reflection
*
* Descomente o bloco abaixo se quiser pré-carregar todas as classes
* de um namespace específico ou diretório
*/
/*
// Exemplo: Pré-carregar todas as classes de um plugin
$plugin_dir = PRELOAD_BASE_PATH . '/wp-content/plugins/woocommerce/includes';
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($plugin_dir),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
try {
opcache_compile_file($file->getPathname());
} catch (Throwable $e) {
error_log("OPcache Preload: Erro ao compilar {$file->getPathname()}: " . $e->getMessage());
}
}
}
*/
/**
* DICAS:
*
* 1. Comece com poucos arquivos e adicione gradualmente
* 2. Monitore o uso de memória com opcache_get_status()
* 3. Arquivos pré-carregados NÃO podem ser modificados sem reiniciar PHP-FPM
* 4. Use apenas para arquivos que raramente mudam (core, plugins estáveis)
* 5. NÃO pré-carregue wp-config.php ou arquivos com side-effects
*
* Para testar:
* 1. sudo systemctl restart php8.x-fpm
* 2. Verifique logs: tail -f /var/log/syslog | grep "OPcache Preload"
* 3. Verifique status: curl https://seusite.com/SECURE_DIR/opcache.php
*/