PHP - Loop through folders, open each docx file and replace string - php

I have a script that:
goes through each folder and subfolder of my "./sample/" directory
opens each .docx file
replaces a string such as "##PROPERTY##" with my $_POST['property'] variable
zips the folder content
launches a download
Now, running portions of the code individually, it does what is needed. However, when putting it all together, it dies while scanning the subfolders for docx files.
My folder structure is like this:
./sample/
/IT/it1.docx
/F&B/fb1.docx
/FO/fo1.docx
sample1.docx
The problem seems to occur during the is_dir($dir) part for the level 1 folders.
Any ideas what could cause this?
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// form variables
$holidex = strtoupper($_POST['holidex']);
$property = $_POST['property'];
$brand = $_POST['brand'];
$division = $_POST['division'];
$language = $_POST['language'];
$date_issued = $_POST['date_issued'];
$approved_by = $_POST['approved_by'];
// script variables
//$dir = './Sample_SOP_-_'.$brand.'_('.$language.')'; //dir to scan like ./sample/
$dir = './sample/'; //dir to scan like ./sample/
$archive = date("Y-m-d H-i-s"); //UNIQUE name of zip file to create and download
$zipfile = "./".$holidex." - ".$archive.".zip"; //path to zip file download
$temp = "./temp/"; //directory to temp folder
// string replacements
$find = "##PROPERTY##"; // find and replace property information
$replace = $_POST['property'];
$find2 = "##BRAND##"; // find and replace brand information
$replace2 = $_POST['brand'];
$find3 = "##DATE##"; // find and replace effective date
$replace3 = $_POST['date_issued'];
$find4 = "##APPROVED_BY##"; // find and replace approved by
$replace4 = $_POST['approved_by'];
//read dir
$files = scandir($dir, 1);
//create new archive name
$zip_download = new ZipArchive();
$zip_download->open("$zipfile", ZipArchive::CREATE);
foreach($files as $file) {
//docx
$ext1 = ".docx";
$checkextension = explode($ext1, $file);
if (count($checkextension) > 1) {
$zip = new ZipArchive;
$zip->open("$file");
$word = $zip->getFromName('word/document.xml');
$word2 = str_replace($find, $replace, $word);
$word2 = str_replace($find2, $replace2, $word);
$word2 = str_replace($find3, $replace3, $word);
$word2 = str_replace($find4, $replace4, $word);
$zip->addFromString("word/document.xml", $word2);
$zip->close();
} else {
die("Error - There are no files the directory..");
}
//folders level 1
if (is_dir($file)) {
$sub = $file . '/';
$subfiles = scandir($sub, 1);
if ($subfiles > 1) {
if ($sub == "../" || $sub == "./") {
}
else {
foreach($subfiles as $subfile) {
//docx
$ext1 = ".docx";
$checkextensionsub = explode($ext1, $subfile);
$subsubfile = $sub . $subfile;
if (count($checkextensionsub) > 1) {
$zipsub = new ZipArchive;
$zipsub->open("$subsubfile");
$wordsub = $zipsub->getFromName('word/document.xml');
$word2sub = str_replace($find, $replace, $wordsub);
$word2sub = str_replace($find2, $replace2, $wordsub);
$word2sub = str_replace($find3, $replace3, $wordsub);
$word2sub = str_replace($find4, $replace4, $wordsub);
$zipsub->addFromString("word/document.xml", $word2sub);
$zipsub->close();
}
//folders level 2
$sub2 = $sub . $subfile;
if (is_dir($sub2)) {
$subfiles2 = scandir($sub2, 1);
if ($subfiles2 > 1) {
if ($sub2 == $sub.".." || $sub2 == $sub.".") {
}
else {
foreach($subfiles2 as $subfile2) {
//docx
$ext1 = ".docx";
$checkextensionsub2 = explode($ext1, $subfile2);
$subsubfile2 = $sub2 . '/' . $subfile2;
if (count($checkextensionsub2) > 1) {
$zipsub2 = new ZipArchive;
$zipsub2->open("$subsubfile2");
$wordsub2 = $zipsub2->getFromName('word/document.xml');
$word2sub2 = str_replace($find, $replace, $wordsub2);
$word2sub2 = str_replace($find2, $replace2, $wordsub2);
$word2sub2 = str_replace($find3, $replace3, $wordsub2);
$word2sub2 = str_replace($find4, $replace4, $wordsub2);
$zipsub2->addFromString("word/document.xml", $word2sub2);
$zipsub2->close();
}
//more directories when needed
//****replicate code here****
//add files to archive
$zip_download->addFile($subsubfile2, $subsubfile2);
}
}
}
}
//add files to archive
$zip_download->addFile($subsubfile, $subsubfile);
}
}
}
} else {
die ("Error - No files in the directory");
}
}
//add files to archive
$zip_download->addFile($file, $file);
}
$zip_download->close();
//download zip
if (file_exists($zipfile) && is_readable($zipfile)) {
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($zipfile));
header('Content-Disposition: attachment; filename="'.basename($zipfile).'";');
header('Content-Transfer-Encoding: binary');
$file_download = # fopen($zipfile, 'rb');
if ($file_download) {
fpassthru($file_download);
exit;
}
echo ("ZIP generated successfully, download is starting...");
} else {
echo ("Error creating the ZIP archive!");
}
}
?>

