How to get the filename without the extension in php? - php

I'm using the following code to display the name of a CSV file before the contents of the CSV file are displayed on a PHP page. It works well and displays the name of the file as it should:
CODE:
#$result .= '<h3>'.$prog.'</h3>'.PHP_EOL; // OLD STYLE
$result .= '<h3>'.$prog. ' '.$_POST['filename'].'</h3>'.PHP_EOL; // NEW STYLE
$result .= '</div>'.PHP_EOL;
$result .= $contents.PHP_EOL;
Problem is, I don't want the file name to display the extension (in my code example, it is .csv)
Can anyone assist in the right code needed to remove the extension (.CSV)...?

// Use this code I hope it's useful ..
=> The basename() function returns the filename
<?php
$path = "filename.CSV"; // set your file name
//Show filename with file extension
echo basename($path) ."<br/>";
//Show filename without file extension
echo basename($path,".CSV");
?>
OutPut :-
filename.CSV
filename
OR
// you also use pathinfo() function .
$file_name = pathinfo('filename');
echo $file_name['dirname'], "\n";
echo $file_name['basename'], "\n";
echo $file_name['extension'], "\n";
echo $file_name['filename'], "\n"
==> Check this Demo Link :-
https://eval.in/930790

Related

can't unlink image which is in url format

php is getting image in following format, while echoing $_POST['img']
http://localhost/uploads/images/1533033949-8.jpg
But why unlink doesn't working -
// Get src.
$img = $_POST["img"];
// Check if file exists.
if (file_exists(getcwd() . $img)) {
// Delete file.
unlink(getcwd() . $img);
echo "Deleted";
}
I tried testing directly, but doesn't work
unlink($img)
unlink works on the file system, not with HTTP URLs. And appending
#CBroe is correct
First get the base path on you live server
or manually specify the base path like below example
$base_directory = '/home/myuser/';
then unlink the file that you need to remove.
if(unlink($base_directory))
echo "File has been Deleted.";
I hope it helps.
Finally I solved storing url information as variable and php substr, strlen function.
$img=$_POST['img'];
$len = strlen("http://localhost/uploads/");
$new_path = substr($img, $len, strlen($img)-$len);
if(unlink($new_path)){
echo "Deleted";
}
else{
echo "Fail";
}

create clickable link in php

I am working with wordpress -> contact form 7 and saving the data with contact form 7 to database extension plugin.
The plugin has filters to modify data before saving into database. ([Like This Page])1
now i wanted to save the file into different folder on the server and output link to that file into the admin panel. i used the filter like this.
function cfdbFilterSaveFile($formData) {
// CHANGE THIS: CF7 form name you want to manipulate
$formName = 'DemoReport';
// CHANGE THIS: upload field name on your form
$fieldName = 'Report';
// CHANGE THIS: directory where the file will be saved permanently
$uploaddir = '/home2/username/public_html/example.com/report/wp-content/uploads/reports/';
$urlDir = 'http://example.com/report/wp-content/uploads/reports/';
if ($formData && $formName == $formData->title && isset($formData->uploaded_files[$fieldName])) {
// make a copy of data from cf7
$formCopy = clone $formData;
// breakdown parts of uploaded file, to get basename
$path = pathinfo($formCopy->uploaded_files[$fieldName]);
// directory of the new file
$newfile = $uploaddir . $path['basename'];
// check if a file with the same name exists in the directory
if (file_exists($newfile)) {
$dupname = true;
$i = 2;
while ($dupname) {
$newpath = pathinfo($newfile);
$newfile = $uploaddir . $newpath['filename'] . '-' . $i . '.' . $newpath['extension'];
if (file_exists($newfile)) {
$i++;
} else {
$dupname = false;
}
}
}
// make a copy of file to new directory
copy($formCopy->uploaded_files[$fieldName], $newfile);
// save the path to the copied file to the cfdb database
$formCopy->posted_data[$fieldName] = $newfile;
$path = pathinfo($newfile);
$filelink = '<a href=' . $urlDir . $path['basename'] . '>' . $path['basename'] . '</a>';
$formCopy->posted_data[$fieldName . '-url'] = $filelink;
// delete the original file from $formCopy
unset($formCopy->uploaded_files[$fieldName]);
return $formCopy;
}
return $formData; }
add_filter('cfdb_form_data', 'cfdbFilterSaveFile');
Now with this code the file is saved into the folder on the server as expected but i am not able to output the clickable link to the saved file in the admin panel tables. In place of clickable links the full url is there. As in the screenshot.
ScreenShot
The output is coming as full URL (as marked 1 in screenshot), while i want the url to output as a link to the file (something like 2 in screenshot). I tried to use echo() and sprintf but got php syntex error.
Thanks for the suggestions. I have found alternate way to output links. What I have to do is output the form submission data on a webpage and convert links clickable by javascript as suggested by #Ovidash ... That is a acceptable workaround for my issue. Thanks for all the suggestions.

