PHP unlink() problem with files named with multiple extensions - php

I'm encountering an issue I've never come across before. I have some images uploaded as JPG or PNG with a duplicate of the image in WebP format, eg in this file naming convension:
https://example.com/uploads/memory-day.png >
https://example.com/uploads/memory-day.png.webp
If I delete a file through PHP using the unlink() function like normal, it works fine for everything else until I delete the PNG duplicate image. When I do that, the WebP file is also deleted and I can't see how it's happening -- is it a weird issue in the unlink() function with a file having a double extension? I can't seem to replicate it unless it's there's a WebP file involved.
For clarity, here's the PHP code that deletes the files (and yeah, I know it needs to be a prepare statement, I haven't updated it yet):
if(isset($_POST['delete'])) {
$countG = 0;
$err = 0;
foreach($_POST['delFile'] as $actionID) {
$action_id = $conn->real_escape_string($actionID);
$query = $conn->query("SELECT `filename`, `dir` FROM `fileuploads` WHERE `id` = '$action_id'");
$delF = $query->fetch_assoc();
$filenameDel = StripSlashes($delF['filename']);
$filenameDir = StripSlashes($delF['dir']);
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)){
if(unlink($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/auto_thumbs/" . $filenameDel)) {
unlink($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/auto_thumbs/" . $filenameDel);
}
$delquery = $conn->query("DELETE FROM `fileuploads` WHERE `id` = '$action_id'");
$countG++;
} else {
$err++;
}
} else {
$err++;
if(!file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)) {
//Remove from db if file is not there physically
$delquery = $conn->query("DELETE FROM `fileuploads` WHERE `id` = '$action_id'");
}
}
}
if($countG > 0) {
$green = 1;
$message1 = "$countG File(s) Deleted!";
}
if($err > 0) {
$red = 1;
$message2 = "Error deleting $err files!";
error_log(print_r(error_get_last(), TRUE));
}
}

Related

GET File extension on php

i have 2 fields on my project to upload documents(pdf, words) i use the following code to get the file extension on upload and rename the file with my custom name:
$ext= pathinfo($rsnew["File"], PATHINFO_EXTENSION);
my problem that i need to add to this code that, if one of the field if not update with a new document then it use the current extension of the oldrecord that was previous upload, and no change to blank extension
any idea, thanks in advance
using this code but no working
$ext= pathinfo($rsnew["File"], PATHINFO_EXTENSION);
$ext2= pathinfo($rsold["File"], PATHINFO_EXTENSION);
// $trim = substr($docpath,0,4);// not using now
if($_FILES["File"]["size"] == 0) {
$rsnew["File"] = "$rname $docpath1 $docpath2 " . " " . "$docpath ID$randomNumber" . ".$ext2";
} else {
$rnew["File"] = "$rname $docpath1 $docpath2 " . " " . "$docpath ID$randomNumber" . ".$ext";
return TRUE;
}
}

generate two files with different extensions with the same unique id

