Rename files increasing as they upload - PHP - php

I need to give incresing number to files as the upload. I am usinf SFWUpload. I have this code:
mkdir("../../imagenes/".$codigo , 0777);
$i = 1;
$nombre = $codigo.'_'.$i.'.jpg';
move_uploaded_file($_FILES['Filedata']['tmp_name'], "../../imagenes/".$codigo."/".$nombre);
chmod("../../imagenes/".$codigo."/".$_FILES['Filedata']['name'], 0777);
The $codigo is the code, for example 101213, so i need the pictures to upload like 101213_1.jpg, 101213_2.jpg, 101213_3.jpg, and so on.
The problem is that SWFUpload runs the php ONCE per picture, so i can not use a foreach loop (I guess).
I need the script to check if the file exists and write the next. For example, if 101213_4.jpg exists, then write 101213_5.jpg.
Can you help me how can I do this.?? I am novice at php, and tried everything.! :(
Thanks in advance
Roberto

Here's a function I use:
function cleanup_name($name){ //accepts name and cleans it up.
$finalDir='/home/username/uploads';
# Go to all lower case for consistency
$name = strtolower($name);
//echo("Name is $name<br>");
$matches=split('\.',$name);
foreach ($matches as $key=>$value){
$exkey=$key;
$exvalue=$value; //if there is more than one period, this will find the actual extension.
//echo("Key $key|$exkey Value $value|$exvalue<br>");
}
if ($exkey<1){die('The file must have an extension.');}
$extension=".".$exvalue;
$loop=0;
while ($loop<($exkey)){
if ($loop<($exkey-1)){$matches[$loop]=".".$matches[$loop];} // this puts extra periods back into the string, but the borrowed code will replace them with underscores.
$stem.=$matches[$loop];
$loop++;
}
//echo("Stem is $stem<br>");
//echo("Extension is $extension<br>");
# Convert whitespace of any kind to single underscores
$stem = preg_replace('/\s+/', '_', $stem);
# Remove any remaining characters other than A-Z, a-z, 0-9 and _
$stem = preg_replace('/[^\w]/', '', $stem);
# Make sure the file extension has no odd characters
if (($extension != '') &&
(!preg_match('/^\.\w+$/', $extension)))
{
echo("odd characters in extension");
//die("Bad file extension");
return FALSE;
}
$safeExtensions = array(
'.zip',
'.psd',
'.pdf',
'.jpg',
'.jpeg',
'.gif',
'.rar',
'.gz',
'.ai',
'.eps',
'.bmp',
'.pub',
'.xls',
'.doc',
'.wpd',
'.rtf',
'.tiff',
'.tif',
'.pcx',
'.ttf',
'.png',
'.txt',
'.mp3',
'.avi',
'.mov',
'.wav'
);
if (!in_array($extension, $safeExtensions)) {
echo("Extension "$extension" not approved.");
//die("File extension not approved");
return FALSE;
}
# Search for a unique filename by adding a number to the
# stem (first we try without, of course)
$suffix = '';
while (file_exists($finalDir."/".$stem.$suffix.$extension)) {
if ($suffix == '') {
$suffix = '0';
} else {
$suffix++;
}
}
# Put the full name back together
$name = "$stem$suffix$extension";
return $name;
}
Pay special attention to the section with this: " while (file_exists..."

Well... you can try to get the current number of files on the folder and get $i from there:
mkdir("../../imagenes/".$codigo , 0777);
$i = count(glob("../../imagenes/".$codigo.'_*.jpg')) + 1;
$nombre = $codigo.'_'.$i.'.jpg';
move_uploaded_file($_FILES['Filedata']['tmp_name'], "../../imagenes/".$codigo."/".$nombre);
chmod("../../imagenes/".$codigo."/".$nombre, 0777);
Try that code...

Related

(edsdk / flmngr) Uploading Image has no naming convention or rules

I am using the edsdk/flmngr library for a personal php/laravel project. However, I want to add the following constraint:
When a user is uploading a file into the gallery from the CMS, the file name should be cleared of all symbols and weird characters as well as empty spaces. By default I know that it removes some of the symbols, but it definetely does not remove spaces.
e.g. Top Three Countries To Study.jpg
should be renamed to TopThreeCountriesToStudy.jpg but it does not.
Any hints on which files to change or how to accomplish this is much appreciated.
I tried editing the fixFileName method in the Utils.php class so that the name that end up being used has no spaces, but for some reason it does not seem to work.
public static function fixFileName($name) {
$newName = '';
for ($i = 0; $i < strlen($name); $i++) {
$ch = substr($name, $i, 1);
if (strpos(Utils::PROHIBITED_SYMBOLS, $ch) !== FALSE) {
$ch = '_';
}
$newName = $newName . $ch;
$newName = Str::replace(" ", "", $newName); //THIS IS THE LINE I ADDED
}
return $newName;
}

php how to have links with spaces automatically add %20 [duplicate]

This question already has answers here:
Using PHP Replace SPACES in URLS with %20
(6 answers)
Closed 8 years ago.
i have this code that is listing all my mp3 links in the directory, but the audio player won't play any files that have spaces in the file names, if i remove the spaces, it works but i was wondering if i can some how have the script add %20 when there is a space in the file name and that way the audio player i am using can pickup on it
Thanks!
heres my code
<ul id="playlist">
<?php
$dirFiles = array();
// opens images folder
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
// strips files extensions
$crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-", "error_log", ".php");
$newstring = str_replace($crap, " ", $file );
//asort($file, SORT_NUMERIC); - doesnt work :(
// hides folders, writes out ul of images and thumbnails from two folders
if ($file != "." && $file != ".." && $file != "index.php" && $file != ".DS_Store" && $file != "download.php" && $file != "error_log" && $file != "Thumbnails") {
$dirFiles[] = $file;
}
}
closedir($handle);
}
sort($dirFiles);
foreach($dirFiles as $file)
{
//echo "<li><img style=\"padding-right: 10px;vertical-align: middle;height: 60px;\" src=\"http://www.ggcc.tv/LogoNE.png\" />";
echo '<li><a href="'.$file.'">'.$file.'<br></li>';
}
?>
</ul>
try rawurlencode or other Url Functions
echo '<li><a href="'.rawurlencode($file).'">'.$file.'<br></li>';
Use str_replace to replace spaces with %20.
$fileURL = str_replace(' ', '%20', $file);
echo '<li><a href="'.$fileURL.'">'.$file.'<br></li>';
Alternatively one may modify the foreach loop as follows:
foreach($dirFiles as $file)
{
$url = join("%20",explode(' ',$file ) );
echo '<li><a href="'.$url.'">'.$file.'<br></li>';
}
The first statement encodes only spaces and assigns the result for later use by the HREF attribute of the <a> tag. rawurlencode is another option to achieve a similar result, but it may also encode more than just space characters which at times is good and other times may cause undesirable effects, such as encoding a character that is part of a domain name. str_replace is probably the sleeker solution since it requires only one function call instead of of the two shown in this snippet.
The TIMTOWDI aspect of PHP is particularly evident with this question. You may also do the following:
<?php
$from = ' ';
$to = '+';
foreach($dirFiles as $file)
{
$url = strtr( $file, $from, $to);
echo '<li><a href="'.$url.'">'.$file.'<br></li>';
}
With this solution, the replacement character for the space is the simple '+' (PHP's way of encoding spaces) and it uses strtr() which some think is faster than str_replace(). Any '+' characters will revert to spaces after the the browser automatically decodes the url.
see simple example here

get file name include_once file based on name

I have multiple files in a directory for pages.
All the pages are the same except the content I enter based on
rental inspections.
bedroom1.php
bedroom2.php
bedroom3.php
But to get them to use the right header I need them to see the
correct header based on their own filename.
bedroom1.php to include header1.php
bedroom2.php to include header2.php
bedroom3.php to include header3.php
.......
bedroom10.php to include header10.php
I can get the filename easy enough.
I'm trying to use preg_match(Maybe should use something else?)
but with not getting any errors in the logs so I'm not sure
what I'm missing and not knowing enough about file comparing
I'm lost.
EDIT: ADDED : Forgot to add, this code is in bedroom1.php etc...
Thanks in advance
<?php
$file = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
if (preg_match('/bedroom . $i .php/', $pfile, $i)) {
$number = $i[1];
foreach(array('header') as $base) {
include_once "$base$number.php";
}
}
?>
It should be:
if (preg_match('/bedroom(\d+)\.php/', $pfile, $i)) {
You need to use \d+ to match numeric digits, and put it inside parentheses to make it a capture group, so you can access it with $i[1].
Try this one:
$file = basename($_SERVER['SCRIPT_NAME'], '.php');
$base = 'header';
$parts = array();
if (preg_match('/bedroom(\d+)/', $file, $parts)) {
include_once $base . $parts[1] . '.php';
} else {
// the file doesn't follow the bedroom{number}.php structure
}
Good luck!
use this
basename($_SERVER['SCRIPT_NAME'])
you get the script name
$file = $_SERVER["SCRIPT_NAME"];
$baseName=basename($file);
$base="header";
preg_match_all('/\d+/', $baseName, $baseNameInt);
$basNameFile=$baseNameInt[0][0];
if(file_exists("$base$basNameFile.php")){
include_once("$base$basNameFile.php");
} else {
// ...
}
Not sure what your array contains that necessitates the foreach (if that is just example code) but why not just:
$array = array('header');
$suffix = str_replace($array, '', basename(__FILE__));
foreach($array as $base) {
if(file_exist("$base$suffix")) {
include_once("$base$suffix");
}
}
If the only thing that will be in the array is header then forgo the loop altogether.

Find all files in directory which matches a string exactly using PHP

Hi i have stored some file names in mongodb and i stored some files in my local directory, now my requirement is to extract the local path of the file which matches to the value in the db exactly it should not match a particular string in the file it should match with complate string. can u please suggest me how to do this.
example: sample-php-book.pdf is the db value it should match with sample-php-book.pdf file name not with sample.pdf
i have used the following code
<?php
$results = array();
$directory = $_SERVER['DOCUMENT_ROOT'].'/some/path/to/files/';
$handler = opendir($directory);
while ($file = readdir($handler)) {
if(preg_match('$doc['filename']', $file)) {
$results[] = $file;
}
}
}
?>
$doc[filename] is the value from db
Thanks
If I understand you correctly than you are looking for something like this:
Edit: I somehow forgot that split uses regex instead of a simple search. Therefore I replaced split with explode
<?php
// DB-Code here[..]
$arrayWithYourDbStrings; // <-- should conatain all strings you obtained from the db
$filesInDir = scandir('files/');
foreach($filesInDir as $file)
{
// split at slash
// $file = split('/', $file); <-- editted
$file = explode('/', $file);
// get filename without path
$file = last($file);
// check if filename is in array
if(in_array($file, $arrayWithYourDbStrings))
{
// code for match
}
else
{
// code for no match
}
}
?>

How to remove extension from string (only real extension!)

I'm looking for a small function that allows me to remove the extension from a filename.
I've found many examples by googling, but they are bad, because they just remove part of the string with "." . They use dot for limiter and just cut string.
Look at these scripts,
$from = preg_replace('/\.[^.]+$/','',$from);
or
$from=substr($from, 0, (strlen ($from)) - (strlen (strrchr($filename,'.'))));
When we add the string like this:
This.is example of somestring
It will return only "This"...
The extension can have 3 or 4 characters, so we have to check if dot is on 4 or 5 position, and then remove it.
How can it be done?
http://php.net/manual/en/function.pathinfo.php
pathinfo — Returns information about a file path
$filename = pathinfo('filename.md.txt', PATHINFO_FILENAME); // returns 'filename.md'
Try this one:
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);
So, this matches a dot followed by three or four characters which are not a dot or a space. The "3 or 4" rule should probably be relaxed, since there are plenty of file extensions which are shorter or longer.
From the manual, pathinfo:
<?php
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // Since PHP 5.2.0
?>
It doesn't have to be a complete path to operate properly. It will just as happily parse file.jpg as /path/to/my/file.jpg.
Use PHP basename()
(PHP 4, PHP 5)
var_dump(basename('test.php', '.php'));
Outputs: string(4) "test"
This is a rather easy solution and will work no matter how long the extension or how many dots or other characters are in the string.
$filename = "abc.def.jpg";
$newFileName = substr($filename, 0 , (strrpos($filename, ".")));
//$newFileName will now be abc.def
Basically this just looks for the last occurrence of . and then uses substring to retrieve all the characters up to that point.
It's similar to one of your googled examples but simpler, faster and easier than regular expressions and the other examples. Well imo anyway. Hope it helps someone.
Recommend use: pathinfo with PATHINFO_FILENAME
$filename = 'abc_123_filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);
You could use what PHP has built in to assist...
$withoutExt = pathinfo($path, PATHINFO_DIRNAME) . '/' . pathinfo($path, PATHINFO_FILENAME);
Though if you are only dealing with a filename (.somefile.jpg), you will get...
./somefile
See it on CodePad.org
Or use a regex...
$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);
See it on CodePad.org
If you don't have a path, but just a filename, this will work and be much terser...
$withoutExt = pathinfo($path, PATHINFO_FILENAME);
See it on CodePad.org
Of course, these both just look for the last period (.).
The following code works well for me, and it's pretty short. It just breaks the file up into an array delimited by dots, deletes the last element (which is hypothetically the extension), and reforms the array with the dots again.
$filebroken = explode( '.', $filename);
$extension = array_pop($filebroken);
$fileTypeless = implode('.', $filebroken);
I found many examples on the Google but there are bad because just remove part of string with "."
Actually that is absolutely the correct thing to do. Go ahead and use that.
The file extension is everything after the last dot, and there is no requirement for a file extension to be any particular number of characters. Even talking only about Windows, it already comes with file extensions that don't fit 3-4 characters, such as eg. .manifest.
There are a few ways to do it, but i think one of the quicker ways is the following
// $filename has the file name you have under the picture
$temp = explode( '.', $filename );
$ext = array_pop( $temp );
$name = implode( '.', $temp );
Another solution is this. I havent tested it, but it looks like it should work for multiple periods in a filename
$name = substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));
Also:
$info = pathinfo( $filename );
$name = $info['filename'];
$ext = $info['extension'];
// Or in PHP 5.4, i believe this should work
$name = pathinfo( $filename )[ 'filename' ];
In all of these, $name contains the filename without the extension
$image_name = "this-is.file.name.jpg";
$last_dot_index = strrpos($image_name, ".");
$without_extention = substr($image_name, 0, $last_dot_index);
Output:
this-is.file.name
As others mention, the idea of limiting extension to a certain number of characters is invalid. Going with the idea of array_pop, thinking of a delimited string as an array, this function has been useful to me...
function string_pop($string, $delimiter){
$a = explode($delimiter, $string);
array_pop($a);
return implode($delimiter, $a);
}
Usage:
$filename = "pic.of.my.house.jpeg";
$name = string_pop($filename, '.');
echo $name;
Outputs:
pic.of.my.house (note it leaves valid, non-extension "." characters alone)
In action:
http://sandbox.onlinephpfunctions.com/code/5d12a96ea548f696bd097e2986b22de7628314a0
This works when there is multiple parts to an extension and is both short and efficient:
function removeExt($path)
{
$basename = basename($path);
return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}
echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file
echo removeExt('file.tar.gz');
// file
echo removeExt('file');
// file
You can set the length of the regular expression pattern by using the {x,y} operator. {3,4} would match if the preceeding pattern occurs 3 or 4 times.
But I don't think you really need it. What will you do with a file named "This.is"?
Landed on this page for looking for the fastest way to remove the extension from a number file names from a glob() result.
So I did some very rudimentary benchmark tests and found this was the quickest method. It was less than half the time of preg_replace():
$result = substr($fileName,0,-4);
Now I know that all of the files in my glob() have a .zip extension, so I could do this.
If the file extension is unknown with an unknown length, the following method will work and is still about 20% faster that preg_replace(). That is, so long as there is an extension.
$result = substr($fileName,0,strrpos($fileName,'.'));
The basic benchmark test code and the results:
$start = microtime(true);
$loop = 10000000;
$fileName = 'a.LONG-filename_forTest.zip';
$result;
// 1.82sec preg_replace() unknown ext
//do {
// $result = preg_replace('/\\.[^.\\s]{3,4}$/','',$fileName);
//} while(--$loop);
// 1.7sec preg_replace() known ext
//do {
// $result = preg_replace('/.zip$/','',$fileName);
//} while(--$loop);
// 4.57sec! - pathinfo
//do {
// $result = pathinfo($fileName,PATHINFO_FILENAME);
//} while(--$loop);
// 2.43sec explode and implode
//do {
// $result = implode('.',explode('.',$fileName,-1));
//} while(--$loop);
// 3.74sec basename, known ext
//do {
// $result = basename($fileName,'.zip');
//} while(--$loop);
// 1.45sec strpos unknown ext
//do {
// $result = substr($fileName,0,strrpos($fileName,'.'));
//} while(--$loop);
// 0.73sec strpos - known ext length
do {
$result = substr($fileName,0,-4);
} while(--$loop);
var_dump($fileName);
var_dump($result);
echo 'Time:['.(microtime(true) - $start).']';
exit;
Use this:
strstr('filename.ext','.',true);
//result filename
Try to use this one. it will surely remove the file extension.
$filename = "image.jpg";
$e = explode(".", $filename);
foreach($e as $key=>$d)
{
if($d!=end($e)
{
$new_d[]=$d;
}
}
echo implode("-",$new_t); // result would be just the 'image'
EDIT:
The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):
$name = basename($filename, '.' . end(explode('.', $filename)));
Cheers ;)

Categories