PHPWord corrupted file?

My basic PHPWord setup is working.
This is my code:
<?php
require_once 'PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();
function getEndingNotes($writers)
{
$result = '';
// Do not show execution time for index
if (!IS_INDEX) {
$result .= date('H:i:s') . " Done writing file(s)" . EOL;
$result .= date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB" . EOL;
}
// Return
if (CLI) {
$result .= 'The results are stored in the "results" subdirectory.' . EOL;
} else {
if (!IS_INDEX) {
$types = array_values($writers);
$result .= '<p> </p>';
$result .= '<p>Results: ';
foreach ($types as $type) {
if (!is_null($type)) {
$resultFile = 'results/' . SCRIPT_FILENAME . '.' . $type;
if (file_exists($resultFile)) {
$result .= "<a href='{$resultFile}' class='btn btn-primary'>{$type}</a> ";
}
}
}
$result .= '</p>';
}
}
return $result;
}
// Template processor instance creation
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
// Variables on different parts of document
//$templateProcessor->setValue('vorname', htmlspecialchars('John')); // On section/content
//$templateProcessor->setValue('nachname', htmlspecialchars('Doe')); // On footer
//$templateProcessor->setValue('funktion', htmlspecialchars('Manager'));
// Simple table
$templateProcessor->cloneRow('rowValue', 10);
//clone our things
// Will clone everything between ${tag} and ${/tag}, the number of times. By default, 1.
$templateProcessor->cloneBlock('CLONEME', 5);
//delete things
// Everything between ${tag} and ${/tag}, will be deleted/erased.
$templateProcessor->deleteBlock('DELETEME');
// Saving the document as OOXML file...
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
ob_clean();
$templateProcessor->saveAs($temp_file);
getEndingNotes(array('Word2007' => 'docx'));
header("Content-Disposition: attachment; filename='cv.docx'");
readfile($temp_file); // or echo file_get_contents($temp_file);
unlink($temp_file); // remove temp file
?>
it works well for this Word file.
However when I change something in my word file PHPWord delivers a corupted file. It has something to do with XML Errors. My question is, how can I edit my word file and get a perfectly working file without errors?
Is there a tool to fix XML?
I'm having the same issue and this is the first response through a Google search.
I've discovered that using a "deleteBlock()" function to remove an unneeded section will do something to the template that makes it unable to be opened with MS Word / Google Docs. I'm able to open with Mac Pages just fine, but for some reason the deleteBlock() function is doing something weird with the export.
My edit was instead of using a deleteBlock(), I did:
$templateProcessor->cloneBlock('HOBBYBLOCK', 0);
("Hobbies" was just the name of the section I was avoiding on case by case exports)
Effectively removing the {} block wrappers and
Setting the internal variable / injection point to nothing.
This seemed to resolve my issue. Just a heads up for anyone in the future who finds this and needs help troubleshooting. :^}
I found an answer, while editing the word file word inserts different xml elements between words. I had to edit the file manually in an editor making sure the replace values were not seperated by tags.

PHP Input & file_get_contents

Can someone explain me why when i POST RAW Data for example "test.txt" in the below script
<?php
echo file_get_contents("php://input");
?>
it only prints the text "test.txt" instead of the file contents of that file?
Thank you
Your code reads the contents of the raw POST data and echoes it back.
Whereas what you want is this:
// retrieve the requested filename
$fileName = file_get_contents("php://input");
// echo the contents of the requested file
echo file_get_contents($fileName);
Depending on what you're trying to, you may wish to sanitize the $fileName input (not shown: too broad) and restrict access to a specific local directory:
$path = $myLocalDirectory . DIRECTORY_SEPARATOR . $fileName;
if (file_exists($path) {
echo file_get_conents($path);
}
Try like this ..
$input = "abc.txt";
echo file_get_contents($input);
It gives the content of the text file abc.txt

PHP Extract only the Filename from UNC Path

I'm trying to create an Intranet page that looks up all pdf documents in a UNC path and the returns them in a list as hyperlinks that opens in a new window. I'm nearly there however the following code displays the FULL UNC path - My question how can I display only the Filename (preferably without the .pdf extension too). I've experimented with the basename function but can't seem to get the right result.
//path to Network Share
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>$file</a><br>";
}
The links work fine it just the display text shows //myserver/adirectory/personnel/document.pdf rather than just document. Note the above code was taken from another example I found whilst researching. If there's a whole new better way then I'm open to suggestions.
echo basename($file);
http://php.net/basename
Modify your code like this:
<?
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>".basename($file)."</a><br>";
}
?>
You may try this, if basename() does not work for some reason:
$file_a = explode('/',$file);
if (trim(end($file_a)) == '')
$filename = $file_a[count($file_a)-2];
else
$filename = end($file_a);

Categories