System cannot find the path specified rename file - php

I am trying to rename a file but I get this error.
$newFile = "$surname _$firstname _$dob";
$string = str_replace(' ', '', $newFile);
rename($filename, "$string.pdf");
This code produces this error
Warning: rename(0001_D_A.pdf,Mccoy_Edward_11/22/2016.pdf): The system cannot find the path specified. (code: 3) in C:\xampp\htdocs\script.php on line 7
However if I change the code to use a normal string without a variable it will rename the file without any error.
$newFile = "$surname _$firstname _$dob";
$string = str_replace(' ', '', $newFile);
rename($filename, "helloworld");
The output from $string is -
Mccoy_Edward_11/22/2016

The / in the date are invalid for file names and are interpreted as directory separators by the function.
Use - instead to separate the date parts i.e. mm-dd-yyyy
$newFile = "{$surname}_{$firstname}_{$dob}";
$string = str_replace('/', '-', $newFile);
rename($filename, "$string.pdf");

That's because the slashes are invalid characters in a windows file name (they act as directory separators on unix-like systems). You have to replace them with something valid, e.g. underscores:
$string = str_replace('/', '_', $newFile);

Related

PHP: How to explode string

I have a variable that stores the location of a temp file:
$file = 'C:\xampp\htdocs\temp\filename.tmp';
How can I explode all this to get filename (without the path and extension)?
Thanks.
Is not the best code but if you confident that this path will be similar and just file name will be different you can use this code:
$str = 'C:\xampp\htdocs\temp\filename.tmp';
$arrayExplode = explode("\\", $str);
$file = $arrayExplode[count($arrayExplode)-1];
$filename = explode('.', $file);
$filename = $filename[0];
echo $filename;
Advice: Watch out on the path contain "n" like the first letter after the backslash. It could destroy your array.
You should use the basename function, it's meant specifically for that.

rename file name using path info extension with dot

i need new name of file name using pathinfo($url, PATHINFO_EXTENSION);
this my code
$name = "name.txt";
$f = fopen($name, 'r');
$nwname = fgets($f);
fclose($f);
$newfname = $destination_folder .$nwname. pathinfo($url, PATHINFO_EXTENSION);
output:
1 jpeg
how to make output nospace and write (.) dot before jpeg like this
output:
1.jpeg
thank
Solved in comments, here's write up.
The . is used for concatenation. So $variable.$variable puts the values of the two variables together. $variable.'.'.$variable would add a period between the 2 variables. The trim function should be used to remove leading and trailing whitespaces from a variable.
Functional demo: https://eval.in/520038
References:
http://php.net/manual/en/function.trim.php
http://php.net/manual/en/language.operators.string.php
I think you need to concatenate strings like below :
$newfname = $destination_folder .$nwname.'.'. pathinfo($url, PATHINFO_EXTENSION);

How to avoid file names with spaces and/or special characters

