PHP: How to remove unnecessary dots in filename on file upload? - php

I have a script to upload files with PHP.
I already do some cleaning to remove ugly characters.
I would also like to to remove dots in the filename, EXCEPT for the last one, which indicates the file extension.
Anyone has an idea how I could do that.?
For example, how would you get
$filename = "water.fall_blue.sky.jpg";
$filename2 = "water.fall_blue.sky.jpeg";
to return this in both cases..?
water.fall_blue.sky

Use pathinfo() to extract the file name (the "filename" array element is available since PHP 5.2); str_replace() all the dots out of it; and re-glue the file extension.

Here's an example of how this can be done:
<?php
$string = "really.long.file.name.txt";
$lastDot = strrpos($string, ".");
$string = str_replace(".", "", substr($string, 0, $lastDot)) . substr($string, $lastDot);
?>
It converts filenames like so:
really.long.file.name.txt -> reallylongfilename.txt
Check here: example
[Edit] Updated script, dot position is cached now

FILENAME = this/is(your,file.name.JPG
$basename=basename($_FILES['Filedata']['name']);
$filename=pathinfo($basename,PATHINFO_FILENAME);
$ext=pathinfo($basename,PATHINFO_EXTENSION);
//replace all these characters with an hyphen
$repar=array(".",","," ",";","'","\\","\"","/","(",")","?");
$repairedfilename=str_replace($repar,"-",$filename);
$cleanfilename=$repairedfilename.".".strtolower($ext);
RESULT = this-is-your-file-name.jpg

Related

Removing Known Characters From End of String

I am writing an HTML file using file_put_content(), but want to be able to add additional content later by pulling the current file contents and chopping off the known ending to the html.
So something along these lines:
$close = '</body></html>';
$htmlFile = file_get_contents('someUrl');
$tmp = $htmlFile - $close;
file_put_contents('someUrl', $tmp.'New Content'.$close);
But since I can't just subtract strings, how can I remove the known string from the end of the file contents?
substr can be used to cut off a know length from the end of a string. But maybe you should determine if your string really ends with your suffix. To reach this, you can also use substr:
if (strtolower(substr($string, -strlen($suffix))) == strtolower($suffix)) {
$string = substr($string, 0, -strlen($suffix));
}
If the case not play any role, you can omit strtolower.
On the other side you can use str_replace to inject your content:
$string = str_replace('</body>', $newContent . '</body>', $string);
Maybe, Manipulate HTML from php could be also helpful.

PHP rtrim ".php"

I want to remove ".php" from the end of a string if it exists. Consider this:
$filename = 'index';
rtrim($filename,".php");//returns "index"
$filename = 'search';
rtrim($filename,".php");//returns "searc"
Why is this happening? I feel like it has something to do with ending with the letter 'h' - 'h' being in the string in rtrim. So I tried a regular expression (.php$) to see if it made a difference but it didn't.
rtrim accepts a list of characters as the second argument, so in this case, it will trim not just the .php extension, but any ., p, or h characters found in the rest of the string.
Try using preg_replace("/(.+)\.php$/", "$1", $filename); instead, or basename($filename, '.php') if you have the file on the server, not just in a string.
The second argument to rtrim is a string with a list of characters. In this case, it will strip off any P, H, and . in your string, so returning searc.
if you're simply trying to remove the extension, why not use this:
$filename = 'index.php';
$name = strstr($filename, '.', true);

Truncating a string from last till a character is encountered in PHP

I have a string with a path like so:
C:/myfolder/mysubfolder/myfile.doc
I need to truncate the string to become:
myfile.doc
Needless to say, I have a list of such paths with different lengths and different folder depths. What I need is something like trancating the rest of the string beginning from the last of the string till the first / is encountered.
How can I achieve this in PHP.
Many thanks
$path = 'C:/myfolder/mysubfolder/myfile.doc':
$filename = basename($path);
echo $filename; // "myfile.doc"
See Manual "basename()". For more detailed information about a path see pathinfo()
You can use the basename() function for this.
echo basename("C:/myfolder/mysubfolder/myfile.doc");
Output:
myfile.doc
Note that this doesn't exactly do what you described, because for these inputs:
/etc/
.
it would return
etc
.
So an (untested) alternative could be:
$fullname = "C:/myfolder/mysubfolder/myfile.doc";
$parts = explode("/", $fullname);
$filename = $parts[count($parts)-1];
echo $filename;
If you mean you want the filename segment, you can use basename()
http://php.net/manual/en/function.basename.php

How to remove %-sign in php string

i need to remove % sign from file or image name in directory
which string i use
$oldfile = "../wallpapers/temp-uploaded/".$file ;
$newfile = "../wallpapers/temp-uploaded/". trim( str_replace('%', '', $file));
rename("$oldfile","$newfile");
But its not work
reply me which string i use ( trim, str_replace not work
preg_replace how can i use for remove &%$ etc
reply back
It could be an issue with other things as your logic seems correct. Firstly
rename("$oldfile","$newfile");
should be:
rename($oldfile,$newfile);
and:
$oldfile = "../wallpapers/temp-uploaded/".$file ;
should be:
$oldfile = '../wallpapers/temp-uploaded/'.$file ;
as there is no need for the extra interpolation. Will speed things up. Source: The PHP Benchmark (See "double (") vs. single (') quotes"). And here.
In regards to the problem, you have to do some proper debugging:
Does echo "[$oldfile][$newfile]"; look as expected
Make sure the folder and oldfile exists.
Does var_dump(file_exists($oldfile),file_exists($newfile)) output true, false
Does file_get_contents($oldfile); work?
Does file_put_contents($newfile, file_get_contents($oldfile));
Make sure you have write permissions for the folder. Typically chmod 777 will do.
Before the rename, perform: if ( file_exists($newfile) ) { unlink($newfile); } as you will have to delete the newfile if it exists, as you will be moving to it. Alternatively, you could append something to the filename if you do not want to do a replace. You get the idea.
In regards to the replace question.
As you have said you would like %xx values removed, it is probably best to decode them first:
$file = trim(urldecode($file));
You could use a regular expression then:
$newfile = '../wallpapers/temp-uploaded/'.preg_replace('/[\\&\\%\\$\\s]+/', '-', $file); // replace &%$ with a -
or if you want to be more strict:
$newfile = '../wallpapers/temp-uploaded/'.preg_replace('/[^a-zA-Z0-9_\\-\\.]+/', '-', $file); // find everything which is not your standard filename character and replace it with a -
The \\ are there to escape the regex character. Perhaps they are not needed for all the characters I've escaped, but history has proven you're better safe than sorry! ;-)
$file = trim($file);
$oldfile = "../wallpapers/temp-uploaded/".$file ;
$newfile = "../wallpapers/temp-uploaded/".str_replace('%', '', $file);
rename($oldfile,$newfile);
To replace &%$ in the filename (or any string), I would use preg_replace.
$file = 'file%&&$$$name';
echo preg_replace('/[&%$]+/', '-', $file);
This will output file-name. Note that with this solution, many consecutive blacklisted characters will result in just one -. This is a feature ;-)

How to extract only part of string in PHP?

I have a following string and I want to extract image123.jpg.
..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length
image123 can be any length (newimage123456 etc) and with extension of jpg, jpeg, gif or png.
I assume I need to use preg_match, but I am not really sure and like to know how to code it or if there are any other ways or function I can use.
You can use:
if(preg_match('#".*?\/(.*?)"#',$str,$matches)) {
$filename = $matches[1];
}
Alternatively you can extract the entire path between the double quotes using preg_match and then extract the filename from the path using the function basename:
if(preg_match('#"(.*?)"#',$str,$matches)) {
$path = $matches[1]; // extract the entire path.
$filename = basename ($path); // extract file name from path.
}
What about something like this :
$str = '..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length';
$m = array();
if (preg_match('#".*?/([^\.]+\.(jpg|jpeg|gif|png))"#', $str, $m)) {
var_dump($m[1]);
}
Which, here, will give you :
string(12) "image123.jpg"
I suppose the pattern could be a bit simpler -- you could not check the extension, for instance, and accept any kind of file ; but not sure it would suit your needs.
Basically, here, the pattern :
starts with a "
takes any number of characters until a / : .*?/
then takes any number of characters that are not a . : [^\.]+
then checks for a dot : \.
then comes the extension -- one of those you decided to allow : (jpg|jpeg|gif|png)
and, finally, the end of pattern, another "
And the whole portion of the pattern that corresponds to the filename is surrounded by (), so it's captured -- returned in $m
$string = '..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length';
$data = explode('"',$string);
$basename = basename($data[1]);

Categories