Skip to content

Commit d7f3f49

Browse files
committed
Prevented fatal errors when opening corrupt files or "doc" files
1 parent 2daa50c commit d7f3f49

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/PhpWord/Shared/XMLReader.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,15 @@ public function getDomFromZip($zipFile, $xmlFile)
6161
}
6262

6363
$zip = new ZipArchive();
64-
$zip->open($zipFile);
64+
$openStatus = $zip->open($zipFile);
65+
if($openStatus !== true){
66+
/**
67+
* Throw an exception since making further calls on the ZipArchive would cause a fatal error.
68+
* This prevents fatal errors on corrupt archives and attempts to open old "doc" files.
69+
*/
70+
throw new Exception("The archive failed to load with the following error code: $openStatus");
71+
}
72+
6573
$content = $zip->getFromName(ltrim($xmlFile, '/'));
6674
$zip->close();
6775

tests/PhpWordTests/Shared/XMLReaderTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,30 @@ public function testThrowsExceptionOnNonExistingArchive(): void
8585
$reader->getDomFromZip($archiveFile, 'test.xml');
8686
}
8787

88+
/**
89+
* Test that read from invalid archive throws exception.
90+
*/
91+
public function testThrowsExceptionOnZipArchiveOpenErrors(): void
92+
{
93+
$tempPath = tempnam(sys_get_temp_dir(), 'PhpWord');
94+
95+
// Simulate a corrupt archive
96+
file_put_contents($tempPath, rand());
97+
98+
$exceptionMessage = null;
99+
try{
100+
$reader = new XMLReader();
101+
$reader->getDomFromZip($tempPath, 'test.xml');
102+
}
103+
catch(\Exception $e){
104+
$exceptionMessage = $e->getMessage();
105+
}
106+
107+
$this->assertNotNull($exceptionMessage);
108+
109+
unlink($tempPath);
110+
}
111+
88112
/**
89113
* Test elements count.
90114
*/

0 commit comments

Comments
 (0)