I have a log method which saves to a file that is named the same as the script calling it, only with a capital first letter, which works sometimes, but other times capitalizes the second letter (I can't see any pattern as to when it does what but it's always consistent, meaning that file A will always either be initial capped or second letter capped, it's not arbitrary).
Here's my code...
function logData($str){
$filePath = $_SERVER["SCRIPT_FILENAME"];
$dir = substr($filePath, 0, strrpos($filePath, "/") + 1);
$fileName = substr($filePath,strrpos($filePath, "/")+1);
$fileName = preg_replace('/\w+$/','log',$fileName);
$fileName = ucfirst($fileName);
$fHandle = fopen( $dir.$fileName , "a");
$contents = fwrite($fHandle, $str ."\n");
fclose($fHandle);
}
Does anyone have any thoughts on what could be causing such an odd behavior *some of the time?
I know I can brute force it with a strtoupper on the first char and then append the rest of the string, but I'd really like to understand what (if anything) I'm doing wrong here.
This is probably a bug further up the code, where you calculate the $dir and $filename. If the path has a slash or not... a probably solution is .
if (strpos('/', $filePath) === false) {
$dir = '';
$fileName = $filePath;
} else {
$dir = substr($filePath, 0, strrpos($filePath, "/") + 1);
$fileName = substr($filePath,strrpos($filePath, "/")+1);
}
But echo those values out and concetrate there
You can forcefully downcase the file name before capitalizing the first letter. That is if all what you care about is capitalizing the first letter.
$fileName = ucfirst(strtolower($fileName));
On the docs for ucfirst it says (with my emphasis):
Returns a string with the first character of str capitalized, if that
character is alphabetic.
Depending on where you execute this script SCRIPT_FILENAME will return different results. Could it be possible that you execute the script from a different path, thus giving SCRIPT_FILENAME a relative path?
To test this theory, I ran the script below from some of your possible execution paths and saw possible examples include the prefix "./" and "/" which would likely not be considered as having alphabetic first characters.
<?php
error_reporting(E_ALL);
echo $_SERVER["SCRIPT_FILENAME"];
?>
Related
I'm stuck in my code.
My site's users are supposed to give me the link of a image that I will store in a variable.
How can I check what the link ends with, the extension if you will?
You can use any of these:
$ext = substr(strrchr(FILENAME, '.'), 1);
$ext = substr(FILENAME, strrpos(FILENAME, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', FILENAME);
Their performance differences are negligible (even when ran like a 500 000 times; tested with PHP 7 using phpcb)
The pathinfo() is like... really slow, compared to these, for just getting the (last) extension.
While Jefferson answer is correct; based on the problem an easier solution would be to use PATHINFO_EXTENSION.
pathinfo('/path/to/file/image.jpg', PHPINFO_EXTENSION); // returns 'jpg'
You can use the substring method "substr" to get the last couple characters after the last occuring period which you can find with "strrpos" I believe.
strrpos (See doc here) returns false if the last occurrence wasn't found and the index of the match if it is.
$mystring = 'stackoverflow.png';
$pos = strrpos($mystring,'.');
if($pos === false) { // Note the triple '='
// not found..
}else{
echo substr($mystring, $pos); // print '.png'
}
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);
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
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
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 ;-)