PHP rename deletes some of the files? - php

I have the following photos:
product-1.jpg
product-2.jpg
product-3.jpg
product-4.jpg
I have the following request (came from jQuery's sortable):
action=save&photos=photo[]=4&photo[]=2&photo[]=3&photo[]=1
I've tried this:
<?php
if($_POST) {
if($_POST['action'] == 'save') {
parse_str($_POST['photos'], $photos);
$id_new = 1;
foreach($photos['photo'] as $id) {
rename(dirname(__FILE__) . '/product-' . $id . '.jpg', dirname(__FILE__) . '/product-' . $id_new . '.jpg');
$id_new++;
}
}
}
?>
But rename deletes some of the photos.

You have photos ids 4, 3, 2, 1 and you are renaming the files in the reverse order so:
if you rename 4 to 1 then 1 is overwritten and 4 disappear
if you rename 3 to 2 then 2 is overwritten and 3 disappear
That's why you remain with less files.
As #MVG1984 suggested in a comment you can rename those files into another folder like:
$path = dirname(__FILE__);
$tmpPath = $path . '/tmp';
mkdir($tmpPath);
$id_new = 1;
foreach($photos['photo'] as $id) {
rename($path . '/product-' . $id . '.jpg', $tmpPath . '/product-' . $id_new . '.jpg');
$id_new++;
}
for ($i = 1; $i < $id_new; $i++) {
rename($tmpPath . '/product-' . $i . '.jpg', $path . '/product-' . $i . '.jpg');
}
rmdir($tmpPath);

Related

No error when creating zip, but it doesn't get created inside directory

I wrote this code to create a ZIP file of my uploaded attachment, wp application has an option to uploads pdf , those upload pdf will stored under upload directory , i got the result success with no error's but still zip is not get created inside the directory server . Here's the code:
// Code for Getting links (Path)of Attachements
$list = array();
// $count = 1;
foreach($applicants as $key=>$val) {
$cat_id =explode("-", $key);
foreach($val as $appkey=>$appval) {
// if(($appval['name'])=='Navn') {
// $names = $count . '_' . $cat_id[1] . '_' . stripslashes($appval['value']) ;
// }
if(($appval['name']) == ' (PDF)') {
$attach = stripslashes($appval['value']) ;
$list[] = $cat_id[0].'-'. $cat_id[1].'/' . $attach; // Attaching ID and Category to attachement file name
}
}
// $count++;
}
$paths = array();
foreach ($list as $list) {
$data = explode('/',$list);
$pdfpath='../../' . $data[7] . '/' . $data[8] . '/' . $data[9] . '/' . $data[10];
$name=(string)$data[0] . '_' . $data[10];
$paths[] = $pdfpath."*".$name;
}
$zip = new ZipArchive;
$rand = rand(0,5000);
// Generating random file name for zipcode
if ($zip->open($rand . 'appl_attachments.zip', ZipArchive::CREATE)) {
// add files to zip from the path i.e uplaods(Folder) if file exists
foreach ($paths as $value ) {
$path=explode("*", $value);
if(file_exists($path[0])) {
$zip->addFile($path[0],$path[1]);
}
}
$zip->close();
Finally got a fix on the issue , update the changes on the pdf path .
Here is the changes on the code :
$paths = array();
foreach ($list as $list) {
$data = explode('/',$list);
$pdfpath='../../' . $data[6] . '/'. $data[7] . '/' . $data[8] . '/' . $data[9] ;
$name=$data[9];

The 'return' keyword is not working correctly in PHP

I am using this piece of function to check if a file exists. If the file exists then I am changing its name:
function checkFileExist($fileName, $z, $ext, $folderWIthFileName){
$tmpNam = "";
if (file_exists($fileName . "_" . $z . "." . $ext)) {
$z = $z + 1;
checkFileExist($fileName, $z, $ext, $folderWIthFileName);
}
else {
$tmpNam = $fileName . "_" . $z;
echo "in else <br> " . $fileName . "_" . $z . "<br>";
}
return $tmpNam;
}
And calling this function like
$definename = checkFileExist($folderWIthFileName . "/" . $InvId, $z, $ext, $folderWIthFileName);
echo "new name is " . $definename;
But this gives me output like this:
in else
444_2015-10-27/444_3
new name is
You can see return is not working correctly. What am I doing wrong here?
You should use return checkFileExist($fileName, $z, $ext, $folderWIthFileName); in the first block to return back a value from the recursively made calls. Use this clean version:
function checkFileExist($fileName, $z, $ext, $folderWIthFileName) {
if (file_exists($fileName . "_" . $z . "." . $ext)) {
return checkFileExist($fileName, $z+1, $ext, $folderWIthFileName);
}
return $fileName . "_" . $z;
}

Creating XML code using image source from SlideshowPro Album using PHP

I used the code from this website http://wiki.slideshowpro.net/PlayerWithoutDirector/PWDSCRIPTS-PHPXMLBuilderScript with a copy of the code below called images.php with audio but I don't really need audio. This PHP script just retrieves the image source of photos in a directory of a folder to an XML file. Instead, I'd like to write an XML file that would get the image source directly from a SlideshowPro Album. The first code below lists the images from an album directly from SlideShowPro. How do I combine the two scripts?
// gallery.php
<?php
include('classes/DirectorPHP.php');
$director = new Director('api', 'key');
$album = $director->album->get(440);
echo $album->name . '<br /><br />';
// Loop through album content
$contents = $album->contents[0];
foreach($contents as $content) {
echo $content->src . '<br />';
}
?>
// images.php
<?php
/**************************************************************************
XML Generator for SlideShowPro
Brad Daily - slideshowpro.net
For instructions, see the wiki:
http://wiki.slideshowpro.net/SSPExtras/PhpXmlBuilder
This script is governed by the following license:
http://creativecommons.org/licenses/by-nc-sa/3.0/us/
**************************************************************************/
/*
CONFIGURATION
*/
// Name of the folder in each album's folder that contains the full size imagery
$large_folder = 'lg';
// Name of the folder in each album's folder that contains the thumbnails
$thumb_folder = 'tn';
// Name of your album preview image. placed at the root of each album's folder (optional)
$album_preview_name = 'albumPreview.jpg';
/* Audio addition
$audio_folder = 'audio';
*/
/*
END CONFIGURATION
(DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING)
*/
// Set up paths
define('DS', DIRECTORY_SEPARATOR);
$dir = dirname(__FILE__);
$server = 'http://' . $_SERVER['HTTP_HOST'];
$rel_path = str_replace('images.php', '', $_SERVER['PHP_SELF']);
$path = $server . $rel_path;
$iptc = is_callable('iptcparse');
/*$width = "thumbnailWidth=auto thumbnailHeight=78"; */
// Find all folders in this directory
$albums = array();
$d = dir($dir);
while (false !== ($folder = $d->read())) {
if ($folder != '.' && $folder != '..' && is_dir($dir . DS . $folder . DS . $large_folder))
{
$albums[] = $folder;
}
}
$d->close();
// Start writing XML
$o = '<?xml version="1.0" encoding="utf-8"?>' . "\n<galleries>\n";
// Cycle through albums
foreach($albums as $album) {
// Path variables
$loc_path = $path . $album . '/';
$full_path = $dir . DS . $album;
// Find images in the large folder
$images = array();
$d2 = dir($full_path . DS . $large_folder);
while (false !== ($image = $d2->read())) {
if (eregi('.jpg|.gif|.png|.swf|.flv|.mov', $image)) {
$images[] = $image;
}
}
$d2->close();
/* Audio addition
// Find audios in the audio folder
$audios = array();
$d2 = dir($full_path . DS . $audio_folder);
while (false !== ($audio = $d2->read())) {
if (eregi('.mp3|.ra|.wav', $audio)) {
$audios[] = $audio;
}
}
$d2->close();
Audio addition */
// Only write the album to XML if there are images
if (!empty($images)) {
natcasesort($images);
// Pretty up the title
$title = ucwords(preg_replace('/_|-/', ' ', $album));
// See if there is an album thumb present, if so add it in
if (file_exists($full_path . DS . $album_preview_name)) {
$atn = ' tn="' . $loc_path . $album_preview_name . '"';
} else {
$atn = '';
}
// Only write tnPath if that folder exists
if (is_dir($full_path . DS . $thumb_folder)) {
$tn = ' tnPath="' . $loc_path . $thumb_folder . '/"';
}
/* Audio addition
$audio = '';
if (0 < count($audios)) {
$audio = sprintf(' audio="%s" audioCaption="%s"',
$loc_path . $audio_folder . '/' . $audios[0],
substr(ucwords(preg_replace('/_|-/', ' ', $audios[0])), 0, -4));
}
Audio addition */
// Album tag
$o .= "\t" . '<imagegroup title="' . $title . '" thumbnailPath="' . $loc_path .
$large_folder . '/"' . $width . $atn . $audio . '>' . "\n";
// Cycle through images, adding tag for each to XML
foreach($images as $i) {
$link = $caption = '';
$title = '';
if ($iptc) {
$file = $full_path . DS . $large_folder . DS . $i;
$path_info = pathinfo($file);
$extensions = array('jpg', 'jpeg', 'gif', 'png');
if (in_array(strtolower($path_info['extension']), $extensions)) {
getimagesize($file, $info);
if (!empty($info['APP13'])) {
$iptc = iptcparse($info['APP13']);
if (isset($iptc['2#005'])) {
$title = $iptc['2#005'];
if (is_array($title)) {
$title = htmlentities($title[0], ENT_COMPAT);
}
}
if (isset($iptc['2#120'])) {
$caption = $iptc['2#120'];
if (is_array($caption)) {
$caption = htmlentities($caption[0], ENT_COMPAT);
}
}
}
}
}
if (isset($_GET['link'])) { $link = $loc_path . $large_folder . '/' . $i; }
$o .= "\t\t" . '<img src="' . $i . '" title="' . $title . '" />' . "\n";
}
// Close the album tag
$o .= "\t</imagegroup>\n";
}
}
// Close gallery tag, set header and output XML
$o .= "</galleries>";
header('Content-type: text/xml');
die($o);
I'd like my result to appear like this:
<galleries>
<imagegroup title="2013 In Review" thumbnailPath="2013Review/thumb.jpg" thumbnailWidth="auto" thumbnailHeight="78">
<img src="2013Review/JLP09509_01_026.jpg" title="Paul Walker by Jeff Lipsky"/>
<img src="2013Review/NAB10003_01_001.jpg" title="Nelson Mandela by Nabil"/>
<img src="2013Review/MMU13110_41_001.jpg" title="Lindsey Vonn by Michael Muller"/>
</imagegroup>
<imagegroup title="Awards Season" thumbnailPath="AwardSeason/thumb.jpg" thumbnailWidth="56" thumbnailHeight="78">
<img src="AwardSeason/GBE07090_04_007.jpg" title="Tom Hanks by Giuliano Bekor - "Captain Phillips""/>
<img src="AwardSeason/DTI12009_02_001.jpg" title="Amy Adams by Darren Tieste - "American Hustle" "/>
<img src="AwardSeason/NPA11013_01_005.jpg" title="Idris Elba by Nigel Parry - "Mandela-Long Walk to Freedom" "/>
</imagegroup>
</galleries>

PHP: How to create foreach loop (simple code)

I am new to PHP and have created a little code for a file upload on a form.
The code works fine but I was wondering if I could achieve the same using a foreach loop so that it could also handle more files and I dont have to write a separate line for each of them.
Can someone here help me with this and tell me how to write it properly.
My Code (working):
session_start();
$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];
$varFile1 = $_FILES["file1"]["name"];
$varExt1 = pathinfo($varFile1, PATHINFO_EXTENSION);
$varFile2 = $_FILES["file2"]["name"];
$varExt2 = pathinfo($varFile2, PATHINFO_EXTENSION);
$varFile3 = $_FILES["file3"]["name"];
$varExt3 = pathinfo($varFile3, PATHINFO_EXTENSION);
move_uploaded_file($_FILES["file1"]["tmp_name"], "uploads/" . $varUID . "_1" . "." . $varExt1);
move_uploaded_file($_FILES["file2"]["tmp_name"], "uploads/" . $varUID . "_2" . "." . $varExt2);
move_uploaded_file($_FILES["file3"]["tmp_name"], "uploads/" . $varUID . "_3" . "." . $varExt3);
echo $varUID;
Thanks for any help with this,
Tim
foreach ($_FILES as $key => $file) {
$name = $file["name"];
$ext = pathinfo($name, PATHINFO_EXTENSION);
preg_match('/(\d+)$/', $key, $match); // get 2 out of "file2"
$nr = $match[1];
move_uploaded_file($file["tmp_name"], "uploads/" . $varUID . "_" . $nr . "." . $ext);
}
$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];
$i = 1;
foreach ($_FILES as $key => $file) {
$varFile = $file[$key]["name"];
$varExt = pathinfo($varFile, PATHINFO_EXTENSION);
move_uploaded_file($file[$key]["tmp_name"], "uploads/" . $varUID . "_" . $i . "." . $varExt);
$i++;
}
echo $varUID;

[function.rename]: No error in

I do want to decrease the first part of the folders which are contained on the server when I delete a field in a database.
my folders are like : 1-Guerlain, 2-Chanel, 3-Diesel. So when the first folder is deleted I want for the other folders to be like 1-Chanel, 2-Diesel.
This is my code :
foreach (new DirectoryIterator($path) as $file)
{
if($file->isDot()) continue;
if($file->isDir())
{
$parts = explode('-', $file->getFilename());
if ($parts[0] > $_GET['id_folder']) {
$old = "./" . $parts[0] . "-" . $parts[1] . "";
$new = "./" . ($parts[0] - 1) . "-" . $parts[1] . "";
rename($old, $new);
}
}
}
But this gives me the following error : Warning: rename(./2-Chanel,./1-Chanel) [function.rename]: No error in C:\wamp\www\pcqsp-scratch\admin.php on line 196 and the folder doesn't be renamed.
How can I achieve this ? Thank you.
You need the full path for rename()
$parts = explode('-', $file->getFilename());
$path = $file->getPath();
$old = $path . DIRECTORY_SEPARATOR . $parts[0] . "-" . $parts[1] . "";
$new = $path . DIRECTORY_SEPARATOR . ($parts[0] - 1) . "-" . $parts[1] . "";
rename($old, $new);

Categories