I think it's because Scandir() will produce something like
`Array
(
...
[9] => .
[10] => ..`
at the end of the arrayand when you check those if they are folders maybe an error occurs and dies.

Related

How to standardize the naming of photos in a folder in php?

I have a folder containing several photos all in .jpg
The name they should all have is STYLE_COLOR-n.jpg for example K14700_7132-6.jpg because I made a script that deletes all the photos greater than -6.jpg.
My problem is that I have photos that are badly renamed, i.e. they have an underscore at the end instead of the dash like :
K14700_7132_6.jpg
Some also have a dash on both like this:
K14700-7132_6.jpg
And so my delete script doesn't work if the pictures don't all have the same rename...
Is it possible to automatically replace all the dashes and underscores that are bad to have this format on all my folder STYLE_COLOR-n.jpg?
<?php
$dir = 'C:/wamp64/www/divers/photos/';
$allFiles = scandir($dir);
foreach($allFiles as $file)
{
if (!in_array($file,array(".","..")))
{
$file = $dir.$file;
$filename = basename( $file ); //KA0710_7250-1.jpg
$underscore = explode("_", $filename);
// echo $underscore[0]."<br>"; //KA0710
$endstring = end($underscore);
// echo $endstring."<br>"; //7250-1.jpg
$underscore2 = explode("-", $endstring);
// echo $underscore2[1]."<br>"; //1.jpg
if ($underscore2[1] > 6)
{
unlink("$dir$filename");
echo 'File ' . $filename . ' has been deleted'."<br>";
}
else
{
}
}
}
echo "Deleted photos !";
?>
Sure, this is the part you'll add to that code:
$parts = preg_split("/[-_]+/", $filename);
$newfilename = strtoupper($parts[0].'_'.$parts[1]).'-'.$parts[2];
if ($newfilename !== $filename) {
rename($dir.$filename, $dir.$newfilename); // test this!
$filename = $newfilename;
}
Note - this will permanently rename files (that need it) so BEFORE you run this in production, please test for the old/new rename arguments just to be safe!
Here is the whole enchilada
<?php
$dir = 'C:/wamp64/www/divers/photos/';
$allFiles = scandir($dir);
foreach($allFiles as $file) {
if (!in_array($file,array(".",".."))) {
$file = $dir.$file;
$filename = basename( $file ); //KA0710_7250-1.jpg
// first fix the format
$parts = preg_split("/[-_]+/", $filename);
$newfilename = strtoupper($parts[0].'_'.$parts[1]).'-'.$parts[2];
if ($newfilename !== $filename) {
rename($dir.$filename, $dir.$newfilename); // test this!
$filename = $newfilename;
}
$underscore = explode("_", $filename);
$endstring = end($underscore);
// echo $endstring."<br>"; //7250-1.jpg
$underscore2 = explode("-", $endstring);
// echo $underscore2[1]."<br>"; //1.jpg
if ($underscore2[1] > 6) {
unlink("$dir$filename");
echo 'File ' . $filename . ' has been deleted'."<br>";
} else {
}
}
}
echo "Deleted photos !";
?>

