Mass file renaming using php
Ok so i had this problem where i had a whole bunch of directories containing images ( .gif ) However the creator of these images thought it would be a great idea to name all the .png .gif as well. So i had about 1800 files all up with about 900 that were really gifs and 900 really pngs. Why on earth they were all renamed .gif i shall never know. So i needed to batch process these in Photoshop however photoshop wouldn’t open up the pngs named .gif unless they were correctly named .png (fair enough). S i wasn’t in the mood for sifting through 1800 and naming them correctly. Thankfully php was able to determine the difference in the files and i was able to recursively loop through the directly and rename them correctly whether they were a .gif or .png. Below is the code i used to accomplish this task in case it helps anyone.
Thankfully i could modify a pre exisitnig function to quickly accomplish this so thankyou to lixlpixel.org for making my life a little easier.
By adding a little bit of code the function below i was able to complete my task.
//get some info about the image</pre>
list($width, $height, $type, $attr) = getimagesize($path);
//if the type of image is 3 (png) and not 1 (gif) replace the .gif extension with a .png one
if($type==3){
$path2 = str_replace("png","gif",$path);
rename($path,$path2);
}
Full function modified
//run the function
scan_directory_recursively($_SERVER['DOCUMENT_ROOT']."/pathtofolder/");
// ------------ lixlpixel recursive PHP functions -------------
// scan_directory_recursively( directory to scan, filter )
// expects path to directory and optional an extension to filter
// of course PHP has to have the permissions to read the directory
// you specify and all files and folders inside this directory
// ------------------------------------------------------------
// to use this function to get all files and directories in an array, write:
// $filestructure = scan_directory_recursively('path/to/directory');
// to use this function to scan a directory and filter the results, write:
// $fileselection = scan_directory_recursively('directory', 'extension');
function scan_directory_recursively($directory, $filter=FALSE)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}elseif(is_readable($directory))
{
// we open the directory
$directory_list = opendir($directory);
// and scan through the items inside
while (FALSE !== ($file = readdir($directory_list)))
{
// if the filepointer is not the current directory
// or the parent directory
if($file != '.' && $file != '..')
{
// we build the new path to scan
$path = $directory.'/'.$file;
// if the path is readable
if(is_readable($path))
{
// we split the new path by directories
$subdirectories = explode('/',$path);
// if the new path is a directory
if(is_dir($path))
{
// add the directory details to the file list
$directory_tree[] = array(
'path' => $path,
'name' => end($subdirectories),
'kind' => 'directory',
// we scan the new path by calling this function
'content' => scan_directory_recursively($path, $filter));
// if the new path is a file
}elseif(is_file($path))
{
// get the file extension by taking everything after the last dot
$extension = end(explode('.',end($subdirectories)));
// if there is no filter set or the filter is set and matches
if($filter === FALSE || $filter == $extension)
{
/*-- Added blindmotion.com --*/
list($width, $height, $type, $attr) = getimagesize($path);
if($type==3){
$path2 = str_replace("png","gif",$path);
rename($path,$path2);
}
/*-- END Added blindmotion.com --*/
// add the file details to the file list
$directory_tree[] = array(
'path' => $path,
'name' => end($subdirectories),
'extension' => $type,
'kind' => 'file');
}
}
}
}
}
// close the directory
closedir($directory_list);
// return file list
return $directory_tree;
// if the path is not readable ...
}else{
// ... we return false
return FALSE;
}
}
// ------------------------------------------------------------
mac os x ftp Transmit 4 now here !
So it has been a while since the kind folks over at panic have released a new version of there wonderful FTP App Transmit. However its here and does not disappoint. Although i would have love to of seen a disconnect button but im sure ill be using the shortcut command+E in no time. So here the link go check it out By far the best FTP available on mac and runs happily along side my favorite editor CODA.
Below are a list of the NEW features for transmit 4
- Engine
- Transmit Twin-Turbo Engine
- Up to 25x faster for small files
- Multi-Connection Transfers
- For faster batch transfers
- Integrated Transfers View
- FXP Support
- For direct server-to-server xfer
- Bandwidth Limiting
- Interface
- Completely Reimagined
- Cleaner, cooler, cake-ier.
- Tear-Off Tabs
- Twin Progress Bar
- See current and overall progress
- Local-Local / Remote-Remote
- Cover Flow
- Image Thumbnail View
- Disclosable List View
- Quick Look
- Custom Favorites Icons
- Labels
- One / Two Pane Switcher
- Just one view if you want
- Extra-Compact Minimum Size
- Sync
- Friendly File Sync
- A nice, plain-English bubble talks you through the sync.
- Compare via File Size
- Navigation
- Path Bar Pro
- Places Pop-Up
- Jump to your most-used folders
- Improved Folder Linking
- Navigate both sides at once
- Multi-Touch Navigation
- 3-finger swipe, back or forward
- Show Folders Above Files
- Transfers
- Advanced File Skipping
- Skipping files is not just for sync anymore: set rules for anytime.
- More Flexible Default Permissions
- Advanced Server Preferences
- Hard-core options now exposed
- Continue on Errors
- Easily Repeat Transfers
- Right-click a transfer to re-do it
- Amazon S3
- CloudFront Support
- Deploy your files via CDN
- Bucket Logging
- SSH
- Send SSH Command
- Zip, UnZip, etc.
- One-Click SFTP Key Import
- Instead of a password, use key
- View Secure Certificates
- Misc
- Overhauled AppleScript
- Automatic Unicode Detection
- Better Transcript Logging
- Instant-Favorite Button
- Line Numbering in Built-In Editor
- Extensive Favorite Importers
- Simplified External Editing
- Auto-Updating via Sparkle
- Fully 64-Bit
- (Except Transmit Disk, for now.)
- Improved Copy URL / Copy Path
Easy Slider 1.7 has arrived !
so i posted it on here before easy slider is definitely my favorite jquery content/image slider and now has some great built in features like continuous sliding (looping back to the start) and numerical slide tabs. These two features have been greatly missed in previous versions and now is a complete package ready to use for any development.
ie8 – a link not clickable without text
So i noticed with ie8 only you cannot just simply set a height width and background image for an a tag with a hover and expect it work. however thanks to some research i found on this site that by simply adding “position:relative;” to the a tag sanity is regained.
eg. simple a:link background position move on hover working in ie8
a{
position:relative;
width:95px;
height:42px;
text-decoration: none;
display: block;
overflow: hidden;
background: white url(/images/button.gif) no-repeat top left;
}
a:hover{
background-position: 0px -42px;
}
AJAX FANCY CAPTCHA – not showing the draggable icon
So i stumbled accross ajax fancy captcha a while ago and thought it was a great idea. However when i uploaded the standard build to my server i found that the icon that it had asked me to drag was the only one that didn’t display. After some tinkering i believe this was due to the way php is set up on my server. So no doubt other people may find the same issue. Here is what it looked like with the standard install. And here is it with my modifications. the modifications i have made are to captcha.php file as shown below. I have not made any improvements to this file just made it workable on my server. (php5)
Hope this may help someone out.
<?php
/*
captcha.php
jQuery Fancy Captcha
www.webdesignbeach.com
Created by Web Design Beach.
Copyright 2009 Web Design Beach. All rights reserved.
*/
session_start(); /* starts session to save generated random number */
/* this compare captcha's number from POST and SESSION */
if(isset($_POST['captcha']) && $_POST['captcha'] == $_SESSION['captcha']){
echo "Passed!"; /* YOUR CODE GOES HERE */
unset($_SESSION['captcha']); /* this line makes session free, we recommend you to keep it */
}else{
/* in case that form isn't submitted this file will create a random number and save it in session */
//echo "Failed!";
$rand = rand(0,4);
$_SESSION['captcha'] = $rand;
echo $rand;
}
?>
jquery nested dropdown list menu
ok so i really needed a basic accordion style menu to convert my ul list navigation into something a little more exciting. After testing a few of the available options i found tat they were all just trying to do too much for what i actually wanted. Mainly i didnt want to define every single time i wanted a sub-menu, i needed a one glove fits all solution that would just pick up my sub menus on the fly. I couldn’t really find what i was chasing but i knew the solution was pretty simple. So here is what i came up with.
the jquery
including jquery and setting up the ul navigation
<script language="javascript" src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#p-list a.cat").next().hide();
$("#p-list a.cat").click(function() { $(this).next().slideToggle(); });
})
</script>
the very simple ul list
<div id="p-list"> <ul> <li><a href="#" class="cat">category 1</a> <ul> <li>sub link</li> <li><a href="#" class="cat">sub category 1</a> <ul> <li>sub link</li> <li>sub link</li> <li>sub link</li> </ul> </li> <li>sub link</li> <li>sub link</li> <li>sub link</li> </ul> </li> <li><a href="#">Not a category</a></li> <li><a href="#" class="cat">category 2</a> <ul> <li>sub link</li> <li>sub link</li> <li>sub link</li> </ul> </li> </ul> </div>
Demos
i have also included two demos bare bones and Styled
i have also included in the styled example the jquery line
$(‘#p-list li:last-child’).addClass(‘end’);
this basically applies the class “end” to the last ui element to allow u the cap of the last category etc. You could obviously do alot like indenting each level etc but i thought i would leave that up to you.
hope you like.
Example uploadify using forms
Ok so here is the complete sample code for using forms with uploadify. Firstly it would be good for you to have the basic demo working and your will have to change the links to the js css and upload.php to suit your paths. in the example upload.php i am basically showing you how to return errors and the full list of get variables posted from the form. You will obviously need to include the right upload.php found on the uploadify web site. you can then just use $_GET['input_name'] to action any of your form fields.
form.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<script type="text/javascript" src="uploadify/jquery-1.3.2.min.js"></script>
<link rel="stylesheet" href="uploadify/uploadify.css" type="text/css" />
<script type="text/javascript" src="uploadify/jquery.uploadify.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#fileUpload").fileUpload({
'uploader': 'uploadify/uploader.swf',
'cancelImg': 'uploadify/cancel.png',
'script': 'upload.php',
'folder': 'files',
'multi': true,
'buttonText': 'Select Files',
'checkScript': 'uploadify/check.php',
'displayData': 'speed',
'simUploadLimit': 1,
'onComplete': function(a, b, c, d, e){ alert(d);},
'onAllComplete': function(event,data){
//something here
}
});
});
</script>
<script type="text/javascript">
function startUpload(id){
var queryString = '&' + $('#new_doc_upload').serialize();
$('#fileUpload').fileUploadSettings('scriptData',queryString);
$('#fileUpload').fileUploadStart();
}
</script>
</head>
<body>
<form id="new_doc_upload" method="get">
<div id="fileUpload">You have a problem with your javascript</div>
<a href="javascript:startUpload('fileUpload')">Start Upload</a> | <a href="javascript:$('#fileUpload').fileUploadClearQueue()">Clear Queue</a>
<p></p>
Your name <input type="text" name="yourname" /><br />
Your comment <textarea name="yourcomment"></textarea>
</form>
</body>
</html>
upload.php
<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
print_r($_GET);
switch ($_FILES['Filedata']['error'])
{
case 0:
//$msg = "No Error (" . print_r($_GET) .")"; // comment this out if you don't want a message to appear on success.
break;
case 1:
$msg = "The file is bigger than this PHP installation allows";
break;
case 2:
$msg = "The file is bigger than this form allows";
break;
case 3:
$msg = "Only part of the file was uploaded";
break;
case 4:
$msg = "No file was uploaded";
break;
case 6:
$msg = "Missing a temporary folder";
break;
case 7:
$msg = "Failed to write file to disk";
break;
case 8:
$msg = "File upload stopped by extension";
break;
default:
$msg = "unknown error ".$_FILES['Filedata']['error'];
break;
}
If ($msg)
$stringData = "Error: ".$_FILES['Filedata']['error']." Error Info: ".$msg;
else
$stringData = "1"; // This is required for onComplete to fire on Mac OSX
echo $stringData;
}
//echo "1";
?>
Google analytics API oh my !
Probably one fo the most anticipated api releases has finally come about from google. Yes the Google Analytics API Fun times ahead ! The API will let developers use the google analytics data on their site in any way they see fit.
Posting forms with uploadify
Here is a nice little way of being able to submit any form data you want with uploadify without having to specify all the inputs.
Step 1
First thing you need is the basic demo going.
Step 2
Create a new function that will act as our new upload function. And replace “#new_doc_upload” with the id of the form with all the input you wish the send to the upload script.
<script type="text/javascript">
function startUpload(id){
var queryString = '&' + $('#new_doc_upload').serialize();
$('#'+id).fileUploadSettings('scriptData',queryString);
$('#'+id).fileUploadStart();
}
</script>
Step 3
Replace your start upload link with a link to the new function we made in step 3. In this case we pass our function the our upload id ‘fileUpload’ (You will need to change this to your own).
eg.
<a href="javascript:startUpload('fileUpload')">Start Upload</a>
And hey presto you should now be able to access all your form items using GET in you specified upload script.
decode a serialized string in PHP plus jQuery Sortables example
Here is a great tip for decoding a serialized string in PHP. Particularly handy when using sortables in jQuery.
This code simply shows you how to make a sortable ul list and process the new order without the leaving the page using ajax and php. The process page is generally where you may do some kind of database modification to save the state of the newly ordered list.
Lets say you had a ul list with the id #sortable
and a bunch of li inside that prefixed with doc_
eg
<ul id="sortable"> <li id="doc_23">Documnet id is 23</li> <li id="doc_24">Documnet id is 24</li> <li id="doc_25">Documnet id is 25</li> </ul>
and the jQuery
<script type="text/javascript">
$(function() {
$("#sortable").sortable({
update: function(event, ui) {
var result = $('#sortable').sortable('serialize');
$.get("process.php", { 'list': result} ,
function(data){
alert(data);
});
}
});
$("#sortable").disableSelection();
});
</script>
then our process.php would contain something like
$list = $_GET['list']; parse_str($list); print_r($doc);
this will convert our li ids to a nice array in the new sort order. From here u could implode it to a nice string or just loop thru the array.
