У меня есть php-скрипт, который проверяет результат вирустотального сканирования. Если сканирование возвращает положительное значение для вредоносного кода, оно изменяет значение на 0 в db. У меня есть еще один php-скрипт, который проверяет значение, и если он равен 0, он удаляет запись из db, а затем удаляет файл из каталога. Когда я запускаю это через командную строку, он работает отлично, однако, когда cron запускает его, он удаляет запись db, поскольку он должен, однако, не удалять файл из каталога.
Любая помощь приветствуется.
Вот конец файла php с отключением:
else{
// if not it deletes the image
$hash = $row['hash'];
$result2 = mysqli_query($connection, "DELETE FROM userUploads WHERE hash = '$hash' ");
// need due to dir structure
$pat = str_replace('../','', $row['fileName']);
unlink ($pat);
if (! $result2){
echo('Database error: ' . mysqli_error($connection));
}
Для справки, вот полный файл:
<?php
function VirusTotalCheckHashOfSubmitedFile($hash){
$debug = false;
$post = array('apikey' => '','resource'=>$hash);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.virustotal.com/vtapi/v2/file/report');
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); // please compress data
curl_setopt($ch, CURLOPT_USERAGENT, "gzip, My php curl client");
curl_setopt($ch, CURLOPT_VERBOSE, 1); // remove this if your not debugging
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code == 200) { // OK
$js = json_decode($result, true);
if($debug){echo "<pre>";}
if($debug){print_r($js);}
if($js["positives"]==0){
// clean
return true;
}else{
// malware
return false;
}
} else { // Error occured
print($result);
}
curl_close ($ch);
}
$connection = mysqli_connect("");
if (!$connection) {
trigger_error("Could not reach database!<br/>");
}
$db_selected = mysqli_select_db($connection, "seclog");
if (!$db_selected) {
trigger_error("Could not reach database!<br/>");
}
// Selecs images that have not been marked as clean by virus total
$result = mysqli_query($connection, "Select hash, fileName FROM userUploads WHERE scanResult = 0");
if (! $result){
echo('Database error: ' . mysqli_error($connection));
}
while ($row = mysqli_fetch_assoc($result)) {
// checks for results on scanned images
if(VirusTotalCheckHashOfSubmitedFile($row['hash'])){
// if report returns image is malware free we update its virusFree attribute to true
$hash = $row['hash'];
$result2 = mysqli_query($connection, "UPDATE userUploads SET scanResult = 1 WHERE hash = '$hash'");
if (! $result2){
echo('Database error: ' . mysqli_error($connection));
}
}else{
// if not it deletes the image
$hash = $row['hash'];
$result2 = mysqli_query($connection, "DELETE FROM userUploads WHERE hash = '$hash' ");
// need due to dir structure
$pat = str_replace('../','', $row['fileName']);
unlink ($pat);
if (! $result2){
echo('Database error: ' . mysqli_error($connection));
}
}
}
?>
Проблема почти наверняка заключается в пути $pat = str_replace('../','', $row['fileName']);
, Кронки выполняют PHP cli, это не тот же PHP, что и Apache, также является другим контекстом. Попробуйте установить абсолютный путь:
$pat = "/var/www/myfolder/myscript.some";
Если по какой-то причине вам нужна переменная, потому что структура папок зависит от контекста (например, разработка, производство), вы можете передать переменную в качестве параметра, когда cron выполняет PHP:
//this is the cron
30 17 * * 1 myscript.php myvar
Внутри myscript.php $argv[1]
есть myvar
.