PHP read lines not working on some computers but works on most

So im reading an CSV file and splitting it apart to get email,name,last name, however this outputs differently on different computers in my platform, let's say when I upload the same file it reads 38 lines and save them. However in 2 specific computers it reads only 1.
Before I was reading only TEMP file, but now im saving it to a directory and reading from there, however the problem is still here, I compared the file size and is the same even the content.
Is this a PHP bug ?
<?php
global $user;
if(isset($_POST['submit'])) {
if ($_FILES['file']['tmp_name']) {
$nome = $_POST['nome'];
$file = $_FILES['file']['tmp_name'];
$user->criarLista($nome, $file);
} else {
$user->mensagem(1, "Não existe nenhum ficheiro");
}
}
?>
public function criarLista($nome,$file){
// ADDED TO SAVE THE FILE IN THE SYSTEM AND READ FROM IT
if(file_exists("uploads/lista.txt")){ unlink("uploads/lista.txt"); }
move_uploaded_file($file, "uploads/lista.txt");
$file = file_get_contents("uploads/lista.txt");
$user = $this->user;
$get = $this->connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $get->fetch_array(MYSQLI_ASSOC);
$user_id = $fetch['id'];
if($insert = $this->connect->prepare("INSERT INTO lista(user_id,nome) VALUES(?,?)")){
$insert->bind_param("is", $user_id,$nome);
$insert->execute();
$list_id = $insert->insert_id;
$file = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $file);
$file = strip_tags($file);
$lines = file("uploads/lista.txt");
$emails = array();
$fnames = array();
$lnames = array();
$linha = 0;
foreach($lines as $line) {
if($linha == 0){
}else{
echo $Linha."</br>";
if (strpos($line, ',') !== false) {
$arr = explode(",", $line);
// Email \ FNAME | LAST
$emailx = trim($arr[0]);
$emailx = trim(preg_replace("/[\\n\\r]+/", "", $emailx));
array_push($emails,$emailx);
if(isset($arr[1])){
$fname = trim($arr[1]);
$fname = str_replace('"','',$fname);
array_push($fnames,$fname);
}
if(isset($arr[2])){
$lname = trim($arr[2]);
array_push($lnames,$lname);
}
}else{
array_push($emails,trim($line));
}
}
$linha++;
}
array_map('trim', $emails);
array_map('trim', $fnames);
array_map('trim', $lnames);
$emails = implode(",",$emails);
$fnames = implode(",",$fnames);
$lnames = implode(",",$lnames);
if($insert_list = $this->connect->prepare("INSERT INTO listas(lista_id,email,primeiro_nome,ultimo_nome) VALUES(?,?,?,?)")){
$insert_list->bind_param("isss", $list_id,$emails,$fnames,$lnames);
$insert_list->execute();
$this->mensagem(2,"Lista adicionada com sucesso");
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}
FIXED this adding this on top of the function :
ini_set('auto_detect_line_endings',true);
I am not sure this is an 'answer' to what is going on, though it is what I had to do to fix an issue with a Mac user sending files.
What I found was that, every time he did an upload, it would send a .zip file, not just the file (like the PCs did). I did not have other Mac users to test against, so, again, I can't say this is exactly the issue you have, but I trust it will at least help in your search.
Note that I had to chop a lot of code out of this (where I was doing various other functions with the database, etc.), so this may not run directly, but I think I closed all the 'ifs' and such - or you can figure it out (if not, let me know and I'll go through it again).
Hope this helps!
$save_file = basename($_FILES["fileToUpload"]["name"]);
$zipfile='maps/'.$save_file; // location of a temp location (stops double uploads)
$alert_upload_file_exists = "Uploaded file exists!";
$alert_upload_successful = "UPLOAD SUCCESSFUL";
$action_failed_text = "Action FAILED";
if(file_exists($zipfile) && (empty($_GET['overwrite']) || $_GET['overwrite'] == 'false'))
die($alert_upload_file_exists);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $zipfile))
{
// I found this mac to be sending a .zip file, not a standard one..... :(
$uploadOk = 0;
$mac_file = 0;
if($basename = basename($_FILES["fileToUpload"]["name"],".zip"))
{
$zip = new ZipArchive;
if($zip->open($zipfile) === true){
// echo "basename is $basename<BR>";
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
// look for the file we really want (in our case, any sort of img file)
if($fileinfo['basename'] == $basename . '.png' || $fileinfo['basename'] == $basename . '.jpg' || $fileinfo['basename'] == $basename . '.gif') {
$imgfile = $_GET['loc_data_id'].".".$fileinfo['extension'];
$files[]=$fileinfo['basename'];
// echo "file added to the list <BR>";
}
// echo "filename is $filename, basename is ->".$fileinfo['basename']."<- fileinfo = ";print_r($fileinfo);
// CHECK TO SEE IF THIS WAS THE 'WEIRD' MAC FILE
if($fileinfo['basename'] == "__MACOSX")
$mac_file = 1;
// echo "mac_file is $mac_file ";
}
if(($imglist = array_keys(array_flip(preg_grep('/^.*\.(jpg|jpeg|png|gif)$/i',$files))))
{
// echo "imglist = ";print_r($imglist);
// echo "files = ";print_r($files);
foreach($files as $key => $value)
{
if ($imglist[0]==$value) {$file = $imgfile;}
$upgrade += file_exists('maps/'.$file);
// echo "imgfile is $imgfile, file is $file upgrade is $upgrade and value is ".$basename."/".$value." ............";
// more 'FUNNY BUSINESS' to work the Mac file....
if($mac_file){
$extracted = $zip->extractTo('maps/',$basename."/".$value);
rename("maps/$basename/$value","maps/$file");
}
else {
$extracted = $zip->extractTo('maps/',$value);
rename("maps/$value","maps/$file");
}
}
// AND A BIT MORE.....
if($mac_file){
rmdir ("maps/$basename");
}
$zip->close();
$imgcount=0;$mapcount=0;$uploadOk=1;
$html = file_get_html('maps/'.$mapfile);
$imgck = strpos($html,'<img ');
if(($imgck===false) || $imgck<>0) {
$uploadOk += 2;
}
// echo "uploadOk is $uploadOk<br>";
if($uploadOk==1)
{
$mapname = pathinfo('maps/'.$mapfile);
// echo "mapfile is $mapfile, mapname = ";print_r($mapname);
}
}
else $uploadOk += 20;
}
}
if($uploadOk==1) echo basename($_FILES["fileToUpload"]["name"])." ".$alert_upload_successful;
else echo $action_failed_text . " ".$uploadOk;
// delete the original .zip file (and any that are in the 'maps/' folder)
array_map('unlink', glob("maps/*.zip"));
}
else
{
echo "Sorry, there was an error uploading your file.";
echo "temp name is " . $_FILES["fileToUpload"]["tmp_name"]. " save file is ". $save_file."<br>";
}