I believe it's a matter of logic but I can't solve it.
I have a code that converts any video file to mp4, but at the moment I'm only converting to .gif. I wanted to know how I can generate a .mp4 and a .gif file with the same unique id.
I tried something like this
$finalFilePath = $targetDir . uniqid() . ".gif" ".mp4";
However, I was not successful.
It is only one file generator
In this case a uniqueid.gif file that is actually mp4.
and the intention is to generate both with the same unique id.
Thank you very much in advance.
Any help is welcome.
update more content to ask --->
Hello, using this code below I can generate the 2 files, but the problem is, two files are generated but both should have the same uniqid. however they are generated with different names, I'm having difficulties in creating a variable that stores only one uniqid this is my big problem.
if(move_uploaded_file($videoData["tmp_name"], $tempFilePath)) {
$finalFilePath = $targetDir . uniqid() . ".gif" ;
$finalFilePath2 = $targetDir . uniqid() . ".mp4";
if(!$this->insertVideoData($videoUploadData, $finalFilePath)) {
echo "Insert query failed\n";
return false;
}
if(!$this->convertVideoToMp4($tempFilePath, $finalFilePath2)) {
echo "Upload failed\n";
return false;
}
Function Upload.
public function upload($videoUploadData) {
$targetDir = "uploads/videos/";
$videoData = $videoUploadData->videoDataArray;
$tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);
$tempFilePath = str_replace(" ", "_", $tempFilePath);
$isValidData = $this->processData($videoData, $tempFilePath);
if(!$isValidData) {
return false;
}
if(move_uploaded_file($videoData["tmp_name"], $tempFilePath)) {
$finalFilePath = $targetDir . uniqid() . ".gif";
if(!$this->insertVideoData($videoUploadData, $finalFilePath)) {
echo "Insert query failed\n";
return false;
}
return true;
}
}
Function ConvertVideoToMp4
public function convertVideoToMp4($tempFilePath, $finalFilePath) {
$cmd = "$this->ffmpegPath -i $tempFilePath -pix_fmt rgb24 -r 4 -vf scale=540:-1 $finalFilePath 2>&1";
$outputLog = array();
exec($cmd, $outputLog, $returnCode);
if($returnCode != 0) {
//Command failed
foreach($outputLog as $line) {
echo $line . "<br>";
}
return false;
}
return true;
}
Call uniqid once and store it to a variable and use it how many times you want.
I think the better way to create a unique id is:
$bytes = random_bytes(16);
echo bin2hex($bytes);
random_bytes() generates cryptographically secure pseudo-random bytes. Further, passing its output to another function bin2hex(), will give you unique random string.
$id = uniqid();
$finalFilePath = $targetDir . $id . ".gif" ;
$finalFilePath2 = $targetDir . $id . ".mp4";
Simple ;)

Mobile audio upload returning octet/stream

On desktop, the upload works correctly, but when I try to upload from a mobile device, it says that the extension is outside the array, and print returns octet-stream, any thoughts? I can't see what could be wrong. I have tried many audio extensions, checked MIME and tested with a few smartphones, no success.
if (isset($_POST['submit_atrack'])) {
$fileinfo=PATHINFO($_FILES["audio"]["name"]);
$newFilename=$fileinfo['filename'] . uniqid($usr_idLogged) . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["audio"]["tmp_name"],"atracks/" . $newFilename);
$location = 'atracks/' . $newFilename;
$formatos = array('audio/mpeg', 'audio/ogg', 'audio/mp3', 'audio/*', 'audio/wav');
$tamanho_max = 500000000; //500 mb
if (empty($_FILES['audio']['name']))
{
$upload_empty = urlencode("empty");
header("Location:playlist?newtrack=".$upload_empty . "&playlist=" . $selectedPlaylist);
exit;
}
else if (!in_array($_FILES['audio']['type'], $formatos))
{
$upload_incorrectformat = urlencode("incorrectext");
header("Location:playlist?newtrack=".$upload_incorrectformat . "&playlist=" . $selectedPlaylist);
exit;
}
else if (in_array($_FILES['audio']['type'], $formatos))
{
if($_FILES['audio']['size'] >= $tamanho_max)
{
$upload_maxsize = urlencode("maxsizereached");
header("Location:playlist?newtrack=".$upload_maxsize . "&playlist=" . $selectedPlaylist);
exit;
}
else
{
$atitle = mysqli_real_escape_string($connection, $_POST['atitle']);
$atag = mysqli_real_escape_string($connection, $_POST['atag']);
$atagcolor = mysqli_real_escape_string($connection, $_POST['atagcolor']);
mysqli_query($connection,"INSERT INTO tbl_users_atrack (atrack_title, atrack_path, atrack_tag, atrack_tagColor, atrack_playlistId) VALUES ('$atitle', '$location', '$atag', '$atagcolor', '$selectedPlaylist')");
$upload_success = urlencode("success");
header("Location:playlist?newtrack=" . $upload_success . "&playlist=" . $selectedPlaylist);
exit;
}
}
}

Losing variable value when trying to copy file using mailReader.php

