PHP extracting files from zip issues with copy - php

I am trying to extract file from a zip via PHP, I have some working code, but when I move it from one server to another it all of sudden stopped working :( In this code, it creates folders, I can see its doing that, but the files in the zip are not being extracted :(
Here is my code:
if($_FILES['url']['error'] == 0){
system('rm -rf ../images/galleries/' . $galleryName);
$filename = $_FILES["url"]["name"];
$source = $_FILES["url"]["tmp_name"];
$type = $_FILES["url"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if (!file_exists('../images/galleries/' . $galleryName)) {
mkdir('../images/galleries/' . $galleryName, 0777, true);
}
$target_path = '../images/galleries/' . $galleryName . '/' . $filename;
$image = $filename;
if(move_uploaded_file($source, $target_path)) {
$path = $target_path;
$zip = new ZipArchive();
if ($zip->open($path) === true) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_")) . '_';
copy("zip://".$path."#".$filename, '../images/galleries/' . $galleryName . '/' . $fileinfo['basename']);
chmod('../images/galleries/' . $galleryName . '/' . $fileinfo['basename'], 0777);
}
$zip->close();
}
}
unlink($path);
$galleryClass->insertImage($connection, $_POST['galleryId'], $image, $_POST['link'], $_POST['order']);
}
I think the issue is with this:
copy("zip://".$path."#".$filename, '../images/galleries/' . $galleryName . '/' . $fileinfo['basename']);
is there another way to do this or is this a server problem?

Try using the extractTo() method instead of copy():
$zip->extractTo('../images/galleries/' . $galleryName . '/' . $fileinfo['basename'], $filename);

Related

PHP - ZipArchive close returns true despite no files being added

I have the following code to create a zip archive. How can I check if the archive was actually created?
When no files are added calling close still returns true?
$profiles = $profileRepository->getProfiles()->get();
$fileName = time() . '-' . uniqid() . '-' . '.zip';
$filePath = storage_path('app/bulkdownloads/' . $fileName);
$zip = new ZipArchive;
if ($zip->open($filePath, ZipArchive::CREATE) === TRUE) {
foreach($profiles as $profile) {
if (file_exists(storage_path('app/' . $profile->file_path)))
$zip->addFile(storage_path('app/' . $profile->file_path), $profile->name . '-' . $profile->id . '.' . pathinfo($profile->file_path, PATHINFO_EXTENSION));
}
$res = $zip->close();
if ($res == true) {
$newFile = \App\File::create([
"name" => $fileName
"path" => 'bulkdownloads/' . $fileName,
"size" => filesize($filePath),
"mime_type" => mime_content_type($filePath),
]);
}
}
I've simply had to refactor the code as follows to get it to work:
$profiles = $profileRepository->getProfiles()->get();
$fileName = time() . '-' . uniqid() . '-' . '.zip';
$filePath = storage_path('app/bulkdownloads/' . $fileName);
$zip = new ZipArchive;
if ($zip->open($filePath, ZipArchive::CREATE) === TRUE) {
foreach($profiles as $profile) {
if (file_exists(storage_path('app/' . $profile->file_path)))
$zip->addFile(storage_path('app/' . $profile->file_path), $profile->name . '-' . $profile->id . '.' . pathinfo($profile->file_path, PATHINFO_EXTENSION));
}
$zip->close();
}
if (file_exists($filePath)) {
$newFile = \App\File::create([
"name" => $fileName
"path" => 'bulkdownloads/' . $fileName,
"size" => filesize($filePath),
"mime_type" => mime_content_type($filePath),
]);
}
Each zip operation will return a boolean if it works so you need to check all of them:
$profiles = $profileRepository->getProfiles()->get();
$fileName = time() . '-' . uniqid() . '-' . '.zip';
$filePath = storage_path('app/bulkdownloads/' . $fileName);
$zip = new ZipArchive;
if ($zip->open($filePath, ZipArchive::CREATE) === TRUE) {
$res = true;
foreach($profiles as $profile) {
if (file_exists(storage_path('app/' . $profile->file_path)))
$res = $res && $zip->addFile(storage_path('app/' . $profile->file_path), $profile->name . '-' . $profile->id . '.' . pathinfo($profile->file_path, PATHINFO_EXTENSION));
else
$res = false;
}
$res = $res && $zip->close();
if ($res == true) {
$newFile = \App\File::create([
"name" => $fileName
"path" => 'bulkdownloads/' . $fileName,
"size" => filesize($filePath),
"mime_type" => mime_content_type($filePath),
]);
}
}

How to check file extension in laravel post request? mycodetest

Here is my code it is working but I want the best practice
if(Input::hasFile('note_thumb')) {
$file = Input::file('note_thumb');
$fileName = substr($file->getClientOriginalName(), -4);
if ($fileName == '.jpg' || $fileName == 'jpeg' || $fileName == '.png') {
//is image
//return 'maaz';
$finalpath = "";
$file = Input::file('note_thumb');
$tmpFilePath = '/notes/thumnail/';
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$tmpFileName = preg_replace('/\s+/', '', $tmpFileName);
$file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
$path = $tmpFileName;
$finalpath .= $path;
/*if ($i != $count_file - 1) {
$finalpath .= ',';
}*/
$newNote->note_thumb = $finalpath;
}
Try this:
$extension = $request->note_thumb->getClientOriginalExtension();
From the documentation:
https://laravel.com/docs/5.6/requests

recursively copy a specific file extension php

I am writing a function to recursively copy a specific file type from one folder to the other, but the function copies all the files in the folder.
function recurse_copy($src, $dst) {
$dir = opendir($src);
#mkdir($dst);
while (false !== ( $file = readdir($dir))) {
if (( $file != '.' ) && ( $file != '..' )) {
if (is_dir($src . '/' . $file)) {
if ($file->getExtension() == "pdf") {
recurse_copy($src . '/' . $file, $dst . '/' . $file);
}
} else {
copy($src . '/' . $file, $dst . '/' . $file);
}
}
} closedir($dir);
}
// if statements for
$itp = new RecursiveDirectoryIterator("foldername/", > FilesystemIterator::SKIP_DOTS);
$displayp = Array('pdf');
$i = 0;
foreach (new RecursiveIteratorIterator($itp) as $filepop) {
if (in_array(strtolower(array_pop(explode('.', $filepop))), $displayp))
if ($filepop->getExtension() == "pdf") {
echo >
recurse_copy("a", "b");
}
}
$itcopy = new RecursiveDirectoryIterator("foldername/", FilesystemIterator::SKIP_DOTS);
$displayp = Array ( 'pdf' );
foreach(new RecursiveIteratorIterator($itcopy) as $filecopy)
{
if (in_array(strtolower(array_pop(explode('.', $filecopy))), $displayp))
if ($filecopy->getExtension()=="pdf"){
copy($filecopy->getrealPath(),'pdf_folder/'.$filecopy->getFilename()) ;
}
}

Php Upload multiple files and rename it if not equal at foreach

Im trying to upload multiple files example:
foreach ($_FILES["images"]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], $_SERVER['DOCUMENT_ROOT'].'/var/uploads/'.$product_id . "/" . $_FILES['images']['name'][$key]);
}
}
Ok now the files are in the server as 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg.. till 24.jpg
Then now Im doing a for each for check if the files that I upload got the name that I want if not rename it.
$directory = $_SERVER['DOCUMENT_ROOT'].'/var/uploads/' . $product_id . "/";
$files = glob($directory . "*.jpg");
foreach($files as $i => $name)
{
$newname = sprintf($directory . "%d.jpg", $i+1);
if ($newname != $i + 1)
{
rename($name, $newname);
}
}
The problem now is that when I rename them I got this result
Why 2.jpg, 3.jpg , 4.jpg till 9.jpg disapear?
Thank you in advance!
Try this..
$directory = $_SERVER['DOCUMENT_ROOT'].'/var/uploads/' . $product_id . "/";
$i = 1;
while (false !== ($file = readdir($directory)))
{
// check extension
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
{
$newName = $i . '.jpg';
rename($file, $newName);//rename file
$i++;
}
}
closedir($directory)
I found the answer :)
$directory = $_SERVER['DOCUMENT_ROOT'].'/var/uploads/' . $product_id . "/";
$files = glob($directory . "*.jpg");
$i = 1;
foreach($files as $e => $name)
{
$newname = $directory . $i . ".jpg";
if($name != $newname)
{
rename($name, $newname);
}
else
{
return 0;
}
$i++;
}