Download file is getting corrupted

I have a code function in php
What it does:
it absorbs data from a table and converts the images(saved as blob) into files and put under a subfolder named "image" under a folder created dynamically based on version and date
ex: v3-20-12-2012
Then it creates a csv file and save it in the v3-20-12-2012 folder.
Then it creates a zip file for the folder v3-20-12-2012.
The problem is , the zip file getting saved in the project folder. I want it to be downloadable.
How can i achieve this.
Here's my code:
function create_csv($version,$ctg,$cnt,$nt,$api)
{
$folder = $version."-".date('d-m-Y')."-".time();
if(!file_exists('./'.$folder))
{
mkdir('./'.$folder);
mkdir('./'.$folder.'/image/');
}
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT DISTINCT $off_table.id,$off_table.name
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$columns_total = mysql_num_fields($result);
for ($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($result, $i);
$output .= '"'.$heading.'",';
}
$output .= '"icon"';
$output .="\n";
while ($row = mysql_fetch_array($result))
{
for ($i = 0; $i < $columns_total; $i++)
{
$output .='"'.$row["$i"].'",';
}
$sql_icon = "SELECT $off_table.icon FROM $off_table WHERE id = '".$row['id']."'";
$result_icon = mysql_query($sql_icon);
while($row_icon = mysql_fetch_array($result_icon))
{
$image = $row_icon["icon"];
$id = $row["id"];
$icon = "./$folder/image/{$id}.jpg";
$icon_link = "$folder/image/{$id}.jpg";
file_put_contents($icon, $image);
}
$output .= '"'.$icon_link.'"';
$output .="\n";
}
$filename = "myFile.csv";
$fd = fopen ( "./$folder/$filename", "w");
fputs($fd, $output);
fclose($fd);
$source = $folder;
$destination = $folder.'.zip';
$flag = '';
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if($flag)
{
$flag = basename($source) . '/';
}
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', realpath($file));
if (is_dir($file) === true)
{
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
$zip->close();
if (is_dir($folder))
{
$objects = scandir($folder);
foreach ($objects as $object)
{
if ($object != "." && $object != "..")
{
if (filetype($folder."/".$object) == "dir")
{
$object_inner = scandir($folder."/".$object);
foreach ($object_inner as $object_inner)
{
if ($object_inner != "." && $object_inner != "..")
{
unlink($folder."/".$object."/".$object_inner);
}
}
rmdir($folder."/".$object);
}
else
unlink($folder."/".$object);
}
}
reset($objects);
}
rmdir("./".$folder);
/*$zipfile = $folder.'.zip';
$file_name = basename($zipfile);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($zipfile));
readfile($zipfile);
exit;*/
}
EDIT:
I have two instance of the file. One file gettng saved automaticaly at the project folder. The next one is getting forced to download. The one that is automatically saved has no prolem whle unzipping. But the one that is forcefully download, that having issue while unzipping.
You forgot to send the actual data at the end and it would be nice to also send the Content-Length header.
Example:
$filename = 'something.zip';
$filepath = './path/to/files/directory/';
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename='.$filename);
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
readfile($filepath.$filename);
And as a side note, you may want to split that function because it does more than it should. As name states, it should just create_csv, but is also working with DB, creating a zip, sending the response, etc.
Update:
After your update I looked closely to your code and you have a few issues which might result in a corrupted download:
$source = str_replace('\\', '\\', realpath($source));
// more code ...
$file = realpath($file);
Those lines will result in full paths being used in archive, which you might not want. I recommend commenting those two lines so you store relative paths inside the archive.
After you add all your files to your archive, you don't close it and because the archive will have a temporary name which is different than its final one, your code used when sending headers will result in sending garbage data.
To fix that, you should close the .zip before sending the headers:
// more code ...
$zip->close();
header('Content-type: application/zip');

class.upload.php and file extension missing

I'm using class.upload.php for images. Resizing works correctly with name and extension into the folder, but i have a problem storing the name into mysql database. There's no file extension (.jpg, .gif etc)... why? how can i resolve the problem?
Thanks
/* ========== SCRIPT UPLOAD MULTI IMAGES ========== */
include('class.upload.php');
$dir_dest="../../images/gallery/";
$files = array();
foreach ($_FILES['fleImage'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded) {
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_big = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_big;
$handle->image_resize = true;
$handle->image_x = 460;
$handle->image_ratio_y = true;
// $handle->image_y = 400;
$handle->Process($dir_dest);
//Thumbnail
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_small = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_small;
$handle->image_resize = true;
$handle->image_x = 180;
$handle->image_ratio_y = true;
// $handle->image_y = 120;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
header("Location: index.php"); //echo 'image resized';
$handle->clean();
$query_img="INSERT into tbl_images (file_name, pd_image, pd_thumbnail) VALUES('$nome','$result_big', '$result_small')";
$result2 = dbQuery($query_img);
} else {
echo 'error : ' . $handle->error;
}
}
}
// END SCRIPT UPLOAD MULTI IMAGES
header("Location: index.php");
}
You are removing the extension with this code
$result_big = str_replace("." . $extension,"",$image1);
I dont know why you do that. anyway you can add it back by adding following line after the $handle->file_new_name_body = $result_big;
$handle->file_new_name_ext = $extension;
You have replaced the extention with empty string here using str_replace
$result_small = str_replace("." . $extension,"",$image1);
and here
$result_big = str_replace("." . $extension,"",$image1);
update below lines just add .$extension at the end
$handle->file_new_name_body = $result_big.$extension;
and
$handle->file_new_name_body = $result_small.$extension;
just change query like this
$query_img="INSERT into tbl_images (
file_name,
pd_image,
pd_thumbnail
) VALUES (
'$nome',
'{$result_big}.{$extension}',
'{$result_small}.{$extension}')";
I will suggest you to have same filename for pd_image and pd_thumbnail, just prefix thumb with thumb_ that will make your life easier in front end.
this way you can access any image thumbnail just by prefixing it with thumb_ with pd_image and you don't have to store pd_thumbnail in database.