I'm using the mailReader script found here: https://github.com/stuporglue/mailreader
I am trying to copy the file(s) after upload to another folder.
The file(s) upload correctly to the folder where the script resides.
When I try to run a copy command, the filename variable is empty.
Here is the portion of the code I am working with: The last three lines are what I added.
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I receive confirmation by email that the file(s) are uploaded, then another email with the error message.
Warning: copy(/attachments/W7652222-546/1453406138_residential-print_from_td.pdf): failed to open stream: No such file or directory in /home/myhost/public_html/mailreader/mailReader.php on line 224
224 being the line number of my added code.
The source filename is missing from in front of /attachments...
Anyone have any thoughts?
$name is defined in the while loop and may not be accessible on the upper scopes my suggestion is to change your code to this:
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
$name = '';
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I hope this solves your problem
I ended up defining a constant of email_id in the private function saveToDb, then running a script after everything else is finished to query the table using the email_id and looping through the records moving the files.

Can't see image, but, I know it's there

I have an image located on my site at:
www.blah.com/gallery/gallery/2244.jpg
If I type this URL directly I see the image.
Now, I have a small gallery where I want the image (and others) to show, but, using the following code it simply does not show:
$files = glob("/home/mysite/public_html/gallery/gallery/*.*");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<a class="fancybox-effects-a" rel="gallery" href="'.$num.'">';
echo '<img src="'.$num.'" class="gallery_img" alt=""></a>';
}
The image was uploaded without error like so (using http://www.verot.net/php_class_upload.htm):
if(isset($_FILES['image'])){
include('/home/mysite/php/lib/img_upload/class.upload.php');
// retrieve eventual CLI parameters
$cli = (isset($argc) && $argc > 1);
if ($cli) {
if (isset($argv[1])) $_GET['file'] = $argv[1];
if (isset($argv[2])) $_GET['dir'] = $argv[2];
if (isset($argv[3])) $_GET['pics'] = $argv[3];
}
// set variables
$dir_dest = (isset($_GET['dir']) ? $_GET['dir'] : 'test');
$dir_pics = (isset($_GET['pics']) ? $_GET['pics'] : $dir_dest);
if (!$cli) {
// ---------- IMAGE UPLOAD ----------
$handle = new Upload($_FILES['image']);
if ($handle->uploaded) {
$handle->image_resize = true;
$handle->image_ratio_x = true;
$handle->image_y = 500;
$handle->Process('/home/mysite/public_html/gallery/gallery/');
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
$success .= 'Image uploaded to the gallery successfully!';
} else {
// one error occured
$error .= '<li>file not uploaded to the wanted location';
$error .= '<li>Error: ' . $handle->error . '';
}
// we now process the image a second time, with some other settings
/******************************/
// produce thumbnails
/*****************************/
$handle->image_resize = true;
$handle->image_ratio_x = true;
$handle->image_y = 120;
$handle->image_reflection_height = 50;
$handle->image_reflection_opacity = 90;
$handle->image_convert = 'png';
$handle->Process('/home/mysite/public_html/gallery/gallery/thumbs/');
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
$success .= '<p>Thumbnail created successfully, see below...';
$success .= '<p><img src="/gallery/gallery/thumbs/' . $handle->file_dst_name . '" />';
} else {
// one error occured
$error .= 'file not uploaded to the wanted location';
$error .= ' Error: ' . $handle->error . '';
}
/******************************/
// END use this if you want to produce thumbnails
/*****************************/
// we delete the temporary files
$handle-> Clean();
} else {
// if we're here, the upload file failed for some reasons
// i.e. the server didn't receive the file
$error .= '<li>file not uploaded on the server';
$error .= '<li>Error: ' . $handle->error . '';
}
}
}
I cannot fathom this out at all!
It looks like you set the src to the images' absolute path. Try this:
foreach (glob('/home/mysite/public_html/gallery/gallery/*.jpg') as $file) {
$file = '/gallery/gallery/'.basename($file);
echo '<a class="fancybox-effects-a" rel="gallery" href="'.$file.'">';
echo '<img src="'.$file.'" class="gallery_img" alt=""></a>';
}

Categories