how find file name in a server source using php - php

i have a link.when clicking on that link a pdf file will be downloaded. am trying to save that file to a folder. with static name it getting saved,but i want to save with its actual name,is that possible? if anybody knows please help me.
sample url:- http://www.intercoat.de/index.php?option=com_jdownloads&Itemid=206&task=finish&cid=341&catid=178&lang=en
am attaching my code below. i have an array of links like above sample link
so am fetching it from an array
foreach($li as $lm)
{
$i++;
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($lm));
if($mime_type=='application/pdf')
{
echo $lm.$i.'<br>';
$filecontent = file_get_contents($lm);
file_put_contents('./uploads/myfile'.$i.'.pdf', $filecontent);
}
}
now all files not saving with its exact name,it saves as myfile1,myfile2 ..etc
cant take base name because the file name is not in url.that urls are just source of file. anybody knows please help

try this
foreach($li as $lm)
{
$i++;
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($lm));
if($mime_type=='application/pdf')
{
echo $lm.$i.'<br>';
$filecontent = file_get_contents($lm);
$actual_name = basename($lm);
file_put_contents('./uploads/'.$actual_name', $filecontent);
}
}

Related

open file on client stored on server

I want to open a server stored html report file on a client machine.
I want to bring back a list of all the saved reports in that folder (scandir).
This way the user can click on any of the crated reports to open them.
So id you click on a report to open it, you will need the location where the report can be opend from
This is my dilemma. Im not sure how to get a decent ip, port and folder location that the client can understand
Here bellow is what Ive been experimenting with.
Using this wont work obviously:
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
So I though I might try this instead.
$host= gethostname();
$ip = gethostbyname($host);
$ip = $ip.':'.$_SERVER['SERVER_PORT'];
$path = $ip."/reports/saved_reports/";
$files = scandir($path);
after the above code I loop through each file and generate a array with the name, date created and path. This is sent back to generate a list of reports in a table that the user can interact with. ( open, delete, edit)
But this fails aswell.
So im officially clueless on how to approach this.
PS. Im adding react.js as a tag, because that is my front-end and might be useful to know.
Your question may be partially answered here: https://stackoverflow.com/a/11970479/2781096
Get the file names from the specified path and hit curl or get_text() function again to save the files.
function get_text($filename) {
$fp_load = fopen("$filename", "rb");
if ( $fp_load ) {
while ( !feof($fp_load) ) {
$content .= fgets($fp_load, 8192);
}
fclose($fp_load);
return $content;
}
}
$matches = array();
// This will give you names of all the files available on the specified path.
preg_match_all("/(a href\=\")([^\?\"]*)(\")/i", get_text($ip."/reports/saved_reports/"), $matches);
foreach($matches[2] as $match) {
echo $match . '<br>';
// Again hit a cURL to download each of the reports.
}
Get list of reports:
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
$files = scandir($path);
foreach($files as $file){
if($file !== '.' && $file != '..'){
echo "<a href='show-report.php?name=".$file. "'>$file</a><br/>";
}
}
?>
and write second php file for showing html reports, which receives file name as GET param and echoes content of given html report.
show-report.php
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
if(isset($_GET['name'])){
$name = $_GET['name'];
echo file_get_contents($path.$name);
}

On creating zip file by php I get two files instead of one

I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php

Cakephp how to browse file?

my question is how to get the content of a file from a input file
becausethe only thing im getting is the name of the file not the
full path of the file.
$handle = file_get_contents($this->data['btnBrowse']);
$absolute = basename($this->data['btnBrowse']);
var_dump($handle);
var_dump($absolute);
This should work:
$file = new File($dir);
$contents = $file->read();
$file->close();

sugarCRM add document from script

I am trying to add Document to Sugar object (client) from PHP script. I have a directory of files (on the same server where sugarCRM is installed) and xls with sugar objec ID and filename). PHP Script should add correct filename to specific sugar object (identified with ID). I can read XLS this is no problem, I can also get instance of sugar object (retrieve by ID), but I have no idea how can I assign the file to sugar. I was trying with Document, and upload_file.php, but those seem to be usable with uploading single file with html Form.
How can I automate this task, copy files with correct filename to cache\upload and create Document related to my Customer from PHP Script? I would prefer not to use SOAP if it's not necesarry...
Edit:
I was able to save document and revision, but something is wrong, and file can't be downloaded from browser ("incorrect call to file")
My Code so far is:
require_once('include/upload_file.php');
$upload_file = new UploadFile('uploadfile');
$document->filename = 'robots.txt';
$document->document_name = 'robots.txt';
$document->save();
$contents = file_get_contents ($document->filename);
$revision = new DocumentRevision;
$revision->document_id = $document->id;
$revision->file = base64_encode($contents);
$revision->filename = $document->filename;
$revision->revision = 1;
$revision->doc_type = 'Sugar';
$revision->file_mime_type = 'text/plain';
$revision->save();
$document->revision_id = $revision->id;
$document->save();
$destination = clean_path($upload_file->get_upload_path($document->id));
$fp = sugar_fopen($destination, 'wb');
if( !fwrite($fp, $contents) ){
die("ERROR: can't save file to $destination");
}
fclose($fp);
WORKS! I Hope this will help someone
I have corrected 3 lines from code abowe:
//$document->revision_id = $revision->id;
//$document->save();
$destination = clean_path($upload_file->get_upload_path($revision->id));

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