I have a web form to upload pictures from the users.
Then I am creating an iOS app to show the pictures loaded from the users. But the app is not loading the pictures if the file name contains spaces or special characters (like á, é, í, ó, ú, ñ, etc.), most of the users are from Spain...
This is the code I am using:
<?php if ((isset($_POST["enviado"])) && ($_POST["enviado"] == "form1")) {
$randomString = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1) . substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
echo $randomString;
$nombre_archivo = $_FILES['userfile']['name'];
move_uploaded_file($_FILES['userfile']['tmp_name'], "logos/".$randomString.$nombre_archivo);
?>
I am using the random function to avoid repeated file names.
How could I change the file name given by the user and that may contain spaces and/or special characters, in a way that can be perfectly loaded in the iOS app?
rename the file after upload. this is an answer to OP's question in comments
// get the uploaded file's temp filename
$tmp_filename = $_FILES['userfile']['tmp_name'];
// get the file's extension
$path = $_FILES['userfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
// rename the uploaded file with a timestamp, insert the destination directory and add the extension
$new_filename = 'logos/'.date('Ymdhms').'.'.$ext;
// put the renamed file in the destination directory
move_uploaded_file($tmp_filename, $new_filename);
Edit: new answer per OP's question
<?php
if((isset($_POST["enviado"])) && ($_POST["enviado"] == "form1")) {
// get the uploaded file's temp filename
$tmp_filename = $_FILES['userfile']['tmp_name'];
// get the file's extension
$path = $_FILES['userfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
// rename the uploaded with a timestamp file, add the extension and assign the directory
$new_filename = 'logos/'.date('Ymdhms').'.'.$ext;
// put the renamed file in the destination directory
move_uploaded_file($tmp_filename, $new_filename);
}
Here is what you need to do.
1) generate a unique id based filename string.
2) Rename the file with newly generated filename.
<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>
If you actually wanted to keep the user-entered string as part of the file name, you could do something like this which transliterates UTF-8 characters to their ASCII equivalent (if possible) and then removes any non ASCII and invalid characters:
function get_file_name($string) {
// Transliterate non-ascii characters to ascii
$str = trim(strtolower($string));
$str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
// Do other search and replace
$searches = array(' ', '&', '/');
$replaces = array('-', 'and', '-');
$str = str_replace($searches, $replaces, $str);
// Make sure we don't have more than one dash together because that's ugly
$str = preg_replace("/(-{2,})/", "-", $str );
// Remove all invalid characters
$str = preg_replace("/[^A-Za-z0-9-]/", "", $str );
// Done!
return $str;
}
You could try combining this together with the unique ID for the file so if two users upload a file with the same file name they don't clash.

PHP how to remove the last part of a filename after underscore

A filename looks like whatever_test_123234545.gif.
What is the easiest way to remove the last underscore followed by all characters and numbers after it but not the the dot extension.
In other words i want whatever_test_123234545.gif to look like whatever_test.gif. A filename can have a random number of underscores. I just want to remove the last part before .ext.
This will remove everything between the last underscore and the .. If the filename does't have a . or doesn't have an _ it will not change the filename:
$filename = 'whatever_test_123234545.gif';
$new_filename = preg_replace('/_[^_.]*\./', '.', $filename);
And to actually rename the file:
rename($filename, $new_filename);
The below code will replace the last _XXXXXX before the . where XXX is any number.It will replace only if XXX is a number.
$filename = 'whatever_test_56623736373738333.gif';
$new_filename = preg_replace('/_[0-9]+(\.)/', '.', $filename, 1);
$x = 'whatever_test_123234545.gif';
$newstring = substr($x, 0, strrpos($x, '_')).substr($x, strrpos($x, '.'));
This one will replace the last _XXXXXX before the . where XXX is any string.
<?php
echo preg_replace('/_[a-zA-Z0-9]+(\.)/', '.', 'whatever_test_123234545.gif', 1);
?>
// Prints: whatever_test.gif

Remove all dots in filename except the dot before the file extension

I am trying to sanitize a filename.
I would like to know of a way to remove all decimals from a files name except the last one. I need to keep the last one because the extension follows that.
EXAMPLE:
abc.def.ghij-klmnop.q234.mp3
This file should look like
abcdefghij-klmnopq234.mp3
Some extensions are longer than 3 characters.
You can use a regex with a positive lookahead. Like this:
$withdots = 'abc.def.ghij-klmnop.q234.mp3';
$nodots = preg_replace('/\.(?=.*\.)/', '', $withdots);
After executing the above, $nodots will contain abcdefghij-klmnopq234.mp3. The regular expression is basically saying match all periods that are followed by another period. So the last period won't match. We replace all matches with an empty string, and we're left with the desired result.
That should do it:
$file = 'abc.def.ghij-klmnop.q234.mp3';
$parts = pathinfo($file);
$filename = str_replace('.', '', $parts['filename']).'.'.$parts['extension'];
You could also do this, it should be faster then using pathinfo & str_replace.
$parts = explode('.', 'abc.def.ghij-klmnop.q234.mp3');
$ext = array_pop($parts);
$nodots = implode('', $parts) . '.' . $ext;
Assuming $s is the name of the file.
$s = (($i = strrpos($s, '.')) === false) ? $s :
str_replace('.','',substr($s,0,$i)).substr($s,$i);

Categories