PHP Fetch current page name without extension? - php

I want to show the current pages filename as the page title, but without the extension. And if possible, the first character should be capitalized. Is this possible?

Everyone loves one-liners:
ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME))
The second argument to pathinfo() strips the path and extension from the file name (PHP >= 5.2)
Btw, I'm using $_SERVER['PHP_SELF'] instead of __FILE__ because otherwise it would break if the code is ran from another file ;-)

Yes, you can do it, but you may want to do some extra parsing for spaces. However, this is the simplest way, and directly according to your instructions.
echo '<title>';
echo ucwords(str_replace('.php', '', __FILE__));
echo '</title>';
What I did here is to get the FILE constant which is the name of the file being executed. Find the .php extension and replace it with blank (assuming '.php' doesn't occur anywhere else in the filename).
Function ucwords() capitalizes the first letter of substrings separated by spaces.
If you want to do further parsing for spaces, you'll need to recognize the format of your file names and do string replacements/regex accordingly.

If you want to go from script.php to Script, yes:
// pathinfo give info about given file and returns it into an associative array:
$info = pathinfo( __FILE__ );
// the filename key holds file name without extension nor parent path:
$title = ucwords( $info['filename'] );

For the first letter needs to be Capitalized, use ucfirst(). That is the Uppercase First character function. You can also use ucwords() for uppercased words.
To get the filename minus the extenseion, use the pathinfo() funciton.
$path_parts = pathinfo(__FILE__);
echo ucfirst($path_parts['filename']);

Yes it's possible:
<?php
$page = basename($_SERVER['PHP_SELF']); // Get script filename without any path information
$page = str_replace( array( '.php', '.htm', '.html' ), '', $page ); // Remove extensions
$page = str_replace( array('-', '_'), ' ', $page); // Change underscores/hyphens to spaces
$page = ucwords( $page ); // uppercase first letter of every word
echo "This title is: $page";

You have 3 scripts: nav.php containerpage.php and footer.php.
In nav.php, put this:
<title><?php
if (isset($subtitle)) {echo "$subtitle";}
else {echo "some other title";}
?>
</title>
in container.php, put this:
<?php $subtitle = ucwords(str_replace('.php', '', __FILE__)); ?>
after that line include your nav.php script:
<?php include("nav.php"); ?>
This may or may not work depending on your site structure, but this is how I've solved this issue other times.

I know this question is 6 years old but, I just wanted to give another way to get the file name.
$_SERVER['SCRIPT_FILENAME']
or
$_SERVER['SCRIPT_NAME']
Check out the PHP docs on the SERVER global.

Related

PHP Regex to get second occurance from the path

I have a path "../uploads/e2c_name_icon/" and I need to extract e2c_name_icon from the path.
What I tried is using str_replace function
$msg = str_replace("../uploads/","","../uploads/e2c_name_icon/");
This result in an output "e2c_name_icon/"
$msg=str_replace("/","","e2c_name_icon/")
There is a better way to do this. I am searching alternative method to use regex expression.
Try this. Outputs: e2c_name_icon
<?php
$path = "../uploads/e2c_name_icon/";
// Outputs: 'e2c_name_icon'
echo explode('/', $path)[2];
However, this is technically the third component of the path, the ../ being the first. If you always need to get the third index, then this should work. Otherwise, you'll need to resolve the relative path first.
Use basename function provided by PHP.
$var = "../uploads/e2c_name_icon/";
echo basename( $var ); // prints e2c_name_icon
If you are strictly want to get the last part of the url after '../uploads'
Then you could use this :
$url = '../uploads/e2c_name_icon/';
$regex = '/\.\.\/uploads\/(\w+)/';
preg_match($regex, $url, $m)
print_r ($m); // $m[1] would output your url if possible
You can trim after the str_replace.
echo $msg = trim(str_replace("../uploads/","","../uploads/e2c_name_icon/"), "/");
I don't think you need to use regex for this. Simple string functions are usually faster
You could also use strrpos to find the second last /, then trim off both /.
$path = "../uploads/e2c_name_icon/";
echo $msg = trim(substr($path, strrpos($path, "/",-2)),"/");
I added -2 in strrpos to skip the last /. That means it returns the positon of the / after uploads.
So substr will return /e2c_name_icon/ and trim will remove both /.
You'd be much better off using the native PHP path functions vs trying to parse it yourself.
For example:
$path = "../uploads/e2c_name_icon/";
$msg = basename(dirname(realpath($path))); // e2c_name_icon

PHP: How to strip all types of extensions from URL (incl. period)

I am new to PHP and hope someone can help me with this.
I want PHP to give me the name of the current page of my website.
The important thing is that I need this without any leading slashes and without any trailing extensions etc., just the plain page name.
Example:
The URL of a page is http://www.myurl.com/index.php?lang=en
In this case it should only return "index".
I found a way to get rid of the leading part using the following but have trouble to remove the trailing part since this is variable (it can be just .php or .php?lang=en or .php=lang=de etc.).
$pageName = basename($_SERVER["REQUEST_URI"]);
The only thing I found is the following but this doesn't cover the variable extension part:
$pageName = basename($_SERVER["REQUEST_URI"], ".php");
Can someone tell me how to get rid of the trailing part as well ?
Many thanks in advance,
Mike
You can use parse_url in combination with pathinfo:
<?php
$input = 'http://www.myurl.com/index.php?lang=en';
$output = pathinfo(parse_url($input, PHP_URL_PATH), PATHINFO_FILENAME);
var_dump($output); // => index
demo: https://eval.in/382330
One possible way is:
$url = "http://www.myurl.com/index.php?lang=en";
preg_match('/\/([\w-_]+)\.php/i',$url,$match);
echo $match[1];
If you need help with the regex look here:
https://regex101.com/r/cM8sS3/1
here is simplest solution.
$pagename = basename($_SERVER['PHP_SELF']);
$a = explode(".",$pagename);
echo $a[0];
A tutorial on how to do it
With an .htaccess file you can:
Redirect the user to different page
Password protect a specific directory
Block users by IP Preventing hot
linking of your images
Rewrite URIs
Specify your own Error Documents
Try this
//return url
$pageName = base64_decode($_GET["return_url"]);
function Url($pageName) {
$pageName= strtolower($pageName);
$pageName= str_replace('.',' ',$pageName);
$pageName= preg_replace("/[^a-z0-9_\s-]/", "", $pageName);
$pageName= preg_replace("/[\s-]+/", " ", $pageName);
$pageName= preg_replace("/[\s_]/", "-", $pageName);
return $pageName ;
}
$cleanurl=Url($pageName);
echo $cleanurl;
This is a situation where I would just use a regular expression. Here's the code:
$pagename = basename("http://www.myurl.com/index.php?lang=en");
$pagename = preg_replace("/\..*/", "", $pagename);
You can see a working demo here: https://ideone.com/RdrHzc
The first argument is an expression that matches for a literal period followed by any number of characters. The second argument tells the function to replace the matched string with an empty string, and the last argument is the variable to operate on.

How to slice an input value? [duplicate]

This question already has answers here:
How do I get a file name from a full path with PHP?
(14 answers)
Closed 8 years ago.
My input value is just like this: Oppa/upload/default.jpeg
I want to slice the value of an input according by / cause i want to get the image file name. Does anyone know some tricks to do this?
example: i want to get default.png
<input type="text" value="Oppa/upload/default.png" id="fileLink" name="fileLink" />
Use basename():
$path = "Oppa/upload/default.jpeg";
echo basename($path); //will output "default.jpeg"
echo basename($path, '.jpeg'); //will output "default"
The first parameter is the path of which the trailing component will be removed. If the first parameter ends in the optional second parameter, the second parameter will also be cut off.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward slash
(/).
- PHP manual
You should use basename() PHP function.
This will work for you
$path = "Oppa/upload/default.jpeg";
echo basename($path);
Use pathinfo() php function
$path = "http://domain.tld/Oppa/upload/default.png";
$info = pathinfo ( $path, PATHINFO_BASENAME ); // returns default.png
Yet another solution, using preg_match()
<?php
$path = "http://domain.tld/Oppa/upload/default.png"; // or "C:\\domain.tld\Oppa\upload\default.jpg";
$pattern = '/[\/|\\\\]((?:.(?!\/|\\\\))+)$/';
if(preg_match($pattern, $path, $matches)){
echo $matches[1]; // default.png or default.jpg
}
?>
Note: People claim to have problems using basename() with asian characters
I am supposing that if your image path will not be change from Oppa/upload/ than this Should work using explode :
$str = "Oppa/upload/default.jpeg";
$s= explode("Oppa/upload/",$str);
echo $s[1];
Another Best thing you can do with defining the relative path as a constant, so :
const path = "Oppa/upload/";
$str = "Oppa/upload/default.jpeg";
$s= explode(path,$str);
echo $s[1];
will also work.

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

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

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

Categories