Repository navigation
Expand file tree
/
Copy pathphp2shell-mitigation.ps1
More file actions
752 lines (695 loc) · 41.9 KB
/
Copy pathphp2shell-mitigation.ps1
File metadata and controls
752 lines (695 loc) · 41.9 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
<#
.SYNOPSIS
php2shell-mitigation.ps1 - interim mitigation for the PHP "php2shell" vulnerabilities
(CVE-2026-109618 / CVE-2026-109619) on Windows: session.upload_progress.enabled = Off
.DESCRIPTION
* finds every PHP installation on the host: PATH, IIS FastCGI (applicationHost.config,
including per-application PHPRC / PHP_INI_SCAN_DIR), registry (HKLM\SOFTWARE\PHP),
Apache mod_php / mod_fcgid (PHPIniDir, LoadModule), running services and processes,
XAMPP / WAMP / Laragon / Plesk / Bitnami / UwAmp / OSPanel / Chocolatey locations,
on every fixed drive
* backs up every file before touching it (central backup dir + JSON manifest)
* uses a drop-in file when a PHP_INI_SCAN_DIR is configured, otherwise edits php.ini
in place inside marker lines, or creates a minimal php.ini when none exists
(PHP's built-in default for the directive is On, so "no php.ini" = vulnerable)
* preserves encoding (BOM or not) and line endings of the edited files
* recycles IIS application pools and restarts Apache services after a config test
* $CONFIG_REVERT = $true removes everything the script added and restores the lines
it commented out; the raw backups can be restored instead if preferred
Designed for unattended runs (CoreUpdate etc.): edit the SETTINGS block, run elevated,
no arguments needed. Switches override the SETTINGS block:
-Apply -Revert -DryRun -NoReload -RestoreBackup
Exit codes: 0 = done, 1 = fatal (not elevated), 2 = done with warnings
(a target still reports On, a restart failed, overrides found)
THIS IS A STOPGAP, NOT A FIX. It is reported to close only one of the two suspected
code paths. Patch PHP as soon as fixed builds are available.
.NOTES
Windows PowerShell 5.1 or PowerShell 7+. Run as Administrator / SYSTEM.
#>
[CmdletBinding()]
param(
[switch]$Apply,
[switch]$Revert,
[switch]$DryRun,
[switch]$NoReload,
[switch]$RestoreBackup
)
########################### SETTINGS - edit here ##############################
$CONFIG_REVERT = $false # $false = apply the mitigation, $true = remove it
$CONFIG_DRY_RUN = $false # $true = report only, change nothing
$CONFIG_RELOAD_SERVICES = $true # recycle IIS app pools / restart Apache after changes
$CONFIG_RESTORE_FROM_BACKUP = $false # revert: copy raw backups back instead of removing markers
$CONFIG_SCAN_OVERRIDES = $true # report .user.ini / .htaccess that mention the directive
$CONFIG_STATE_DIR = Join-Path $env:ProgramData 'php2shell-mitigation' # backups + manifest
$CONFIG_EXTRA_INI_FILES = @() # extra php.ini paths for exotic installs, e.g. @('D:\php\php.ini')
$CONFIG_EXTRA_SCAN_DIRS = @() # extra PHP_INI_SCAN_DIR folders, if you use that mechanism
$CONFIG_EXTRA_SEARCH_ROOTS = @() # extra folders searched (3 levels) for php.exe / php-cgi.exe / httpd.exe
###############################################################################
Set-StrictMode -Off
$ErrorActionPreference = 'Continue'
if ($Apply) { $CONFIG_REVERT = $false }
if ($Revert) { $CONFIG_REVERT = $true }
if ($DryRun) { $CONFIG_DRY_RUN = $true }
if ($NoReload) { $CONFIG_RELOAD_SERVICES = $false }
if ($RestoreBackup) { $CONFIG_RESTORE_FROM_BACKUP = $true }
$SCRIPT_NAME = 'php2shell-mitigation'
$DIRECTIVE = 'session.upload_progress.enabled'
$DIRECTIVE_RE = [regex]::Escape($DIRECTIVE)
$DROPIN_NAME = "zz-$SCRIPT_NAME.ini"
$MARK_BEGIN = "; >>> $SCRIPT_NAME BEGIN (CVE-2026-109618 / CVE-2026-109619) - managed by $SCRIPT_NAME, do not edit"
$MARK_END = "; <<< $SCRIPT_NAME END"
$MARK_BEGIN_RE = "$SCRIPT_NAME BEGIN"
$MARK_END_RE = "$SCRIPT_NAME END"
$DISABLED_PREFIX = ";$SCRIPT_NAME-disabled: "
$INI_LINE = "$DIRECTIVE = Off"
$CREATED_TAG = "created by $SCRIPT_NAME"
$RUN_TS = Get-Date -Format 'yyyyMMdd-HHmmss'
$MODE = if ($CONFIG_REVERT) { 'REVERT' } else { 'APPLY' }
$BACKUP_DIR = Join-Path (Join-Path $CONFIG_STATE_DIR 'backups') "$RUN_TS-$($MODE.ToLower())-$PID"
$MANIFEST = Join-Path $CONFIG_STATE_DIR 'applied.manifest.json'
$script:Warnings = 0
$script:Changes = 0
$script:ManifestEntries = New-Object System.Collections.Generic.List[object]
# ----------------------------------------------------------------------------
# logging (direct to stdout/stderr so function return values stay clean)
# ----------------------------------------------------------------------------
function Log ([string]$m) { [Console]::Out.WriteLine($m) }
function Info ([string]$m) { [Console]::Out.WriteLine("[INFO] $m") }
function Ok ([string]$m) { [Console]::Out.WriteLine("[OK] $m") }
function Dry ([string]$m) { [Console]::Out.WriteLine("[DRY] $m") }
function Warn ([string]$m) { [Console]::Error.WriteLine("[WARN] $m"); $script:Warnings++ }
function Die ([string]$m) { [Console]::Error.WriteLine("[FATAL] $m"); exit 1 }
# never let a child process (php.exe with a missing DLL...) pop a blocking dialog
try {
Add-Type -Namespace Php2Shell -Name Native -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetErrorMode(uint uMode);' -ErrorAction Stop
[void][Php2Shell.Native]::SetErrorMode(0x8007)
} catch { }
# ----------------------------------------------------------------------------
# generic helpers
# ----------------------------------------------------------------------------
function Invoke-Proc {
param([string]$FilePath, [string[]]$Arguments = @(), [int]$TimeoutSec = 25, [hashtable]$Env = $null, [string]$WorkingDirectory = $null)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $FilePath
$quoted = foreach ($a in $Arguments) { if ($a -match '[\s"]') { '"' + ($a -replace '"', '\"') + '"' } else { $a } }
$psi.Arguments = ($quoted -join ' ')
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
if ($WorkingDirectory) { $psi.WorkingDirectory = $WorkingDirectory }
if ($Env) { foreach ($k in $Env.Keys) { $psi.EnvironmentVariables[$k] = [string]$Env[$k] } }
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
try { [void]$p.Start() } catch { return [pscustomobject]@{ ExitCode = -1; StdOut = ''; StdErr = $_.Exception.Message; TimedOut = $false } }
$outTask = $p.StandardOutput.ReadToEndAsync()
$errTask = $p.StandardError.ReadToEndAsync()
if (-not $p.WaitForExit($TimeoutSec * 1000)) {
try { $p.Kill() } catch { }
return [pscustomobject]@{ ExitCode = -2; StdOut = ''; StdErr = 'timeout'; TimedOut = $true }
}
$p.WaitForExit()
return [pscustomobject]@{ ExitCode = $p.ExitCode; StdOut = $outTask.Result; StdErr = $errTask.Result; TimedOut = $false }
}
function Normalize-Path([string]$p) {
if ([string]::IsNullOrWhiteSpace($p)) { return $null }
$p = $p.Trim().Trim('"').Replace('/', '\')
try { $p = [System.IO.Path]::GetFullPath($p) } catch { return $null }
return $p.TrimEnd('\')
}
# resolve a (possibly) symlinked file to its target, so WAMP's apache\bin\php.ini -> phpForApache.ini dedupes
function Resolve-Link([string]$p) {
try {
$it = Get-Item -LiteralPath $p -Force -ErrorAction Stop
if ($it.Attributes -band [IO.FileAttributes]::ReparsePoint) {
$t = $it.Target
if ($t -is [array]) { $t = $t[0] }
if ($t) {
if (-not [System.IO.Path]::IsPathRooted($t)) { $t = Join-Path $it.DirectoryName $t }
return (Normalize-Path $t)
}
}
} catch { }
return $p
}
function Backup-File([string]$src) {
$rel = $src -replace '^([A-Za-z]):', '$1'
$dst = Join-Path $BACKUP_DIR $rel
try {
[void](New-Item -ItemType Directory -Path (Split-Path $dst -Parent) -Force -ErrorAction Stop)
[System.IO.File]::Copy($src, $dst, $true) # follows symlinks: backs up the real content
return $dst
} catch { Warn "backup failed for $src : $($_.Exception.Message)"; return $null }
}
function Record([string]$type, [string]$path, [string]$backup) {
if ($CONFIG_DRY_RUN) { return }
$script:ManifestEntries.Add([pscustomobject]@{ Type = $type; Path = $path; Backup = $backup; Ts = $RUN_TS })
}
function Save-Manifest {
if ($CONFIG_DRY_RUN) { return }
$existing = @(Read-Manifest)
$all = @($existing + $script:ManifestEntries)
try { ConvertTo-Json -InputObject $all -Depth 4 | Set-Content -LiteralPath $MANIFEST -Encoding UTF8 } catch { Warn "cannot write manifest $MANIFEST : $($_.Exception.Message)" }
}
function Read-Manifest {
if (-not (Test-Path -LiteralPath $MANIFEST)) { return @() }
try { $j = Get-Content -LiteralPath $MANIFEST -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop; return @($j) } catch { Warn "manifest unreadable: $MANIFEST"; return @() }
}
# --- text files with encoding / EOL preservation --------------------------------
function Read-TextFile([string]$path) {
$bytes = [System.IO.File]::ReadAllBytes($path)
$bom = $false; $enc = $null
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $bom = $true; $enc = New-Object System.Text.UTF8Encoding($true) }
else {
try { $strict = New-Object System.Text.UTF8Encoding($false, $true); [void]$strict.GetString($bytes); $enc = New-Object System.Text.UTF8Encoding($false) }
catch { $enc = [System.Text.Encoding]::Default } # ANSI (Latin-1 accents in comments...)
}
$text = $enc.GetString($bytes)
if ($bom) { $text = $text.TrimStart([char]0xFEFF) }
$eol = if ($text.Contains("`r`n")) { "`r`n" } else { "`n" }
$trailing = $text.EndsWith("`n")
$lines = [regex]::Split($text, "`r`n|`n|`r")
if ($trailing -and $lines.Count -gt 0 -and $lines[-1] -eq '') { $lines = $lines[0..($lines.Count - 2)] }
return [pscustomobject]@{ Lines = [string[]]$lines; Encoding = $enc; Eol = $eol; TrailingNewline = $trailing }
}
function Write-TextFile([string]$path, [string[]]$lines, $info) {
$text = ($lines -join $info.Eol)
if ($info.TrailingNewline) { $text += $info.Eol } # a file without final newline stays that way, so revert is byte-exact
[System.IO.File]::WriteAllText($path, $text, $info.Encoding) # writes through symlinks, keeps ACLs
}
function Has-Marker([string]$path) {
try { return ((Get-Content -LiteralPath $path -Raw -ErrorAction Stop) -match [regex]::Escape($MARK_BEGIN_RE)) } catch { return $false }
}
# ----------------------------------------------------------------------------
# apply / revert primitives
# ----------------------------------------------------------------------------
function Ini-ApplyInPlace([string]$f) {
if (Has-Marker $f) { Ok "already applied: $f"; return }
if ($CONFIG_DRY_RUN) { Dry "would edit in place: $f (comment out existing '$DIRECTIVE' lines, append marker block)"; return }
$bak = Backup-File $f; if (-not $bak) { return }
try {
$t = Read-TextFile $f
$out = New-Object System.Collections.Generic.List[string]
foreach ($l in $t.Lines) { if ($l -match "^\s*$DIRECTIVE_RE\s*=") { $out.Add($DISABLED_PREFIX + $l) } else { $out.Add($l) } }
$out.Add(''); $out.Add($MARK_BEGIN); $out.Add($INI_LINE); $out.Add($MARK_END)
Write-TextFile $f $out.ToArray() $t
Record 'MODIFIED' $f $bak; $script:Changes++
Ok "edited in place: $f (backup: $bak)"
} catch { Warn "edit failed on $f : $($_.Exception.Message)" }
}
function Ini-RevertInPlace([string]$f) {
$raw = $null; try { $raw = Get-Content -LiteralPath $f -Raw -ErrorAction Stop } catch { return }
if (-not ($raw -match [regex]::Escape($MARK_BEGIN_RE)) -and -not ($raw -match "(?m)^" + [regex]::Escape($DISABLED_PREFIX))) { return }
if ($CONFIG_DRY_RUN) { Dry "would remove marker block and restore commented lines in: $f"; return }
$bak = Backup-File $f; if (-not $bak) { return }
try {
$t = Read-TextFile $f
$out = New-Object System.Collections.Generic.List[string]
$skip = $false
foreach ($l in $t.Lines) {
if ($l.Contains($MARK_BEGIN_RE)) { $skip = $true; continue }
if ($l.Contains($MARK_END_RE)) { $skip = $false; continue }
if ($skip) { continue }
if ($l.StartsWith($DISABLED_PREFIX)) { $out.Add($l.Substring($DISABLED_PREFIX.Length)) } else { $out.Add($l) }
}
if ($out.Count -gt 0 -and $out[$out.Count - 1] -eq '') { $out.RemoveAt($out.Count - 1) } # the one blank line we added
Write-TextFile $f $out.ToArray() $t
Record 'REVERTED' $f $bak; $script:Changes++
Ok "reverted: $f (backup of pre-revert state: $bak)"
} catch { Warn "revert failed on $f : $($_.Exception.Message)" }
}
function Dropin-Apply([string]$dir) {
$f = Join-Path $dir $DROPIN_NAME
if ((Test-Path -LiteralPath $f) -and (Has-Marker $f)) { Ok "already applied: $f"; return }
if ($CONFIG_DRY_RUN) { Dry "would create drop-in: $f"; return }
try {
if (Test-Path -LiteralPath $f) { $bak = Backup-File $f; Record 'MODIFIED' $f $bak }
[System.IO.File]::WriteAllText($f, ($MARK_BEGIN + "`r`n" + $INI_LINE + "`r`n" + $MARK_END + "`r`n"), (New-Object System.Text.UTF8Encoding($false)))
Record 'DROPIN' $f ''; $script:Changes++
Ok "drop-in created: $f"
} catch { Warn "cannot write $f : $($_.Exception.Message)" }
}
function Dropin-Revert([string]$f) {
if (-not (Test-Path -LiteralPath $f)) { return }
if (-not (Has-Marker $f)) { Warn "drop-in $f exists but has no marker, left untouched"; return }
if ($CONFIG_DRY_RUN) { Dry "would delete drop-in: $f"; return }
$bak = Backup-File $f
try { Remove-Item -LiteralPath $f -Force -ErrorAction Stop; Record 'REVERTED' $f $bak; $script:Changes++; Ok "drop-in removed: $f" } catch { Warn "cannot delete $f : $($_.Exception.Message)" }
}
function Ini-CreateMinimal([string]$f) {
if ($CONFIG_DRY_RUN) { Dry "would create minimal php.ini: $f"; return }
try {
$dir = Split-Path $f -Parent
if (-not (Test-Path -LiteralPath $dir)) { [void](New-Item -ItemType Directory -Path $dir -Force -ErrorAction Stop) }
$content = "; php.ini $CREATED_TAG on $RUN_TS`r`n; No php.ini existed here: all other settings keep PHP built-in defaults.`r`n$MARK_BEGIN`r`n$INI_LINE`r`n$MARK_END`r`n"
[System.IO.File]::WriteAllText($f, $content, (New-Object System.Text.UTF8Encoding($false)))
Record 'CREATED' $f ''; $script:Changes++
Ok "minimal php.ini created: $f"
} catch { Warn "cannot create $f : $($_.Exception.Message)" }
}
function Ini-RemoveCreated([string]$f) {
if (-not (Test-Path -LiteralPath $f)) { return }
$raw = Get-Content -LiteralPath $f -Raw
if (-not ($raw -match [regex]::Escape($CREATED_TAG))) { Ini-RevertInPlace $f; return }
$others = @([regex]::Split($raw, "`r`n|`n|`r") | Where-Object { $_ -notmatch '^\s*;' -and $_ -notmatch '^\s*$' -and $_ -notmatch "^\s*$DIRECTIVE_RE" })
if ($others.Count -gt 0) { Warn "$f was created by us but has been modified since: reverting markers only"; Ini-RevertInPlace $f; return }
if ($CONFIG_DRY_RUN) { Dry "would delete php.ini we created: $f"; return }
$bak = Backup-File $f
try { Remove-Item -LiteralPath $f -Force -ErrorAction Stop; Record 'REVERTED' $f $bak; $script:Changes++; Ok "removed php.ini we had created: $f" } catch { Warn "cannot delete $f : $($_.Exception.Message)" }
}
# ----------------------------------------------------------------------------
# discovery
# ----------------------------------------------------------------------------
$script:PhpExes = @{} # path -> [pscustomobject] Path, Kind (cli|cgi), Source, Phprc, ScanDir
$script:Apaches = @{} # httpd.exe path -> [pscustomobject] Exe, ServerRoot, ConfArgs, Service, Running
$script:Targets = New-Object System.Collections.Generic.List[object]
$script:SeenTgt = @{}
$script:RegIniPaths = New-Object System.Collections.Generic.List[string]
function Add-PhpExe([string]$path, [string]$source, [string]$phprc = $null, [string]$scanDir = $null) {
$p = Normalize-Path $path
if (-not $p -or -not (Test-Path -LiteralPath $p -PathType Leaf)) { return }
$kind = if ((Split-Path $p -Leaf) -ieq 'php-cgi.exe') { 'cgi' } else { 'cli' }
if ($script:PhpExes.ContainsKey($p)) {
$e = $script:PhpExes[$p]
if ($phprc -and -not $e.Phprc) { $e.Phprc = $phprc }
if ($scanDir -and -not $e.ScanDir) { $e.ScanDir = $scanDir }
return
}
$script:PhpExes[$p] = [pscustomobject]@{ Path = $p; Kind = $kind; Source = $source; Phprc = $phprc; ScanDir = $scanDir }
# the sibling binary belongs to the same install
$sib = Join-Path (Split-Path $p -Parent) $(if ($kind -eq 'cgi') { 'php.exe' } else { 'php-cgi.exe' })
if ((Test-Path -LiteralPath $sib) -and -not $script:PhpExes.ContainsKey((Normalize-Path $sib))) { Add-PhpExe $sib "sibling of $source" $phprc $scanDir }
}
function Add-Target([string]$ini, [string]$scan, [string]$createAt, [string]$label, [string]$exe) {
if ($ini) { $ini = Resolve-Link (Normalize-Path $ini) }
if ($scan) { $scan = Normalize-Path $scan; if (-not (Test-Path -LiteralPath $scan -PathType Container)) { $scan = $null } }
if ($createAt) { $createAt = Normalize-Path $createAt }
if ($scan -and $ini -and -not (Test-Path -LiteralPath $ini -PathType Leaf)) { $ini = $null } # drop-in will do
if (-not $ini -and -not $scan -and -not $createAt) { return }
$key = "$ini|$scan"; if (-not $ini -and -not $scan) { $key = "create:$createAt" }
$key = $key.ToLowerInvariant()
if ($script:SeenTgt.ContainsKey($key)) { $t = $script:SeenTgt[$key]; if (-not $t.Exe -and $exe) { $t.Exe = $exe }; return }
$t = [pscustomobject]@{ Ini = $ini; ScanDir = $scan; CreateAt = $createAt; Label = $label; Exe = $exe }
$script:SeenTgt[$key] = $t
$script:Targets.Add($t)
}
function Get-FixedDrives { Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Root -match '^[A-Za-z]:\\$' } | ForEach-Object { $_.Root.TrimEnd('\') } }
function Find-ByPatterns([string[]]$patterns) {
$found = New-Object System.Collections.Generic.List[string]
foreach ($drive in Get-FixedDrives) {
foreach ($pat in $patterns) {
$full = $pat -replace '^C:', $drive
try { Resolve-Path -Path $full -ErrorAction SilentlyContinue | ForEach-Object { $found.Add($_.ProviderPath) } } catch { }
}
}
return $found
}
function Find-PhpBinaries {
# 1) PATH
foreach ($n in 'php.exe', 'php-cgi.exe') {
try { Get-Command $n -All -ErrorAction SilentlyContinue | ForEach-Object { Add-PhpExe $_.Source 'PATH' } } catch { }
}
# 2) services and running processes
try {
Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | ForEach-Object {
$pn = $_.PathName
if ($pn -match '(?i)^(?:"([^"]+\.exe)"|(\S+\.exe))') {
$exe = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
if ($exe -match '(?i)php(-cgi)?\.exe$') { Add-PhpExe $exe "service $($_.Name)" }
elseif ($exe -match '(?i)httpd\.exe$|apache[^\\]*\.exe$') { Add-Apache $exe "service $($_.Name)" $_.Name $pn ($_.State -eq 'Running') }
}
}
} catch { }
foreach ($pr in 'php', 'php-cgi', 'httpd', 'apache') {
try { Get-Process -Name $pr -ErrorAction SilentlyContinue | ForEach-Object { if ($_.Path) { if ($pr -like 'php*') { Add-PhpExe $_.Path 'running process' } else { Add-Apache $_.Path 'running process' $null $null $true } } } } catch { }
}
# 3) IIS FastCGI
Find-IisPhp
# 4) registry
foreach ($k in 'HKLM:\SOFTWARE\PHP', 'HKLM:\SOFTWARE\WOW6432Node\PHP') {
if (-not (Test-Path $k)) { continue }
foreach ($key in @(Get-Item $k -ErrorAction SilentlyContinue) + @(Get-ChildItem $k -Recurse -ErrorAction SilentlyContinue)) {
$v = $null; try { $v = (Get-ItemProperty -LiteralPath $key.PSPath -ErrorAction SilentlyContinue).IniFilePath } catch { }
if ($v) { $script:RegIniPaths.Add((Normalize-Path $v)) }
if ($key.PSChildName -eq 'Per Directory Values') { Warn "registry 'Per Directory Values' exist under $($key.PSPath): they can override php.ini per directory, review them" }
}
}
# 5) well-known locations, on every fixed drive
$pats = @(
'C:\php*\php.exe', 'C:\php*\php-cgi.exe',
'C:\xampp\php\php.exe',
'C:\wamp*\bin\php\php*\php.exe',
'C:\laragon\bin\php\*\php.exe',
'C:\Program Files\PHP\php.exe', 'C:\Program Files\PHP\*\php.exe', 'C:\Program Files (x86)\PHP\php.exe', 'C:\Program Files (x86)\PHP\*\php.exe',
'C:\Program Files\iis express\PHP\*\php.exe',
'C:\tools\php*\php.exe', 'C:\ProgramData\chocolatey\lib\php*\tools\php.exe',
'C:\inetpub\php*\php.exe', 'C:\inetpub\*\php\php.exe',
'C:\Bitnami\*\php\php.exe', 'C:\UwAmp\bin\php\*\php.exe',
'C:\OSPanel\modules\php\*\php.exe', 'C:\OpenServer\modules\php\*\php.exe',
'C:\Program Files*\Plesk\Additional\PleskPHP*\php.exe', 'C:\Program Files*\Parallels\Plesk\Additional\PleskPHP*\php.exe',
'C:\Program Files*\Plesk\Additional\PleskPHP*\php-cgi.exe'
)
foreach ($f in (Find-ByPatterns $pats)) { Add-PhpExe $f 'well-known location' }
foreach ($root in $CONFIG_EXTRA_SEARCH_ROOTS) {
if (Test-Path -LiteralPath $root) {
# (-Include is unreliable with -LiteralPath on PS 5.1, filter by name instead)
try { Get-ChildItem -LiteralPath $root -Recurse -Depth 3 -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -in @('php.exe', 'php-cgi.exe', 'httpd.exe') } | ForEach-Object { if ($_.Name -ieq 'httpd.exe') { Add-Apache $_.FullName 'extra root' $null $null $false } else { Add-PhpExe $_.FullName 'extra root' } } } catch { }
}
}
# 6) Apache installs
$apats = @(
'C:\xampp\apache\bin\httpd.exe', 'C:\wamp*\bin\apache\apache*\bin\httpd.exe', 'C:\Apache*\bin\httpd.exe',
'C:\laragon\bin\apache\*\bin\httpd.exe', 'C:\Program Files*\Apache Software Foundation\Apache*\bin\httpd.exe',
'C:\Program Files*\Apache*\bin\httpd.exe', 'C:\Bitnami\*\apache*\bin\httpd.exe', 'C:\UwAmp\bin\apache\bin\httpd.exe',
'C:\OSPanel\modules\http\Apache*\bin\httpd.exe', 'C:\OpenServer\modules\http\Apache*\bin\httpd.exe'
)
foreach ($f in (Find-ByPatterns $apats)) { Add-Apache $f 'well-known location' $null $null $false }
}
function Find-IisPhp {
$cfg = Join-Path $env:windir 'System32\inetsrv\config\applicationHost.config'
if (-not [Environment]::Is64BitProcess -and [Environment]::Is64BitOperatingSystem) { $cfg = Join-Path $env:windir 'Sysnative\inetsrv\config\applicationHost.config' }
if (-not (Test-Path -LiteralPath $cfg)) { return }
try { [xml]$x = Get-Content -LiteralPath $cfg -Raw -ErrorAction Stop } catch { Warn "cannot parse $cfg"; return }
$script:IisConfig = $x
$apps = @($x.SelectNodes('//system.webServer/fastCgi/application'))
foreach ($a in $apps) {
$exe = [Environment]::ExpandEnvironmentVariables([string]$a.fullPath)
if ($exe -notmatch '(?i)php') { continue }
$phprc = $null; $scan = $null
foreach ($ev in @($a.SelectNodes('environmentVariables/environmentVariable'))) {
$val = [Environment]::ExpandEnvironmentVariables([string]$ev.value)
if ($ev.name -ieq 'PHPRC') { $phprc = $val }
if ($ev.name -ieq 'PHP_INI_SCAN_DIR') { $scan = $val }
}
Add-PhpExe $exe 'IIS FastCGI' $phprc $scan
}
foreach ($h in @($x.SelectNodes('//handlers/add[@scriptProcessor]'))) {
$sp = [Environment]::ExpandEnvironmentVariables(([string]$h.scriptProcessor -split '\|')[0])
if ($sp -match '(?i)php') { Add-PhpExe $sp 'IIS handler' }
}
}
function Add-Apache([string]$exe, [string]$source, [string]$svc, [string]$cmdline, [bool]$running) {
$p = Normalize-Path $exe
if (-not $p -or -not (Test-Path -LiteralPath $p -PathType Leaf)) { return }
$args = @()
if ($cmdline) {
if ($cmdline -match '(?i)\s-d\s+("([^"]+)"|(\S+))') { $args += @('-d', $(if ($Matches[2]) { $Matches[2] } else { $Matches[3] })) }
if ($cmdline -match '(?i)\s-f\s+("([^"]+)"|(\S+))') { $args += @('-f', $(if ($Matches[2]) { $Matches[2] } else { $Matches[3] })) }
}
if ($script:Apaches.ContainsKey($p)) {
$a = $script:Apaches[$p]
if ($svc -and -not $a.Service) { $a.Service = $svc; $a.ConfArgs = $args }
if ($running) { $a.Running = $true }
return
}
$root = Split-Path (Split-Path $p -Parent) -Parent
$script:Apaches[$p] = [pscustomobject]@{ Exe = $p; ServerRoot = $root; ConfArgs = $args; Service = $svc; Running = $running; Source = $source }
}
# parse httpd.conf (+ Include/IncludeOptional) for PHPIniDir and LoadModule php
function Read-ApacheConf([string]$file, [string]$root, [int]$depth, $acc) {
if ($depth -gt 4 -or -not (Test-Path -LiteralPath $file -PathType Leaf)) { return }
$acc.Files.Add($file)
$lines = @(); try { $lines = Get-Content -LiteralPath $file -ErrorAction Stop } catch { return }
foreach ($l in $lines) {
if ($l -match '^\s*PHPIniDir\s+"?([^"\r\n]+?)"?\s*$') { $acc.PhpIniDir.Add($Matches[1].Trim()) }
if ($l -match '^\s*LoadModule\s+php\w*_module\s+"?([^"\r\n]+?)"?\s*$') { $acc.PhpModule.Add($Matches[1].Trim()) }
if ($l -match '^\s*FcgidWrapper\s+"?([^"\s]+php-cgi\.exe)') { Add-PhpExe $Matches[1] 'Apache FcgidWrapper' }
if ($l -match '^\s*DocumentRoot\s+"?([^"\r\n]+?)"?\s*$') { $acc.DocRoots.Add($Matches[1].Trim()) }
if ($l -match '^\s*Include(?:Optional)?\s+"?([^"\r\n]+?)"?\s*$') {
$inc = $Matches[1].Trim().Replace('/', '\')
$inc = $inc -replace '\$\{SRVROOT\}', $root -replace '\$\{APACHE_DIR\}', $root
if (-not [System.IO.Path]::IsPathRooted($inc)) { $inc = Join-Path $root $inc }
try { Resolve-Path -Path $inc -ErrorAction SilentlyContinue | ForEach-Object { if (Test-Path -LiteralPath $_.ProviderPath -PathType Leaf) { Read-ApacheConf $_.ProviderPath $root ($depth + 1) $acc } } } catch { }
}
}
}
# the php.ini search order used by PHP on Windows, first existing wins
function Resolve-IniChain([string]$exeDir, [string]$phprc, [string]$sapiDir, [bool]$isCli) {
$cands = New-Object System.Collections.Generic.List[string]
$createAt = $null
foreach ($rc in @($phprc, [Environment]::GetEnvironmentVariable('PHPRC', 'Machine'), $env:PHPRC)) {
if (-not $rc) { continue }
$rc = Normalize-Path $rc; if (-not $rc) { continue }
if (Test-Path -LiteralPath $rc -PathType Container) { $cands.Add((Join-Path $rc 'php.ini')); if (-not $createAt) { $createAt = Join-Path $rc 'php.ini' } }
else { $cands.Add($rc); if (-not $createAt) { $createAt = $rc } }
}
foreach ($r in $script:RegIniPaths) { if (Test-Path -LiteralPath $r -PathType Container) { $cands.Add((Join-Path $r 'php.ini')) } else { $cands.Add($r) } }
if ($isCli) { $cands.Add((Join-Path $exeDir 'php-cli.ini')) }
if ($sapiDir) { $cands.Add((Join-Path $sapiDir 'php.ini')) }
$cands.Add((Join-Path $exeDir 'php.ini'))
$cands.Add((Join-Path $env:windir 'php.ini'))
$hit = $null
foreach ($c in $cands) { if (Test-Path -LiteralPath $c -PathType Leaf) { $hit = $c; break } }
if (-not $createAt) { $createAt = if ($sapiDir) { Join-Path $sapiDir 'php.ini' } else { Join-Path $exeDir 'php.ini' } }
return [pscustomobject]@{ Ini = $hit; CreateAt = $createAt; Candidates = $cands }
}
function Build-Targets {
$machineScan = [Environment]::GetEnvironmentVariable('PHP_INI_SCAN_DIR', 'Machine')
foreach ($e in $script:PhpExes.Values) {
$dir = Split-Path $e.Path -Parent
$scan = $e.ScanDir; if (-not $scan) { $scan = $machineScan }
if ($scan) { $scan = (($scan -split ';') | Where-Object { $_ } | Select-Object -Last 1) } # several dirs: the last one parsed wins
$chain = Resolve-IniChain $dir $e.Phprc $null ($e.Kind -eq 'cli')
Add-Target $chain.Ini $scan $chain.CreateAt "$($e.Kind) $($e.Path) [$($e.Source)]" $e.Path
# what php.exe itself says it loads (covers PHPRC set only in the current session, odd builds...)
if ($e.Kind -eq 'cli') {
$r = Invoke-Proc $e.Path @('--ini') 20
if ($r.ExitCode -eq 0 -and $r.StdOut -match '(?m)^Loaded Configuration File:\s*(.+?)\s*$') {
$loaded = $Matches[1]
if ($loaded -and $loaded -ne '(none)') { Add-Target $loaded $scan $null "php.exe --ini of $($e.Path)" $e.Path }
} elseif ($r.ExitCode -ne 0) { Warn "'$($e.Path) --ini' failed (exit $($r.ExitCode), $($r.StdErr.Trim())): broken install? file-based detection only" }
}
# WAMP keeps the Apache ini next to php.exe
$wamp = Join-Path $dir 'phpForApache.ini'
if (Test-Path -LiteralPath $wamp -PathType Leaf) { Add-Target $wamp $null $null "WAMP phpForApache.ini" $e.Path }
}
foreach ($a in $script:Apaches.Values) {
$acc = [pscustomobject]@{ Files = (New-Object System.Collections.Generic.List[string]); PhpIniDir = (New-Object System.Collections.Generic.List[string]); PhpModule = (New-Object System.Collections.Generic.List[string]); DocRoots = (New-Object System.Collections.Generic.List[string]) }
$conf = $null
$idx = [array]::IndexOf($a.ConfArgs, '-f'); if ($idx -ge 0) { $conf = $a.ConfArgs[$idx + 1] }
$idxd = [array]::IndexOf($a.ConfArgs, '-d'); if ($idxd -ge 0) { $a.ServerRoot = Normalize-Path $a.ConfArgs[$idxd + 1] }
if (-not $conf) { $conf = Join-Path $a.ServerRoot 'conf\httpd.conf' } elseif (-not [System.IO.Path]::IsPathRooted($conf)) { $conf = Join-Path $a.ServerRoot $conf }
Read-ApacheConf $conf $a.ServerRoot 0 $acc
$a | Add-Member -NotePropertyName DocRoots -NotePropertyValue $acc.DocRoots -Force
$a | Add-Member -NotePropertyName HasPhp -NotePropertyValue ($acc.PhpModule.Count -gt 0) -Force
foreach ($m in $acc.PhpModule) {
$mp = Normalize-Path ($m.Replace('/', '\')); if ($mp -and -not [System.IO.Path]::IsPathRooted($m)) { $mp = Join-Path $a.ServerRoot $m }
if ($mp) { $pd = Split-Path $mp -Parent; foreach ($n in 'php.exe', 'php-cgi.exe') { $px = Join-Path $pd $n; if (Test-Path -LiteralPath $px) { Add-PhpExe $px "Apache LoadModule in $($a.Exe)" } } }
}
if ($acc.PhpModule.Count -eq 0) { continue } # no mod_php: FastCGI/php-cgi paths are handled through the php exes
$bin = Split-Path $a.Exe -Parent
$exeForVerify = $null
foreach ($m in $acc.PhpModule) { $pd = Split-Path (Normalize-Path $m.Replace('/', '\')) -Parent; $px = Join-Path $pd 'php.exe'; if (Test-Path -LiteralPath $px) { $exeForVerify = $px } }
if ($acc.PhpIniDir.Count -gt 0) {
foreach ($d in $acc.PhpIniDir) {
$dd = $d.Replace('/', '\') -replace '\$\{SRVROOT\}', $a.ServerRoot -replace '\$\{APACHE_DIR\}', $a.ServerRoot
if (-not [System.IO.Path]::IsPathRooted($dd)) { $dd = Join-Path $a.ServerRoot $dd }
$dd = Normalize-Path $dd
if (Test-Path -LiteralPath $dd -PathType Container) { $ini = Join-Path $dd 'php.ini' } else { $ini = $dd }
if (Test-Path -LiteralPath $ini -PathType Leaf) { Add-Target $ini $null $null "Apache mod_php PHPIniDir ($($a.Exe))" $exeForVerify }
else {
$chain = Resolve-IniChain $bin $null $bin $false
if ($chain.Ini) { Add-Target $chain.Ini $null $null "Apache mod_php ($($a.Exe))" $exeForVerify } else { Add-Target $null $null $ini "Apache mod_php PHPIniDir ($($a.Exe))" $exeForVerify }
}
}
} else {
$chain = Resolve-IniChain $bin $null $bin $false
Add-Target $chain.Ini $null $chain.CreateAt "Apache mod_php ($($a.Exe))" $exeForVerify
}
}
foreach ($x in $CONFIG_EXTRA_INI_FILES) { Add-Target $x $null $x 'extra ini (settings)' $null }
foreach ($x in $CONFIG_EXTRA_SCAN_DIRS) { Add-Target $null $x $null 'extra scan dir (settings)' $null }
}
# ----------------------------------------------------------------------------
# restart web servers
# ----------------------------------------------------------------------------
function Get-AppCmd {
$d = Join-Path $env:windir 'System32\inetsrv'
if (-not [Environment]::Is64BitProcess -and [Environment]::Is64BitOperatingSystem) { $d = Join-Path $env:windir 'Sysnative\inetsrv' }
$p = Join-Path $d 'appcmd.exe'
if (Test-Path -LiteralPath $p) { return $p }
return $null
}
function Restart-WebServers {
if (-not $CONFIG_RELOAD_SERVICES) { Info 'service restart disabled (CONFIG_RELOAD_SERVICES = $false)'; return }
if ($CONFIG_DRY_RUN) { Dry 'would recycle IIS application pools and restart Apache'; return }
if ($script:Changes -eq 0) { Info 'nothing changed, no restart needed'; return }
# --- IIS
$w3 = Get-Service -Name W3SVC -ErrorAction SilentlyContinue
if ($w3 -and $w3.Status -eq 'Running') {
$appcmd = Get-AppCmd
if ($appcmd) {
$r = Invoke-Proc $appcmd @('list', 'apppool', '/state:Started', '/text:APPPOOL.NAME') 30
$pools = @($r.StdOut -split "`r?`n" | Where-Object { $_.Trim() })
$n = 0
foreach ($pool in $pools) {
$rr = Invoke-Proc $appcmd @('recycle', 'apppool', "/apppool.name:$($pool.Trim())") 60
if ($rr.ExitCode -eq 0) { $n++ } else { Warn "recycle failed for app pool '$pool': $($rr.StdOut.Trim()) $($rr.StdErr.Trim())" }
}
Ok "IIS: recycled $n application pool(s) (FastCGI php-cgi.exe workers are restarted with them)"
} else {
$rr = Invoke-Proc (Join-Path $env:windir 'System32\iisreset.exe') @('/restart') 120
if ($rr.ExitCode -eq 0) { Ok 'IIS: iisreset /restart done' } else { Warn "iisreset failed: $($rr.StdOut.Trim())" }
}
}
# --- Apache: services first, then console instances
foreach ($a in $script:Apaches.Values) {
if (-not $a.Running) { continue }
$t = Invoke-Proc $a.Exe (@($a.ConfArgs) + @('-t')) 30 $null (Split-Path $a.Exe -Parent)
if ($t.ExitCode -ne 0) { Warn "Apache config test failed for $($a.Exe): $($t.StdErr.Trim()) - not restarting it"; continue }
if ($a.Service) {
try { Restart-Service -Name $a.Service -Force -ErrorAction Stop; Ok "Apache service '$($a.Service)' restarted" } catch { Warn "restart failed for service '$($a.Service)': $($_.Exception.Message)" }
} else {
$rr = Invoke-Proc $a.Exe (@($a.ConfArgs) + @('-k', 'restart')) 60 $null (Split-Path $a.Exe -Parent)
if ($rr.ExitCode -eq 0) { Ok "Apache (console instance) restarted: $($a.Exe)" } else { Warn "could not restart console Apache $($a.Exe): $($rr.StdErr.Trim()) - restart it from its control panel" }
}
}
# --- php-cgi.exe spawned by something else (nginx + RunHiddenConsole style)
try {
$w3pids = @(Get-Process -Name w3wp -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
$httpdpids = @(Get-Process -Name httpd, apache -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
Get-CimInstance Win32_Process -Filter "Name = 'php-cgi.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
if ($w3pids -notcontains $_.ParentProcessId -and $httpdpids -notcontains $_.ParentProcessId) {
Warn "php-cgi.exe pid $($_.ProcessId) runs outside IIS/Apache (nginx-style FastCGI?): restart it yourself to load the new php.ini: $($_.CommandLine)"
}
}
} catch { }
}
# ----------------------------------------------------------------------------
# verification
# ----------------------------------------------------------------------------
function Get-EffectiveValue($t) {
$exe = $t.Exe
if (-not $exe) { $exe = ($script:PhpExes.Values | Where-Object { $_.Kind -eq 'cli' } | Select-Object -First 1).Path }
if (-not $exe) { $exe = ($script:PhpExes.Values | Select-Object -First 1).Path }
if (-not $exe) { return 'n/a (no php.exe to test with)' }
$iniArg = if ($t.Ini -and (Test-Path -LiteralPath $t.Ini)) { $t.Ini } elseif ($t.ScanDir) { $t.ScanDir } else { return 'n/a (no php.ini)' }
$envs = @{ 'PHP_INI_SCAN_DIR' = $(if ($t.ScanDir) { $t.ScanDir } else { '' }) }
$r = Invoke-Proc $exe @('-c', $iniArg, '-i') 25 $envs
if ($r.ExitCode -lt 0) { return "n/a ($($r.StdErr))" }
if ($r.StdOut -match "(?m)^$DIRECTIVE_RE => (\S+) => ") { return $Matches[1] } # php.exe text output
if ($r.StdOut -match "$DIRECTIVE_RE</td><td class=`"v`">([^<]*)<") { return $Matches[1].Trim() } # php-cgi.exe HTML output
if ($r.StdOut -match "(?m)^$DIRECTIVE_RE\s*=>\s*(\S+)") { return $Matches[1] }
return '? (directive absent: session extension not loaded?)'
}
function Verify-Targets {
Log ''
Log '---- verification (value as parsed by PHP for each target) ----'
$bad = 0
foreach ($t in $script:Targets) {
$v = Get-EffectiveValue $t
$what = if ($t.Ini) { $t.Ini } elseif ($t.CreateAt) { "$($t.CreateAt) (to create)" } else { '(no php.ini)' }
if ($t.ScanDir) { $what += " + $($t.ScanDir)\" }
Log (" {0,-6} {1} [{2}]" -f $v, $what, $t.Label)
if (-not $CONFIG_REVERT -and $v -ne 'Off' -and $v -notlike 'n/a*' -and $v -notlike '?*') { $bad++ }
}
if (-not $CONFIG_REVERT -and $bad -gt 0 -and -not $CONFIG_DRY_RUN) { Warn "$bad target(s) still report $DIRECTIVE != Off" }
Log " web SAPI check: a one-off script <?php var_dump(ini_get('$DIRECTIVE')); served through IIS/Apache confirms the live value"
}
function Scan-Overrides {
if (-not $CONFIG_SCAN_OVERRIDES) { return }
Log ''
Log '---- overrides that could re-enable the directive (report only) ----'
$roots = New-Object System.Collections.Generic.List[string]
if ($script:IisConfig) {
foreach ($vd in @($script:IisConfig.SelectNodes('//sites/site/application/virtualDirectory[@physicalPath]'))) { $roots.Add([Environment]::ExpandEnvironmentVariables([string]$vd.physicalPath)) }
}
foreach ($a in $script:Apaches.Values) { if ($a.DocRoots) { foreach ($d in $a.DocRoots) { $roots.Add(($d.Replace('/', '\'))) } } }
foreach ($f in (Find-ByPatterns @('C:\inetpub\wwwroot', 'C:\xampp\htdocs', 'C:\wamp*\www', 'C:\laragon\www', 'C:\inetpub\vhosts'))) { $roots.Add($f) }
$hits = New-Object System.Collections.Generic.List[string]
foreach ($r in ($roots | Sort-Object -Unique)) {
if (-not (Test-Path -LiteralPath $r -PathType Container)) { continue }
try {
Get-ChildItem -LiteralPath $r -Recurse -Depth 6 -Force -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -in @('.user.ini', '.htaccess') } | Select-Object -First 2000 | ForEach-Object {
if (Select-String -LiteralPath $_.FullName -Pattern 'upload_progress' -Quiet -ErrorAction SilentlyContinue) { $hits.Add($_.FullName) }
}
} catch { }
}
if ($hits.Count -eq 0) { Ok 'no .user.ini / .htaccess mentioning upload_progress under the web roots found'; return }
foreach ($h in $hits) { Log " $h"; Select-String -LiteralPath $h -Pattern 'upload_progress' | Select-Object -First 5 | ForEach-Object { Log " $($_.LineNumber): $($_.Line.Trim())" } }
Warn 'the files above mention upload_progress: check they do not set it back On (.user.ini applies to FastCGI, .htaccess php_flag to mod_php)'
}
# ----------------------------------------------------------------------------
# main (skipped when the file is dot-sourced, so the functions can be unit-tested)
# ----------------------------------------------------------------------------
if ($MyInvocation.InvocationName -eq '.') { return }
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin -and -not $CONFIG_DRY_RUN) { Die 'must run elevated (Administrator or SYSTEM)' }
if (-not $CONFIG_DRY_RUN) {
try { [void](New-Item -ItemType Directory -Path $BACKUP_DIR -Force -ErrorAction Stop) } catch { Die "cannot create $BACKUP_DIR : $($_.Exception.Message)" }
}
Log '=============================================================='
Log " $SCRIPT_NAME - mode: $MODE$(if ($CONFIG_DRY_RUN) { ' (DRY RUN)' })"
Log " host: $env:COMPUTERNAME date: $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')) UTC ps: $($PSVersionTable.PSVersion)"
Log '=============================================================='
Find-PhpBinaries
Build-Targets
if ($script:Targets.Count -eq 0 -and $script:PhpExes.Count -eq 0) {
Info 'no PHP installation found on this host, nothing to do'
exit 0
}
Log ''
Log '---- PHP installations found ----'
foreach ($e in $script:PhpExes.Values) {
$v = Invoke-Proc $e.Path @('-v') 15
$ver = if ($v.StdOut) { ($v.StdOut -split "`r?`n")[0] } else { '?' }
Log " $($e.Path) ($ver) [$($e.Source)]"
}
foreach ($a in $script:Apaches.Values) { Log " apache: $($a.Exe) mod_php=$($a.HasPhp) service=$($a.Service) running=$($a.Running)" }
foreach ($t in $script:Targets) { Log " target: ini=$(if ($t.Ini) { $t.Ini } else { '-' }) scan=$(if ($t.ScanDir) { $t.ScanDir } else { '-' }) createAt=$(if ($t.CreateAt) { $t.CreateAt } else { '-' }) [$($t.Label)]" }
Log ''
if (-not $CONFIG_REVERT) {
Log "---- applying: $INI_LINE ----"
foreach ($t in $script:Targets) {
if ($t.ScanDir) { Dropin-Apply $t.ScanDir }
elseif ($t.Ini -and (Test-Path -LiteralPath $t.Ini -PathType Leaf)) { Ini-ApplyInPlace $t.Ini }
elseif ($t.CreateAt) { Ini-CreateMinimal $t.CreateAt }
else { Warn "target [$($t.Label)] has no php.ini, scan dir or creation path, skipped" }
}
} else {
Log '---- reverting ----'
foreach ($t in $script:Targets) {
if ($t.ScanDir) { Dropin-Revert (Join-Path $t.ScanDir $DROPIN_NAME) }
foreach ($f in @($t.Ini, $t.CreateAt)) {
if ($f -and (Test-Path -LiteralPath $f -PathType Leaf)) {
$raw = Get-Content -LiteralPath $f -Raw
if ($raw -match [regex]::Escape($CREATED_TAG)) { Ini-RemoveCreated $f } else { Ini-RevertInPlace $f }
}
}
}
$old = @(Read-Manifest)
if ($old.Count -gt 0) {
foreach ($m in $old) {
if (-not $m.Path -or -not (Test-Path -LiteralPath $m.Path -PathType Leaf)) { continue }
switch ($m.Type) {
'DROPIN' { Dropin-Revert $m.Path }
'CREATED' { Ini-RemoveCreated $m.Path }
'MODIFIED' {
if ($CONFIG_RESTORE_FROM_BACKUP -and $m.Backup -and (Test-Path -LiteralPath $m.Backup)) {
if ($CONFIG_DRY_RUN) { Dry "would restore $($m.Path) from $($m.Backup)" }
else { try { [System.IO.File]::Copy($m.Backup, $m.Path, $true); $script:Changes++; Ok "restored $($m.Path) from backup $($m.Backup)" } catch { Warn "restore failed for $($m.Path): $($_.Exception.Message)" } }
} else { Ini-RevertInPlace $m.Path }
}
}
}
if (-not $CONFIG_DRY_RUN) {
try { Move-Item -LiteralPath $MANIFEST -Destination (Join-Path $CONFIG_STATE_DIR "reverted-$RUN_TS.manifest.json") -Force -ErrorAction Stop } catch { }
}
} else { Info "no manifest at $MANIFEST (never applied here, or already reverted): marker-based revert only" }
}
if (-not $CONFIG_REVERT) { Save-Manifest }
elseif (-not $CONFIG_DRY_RUN -and $script:ManifestEntries.Count -gt 0) {
try { ConvertTo-Json -InputObject @($script:ManifestEntries) -Depth 4 | Set-Content -LiteralPath (Join-Path $CONFIG_STATE_DIR "revert-log-$RUN_TS.json") -Encoding UTF8 } catch { }
}
Log ''
Log '---- restart ----'
Restart-WebServers
Verify-Targets
if (-not $CONFIG_REVERT) { Scan-Overrides }
Log ''
Log '---- summary ----'
Log " mode: $MODE changes: $($script:Changes) warnings: $($script:Warnings)"
if (-not $CONFIG_DRY_RUN -and -not $CONFIG_REVERT) { Log " backups: $BACKUP_DIR manifest: $MANIFEST" }
if (-not $CONFIG_REVERT) { Log ' REMINDER: this is a stopgap. Install the fixed PHP build (8.2+) and restart every SAPI.' }
if ($script:Warnings -gt 0) { exit 2 }
exit 0