php file search issue - not returning full path to file

This script will search my server for files starting by a specific string, then return the download links. Search query is defined by "f" GET value.
Now let's say that i have the following files on my server:
/folder/example file number one.zip
/folder/example file number two.zip
/folder/example file number three.zip
If i search for "example file" then the script will return 3 results BUT every download links will be "/folder/example file" instead of the FULL filename (/folder/example file number XXX.zip).
This will also create a bug with the filesize() function at the end of the script, since filesize() will look for the size of "/folder/example file" instead of using the full filename
Can you help me to fix that ?
$request = $_GET['f'];
$adr = $_SERVER['QUERY_STRING'];
$decode = rawurldecode(substr($adr, 2));
echo "Searching for $decode";
// finding the file on the server
$root = $_SERVER['DOCUMENT_ROOT'];
$search = preg_quote(utf8_decode($decode));
function rsearch($folder, $pattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
$fileList = array();
foreach ($files as $file) {
$fileList = array_merge($fileList, $file);
}
return $fileList;
}
$resultatss = rsearch($root, '/.*\/'.$search.'/');
foreach ($resultatss as $resultat) {
$downloadlink = str_replace("$root/", "", $resultat);
$pos = strrpos($downloadlink, '/') + 1;
$encodedownloadlink = substr($downloadlink, 0, $pos) . rawurlencode(substr($downloadlink, $pos));
if (!empty($downloadlink)) {
echo "download link = http://www.mydomain.com/$encodedownloadlink";
$taillekb = filesize($downloadlink) / 1024;
echo "<br>Size: $taillekb KB<br>";
} else {
echo "File not found";
}
}
I was unfamiliar with the RecursiveDirectoryIterator function, so I decided to check it out. Neat stuff! I wrote the following, it seems to do what you want:
Method #1 ...
$path = $_SERVER['DOCUMENT_ROOT'];
$search = rawurldecode($_GET['f']);
$it = new RecursiveDirectoryIterator( $path );
foreach (new RecursiveIteratorIterator($it) as $file){
$pathfile = str_replace($path,'',$file);
if (strpos($pathfile, $search) !== false) {
echo 'file = '. basename($file) .'<br>';
echo 'link = http://www.mydomain.com'. $pathfile .'<br>';
echo 'size = '. round(filesize($file)/1024,2) .' KB<br><br>';
}
}
You run it via http://www.mydomain.com/search.php?f=whatever ... assuming you name the script search.php, this will find any file containing the word whatever.
Method #2 ...
If you want to split this apart (putting the search in a function), here's how that looks:
function rsearch($path, $search) {
$files = array();
$it = new RecursiveDirectoryIterator( $path );
foreach (new RecursiveIteratorIterator($it) as $file){
if (strpos($file, $search) !== false) $files[] = $file;
}
return $files;
}
$path = $_SERVER['DOCUMENT_ROOT'];
$search = rawurldecode($_GET['f']);
$files = rsearch($path, $search);
foreach ($files as $file) {
$pathfile = str_replace($path,'',$file);
if (strpos($pathfile, $search) !== false) {
echo 'file = '. basename($file) .'<br>';
echo 'link = http://www.mydomain.com'. $pathfile .'<br>';
echo 'size = '. round(filesize($file)/1024,2) .' KB<br><br>';
}
}

Categories