PHP Rename file if exists

I've been working with image uploading and am wondering why this isn't working correctly? It doesn't move/upload the file with the new name if it already exists.
if(isset($_REQUEST['submit'])){
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)){
$loc = "userpics/$filename";
if(file_exists($loc)){
$increment = 0;
list($name, $ext) = explode('.', $loc);
while(file_exists($loc)) {
$increment++;
$loc = $name. $increment . '.' . $ext;
$filename = $name. $increment . '.' . $ext;
}
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
}
else{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$filename");
}
}
else{
echo "invalid file.";
}
}
You've included the folder path in $loc, then you attempt to move a file to userpics/$loc, which is probably incorrect. See the comments:
$filename = "example.jpg";
$loc = "userpics/$filename";
if(file_exists($loc)){
$increment = 0;
list($name, $ext) = explode('.', $loc);
while(file_exists($loc)) {
$increment++;
// $loc is now "userpics/example1.jpg"
$loc = $name. $increment . '.' . $ext;
$filename = $name. $increment . '.' . $ext;
}
// Now you're trying to move the uploaded file to "userpics/$loc"
// which expands to "userpics/userpics/example1.jpg"
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
} else {
// ...
As a general debugging tip, always check a function's return value to see if it was successful. Secondly, display the function's input values if it's failing. It will make debugging things a lot easier.
Try this:
$fullpath = 'images/1086_002.jpg';
$additional = '1';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/'
. $info['filename'] . $additional
. '.' . $info['extension'];
}
Thanks to here:Clickie!!

Categories