Created
November 2, 2020 15:59
-
-
Save dominickj-tdi/22f9f2147e1cf54dc627b6a5cfa85ada to your computer and use it in GitHub Desktop.
Demonstrate possible bug with PDO. The following does not work, but does if you replace `$database->query` with prepared statements.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Perform a cleanup that spans multiple tables and columns | |
* | |
* @param string $dir The directory to search. This should be | |
* a relative directory starting with "upload/", e.g. | |
* "upload/galleries/". The trailing slash is required. | |
* @param PDO $database The database object to use | |
* @param string[][] $searchArray An array of arrays of exactly | |
* 2 strings. The first string is the table name, and the second | |
* is the column name. | |
*/ | |
function tableFileCleanupMulti($dir, $database, $searchArray){ | |
// First we need to build an SQL query to get all the | |
// images in the given search array | |
echo '<hr style="margin-top: 30px;"/><h2>'.$dir.'</h2>'; | |
$matchString = $database->quote("%$dir%"); | |
$sql = implode(' UNION ', array_map(function($tableAndCol) use ($matchString){ | |
$table = $tableAndCol[0]; | |
$column = $tableAndCol[1]; | |
return "SELECT $column FROM $table WHERE $column LIKE $matchString"; | |
}, $searchArray)); | |
$result = $database->query($sql, PDO::FETCH_COLUMN); | |
// Now we need to extract all paths from the data we got | |
$foundFiles = []; | |
$regex = "|{$dir}[-A-Za-z0-9_.]+|"; | |
foreach ($result as $textBlock){ | |
$matches = []; | |
preg_match_all($regex, $textBlock, $matches); | |
array_push($foundFiles, ...$matches[0]); | |
} | |
foreach (scandir($dir) as $file) { | |
if ('.' === $file) continue; | |
if ('..' === $file) continue; | |
if (!in_array($dir.$file, $foundFiles)){ | |
// delete files not in the database | |
echo '<br/>Deleting file: '.$dir.$file; | |
deleteFile($dir.$file); | |
} | |
else{ | |
echo '<br/>Keeping file: '.$dir.$file; | |
} | |
} | |
} | |
tableFileCleanupMulti('upload/imgs/', $DATABASE, [ | |
['settings', 'value'], | |
['articles', 'content'], | |
]) | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment