I am trying to read a file inside CodeIgniter framework, it means in controller, My code is given below, But this doesn't work, I am a bit newbie here, can you guys guide me how to read file inside the controller?
$fp = fopen("id_rsa.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
if you have set base_url in config.php
you can load a file like this in your controller
public function load_file()
{
// you need to load the url helper to call base_url()
$this->load->helper("url");
// you can change the location of your file wherever you want
$MyFile = file_get_contents(base_url()."application/controllers/readme.txt");
var_dump($MyFile);
//etc...
}
example with json file using google api
public function load_file_via_api()
{
$json = file_get_contents('https://www.googleapis.com/youtube/v3/videos?key=AIzaSyBdiYy5i2sI5HSkLYy54xoYIXn0M8OgGoA&id=DniEWhn7fvA&part=snippet&fields=items(snippet(title))');
$obj = json_decode($json);
print '<pre>' . print_r($obj) . '</pre>';
}
read more about file_get_contents here http://php.net/manual/en/function.file-get-contents.php
hope that helps
You can try this script.. and also load the helper library
$this->load->helper('file');
$image_path = '/path/to/image/file';
$this->output->set_content_type(get_mime_by_extension($image_path));
$this->output->set_output(file_get_contents($image_path));
$fp=file_get_contents(APPPATH . 'controllers/id_rsa.pem');
You can see the content by running the function below
var_dump($fp);
Related
im having a hard time with the filesystem of Laravel. Im trying to generate, save and transfer a xml-file in a controller.
everything but the ftp-transfer works. I suspect it is because i cant get the right path of the new xml-file in the sendFilToNCS($fileName) function. Im getting this error:
ErrorException ftp_put(/storage/1584533245.xml): failed to open
stream: No such file or directory
Hope to get som help from the laravel-experts. Good day.
class ExportController extends Controller
{
public function __construct(){
$this->middleware('auth:admin');
}
public function index($id){
$foromtale = Foromtale::find($id);
$data = new NCSNote($foromtale);
$xml = View::make('xmlTemplate')->with('view', $data);
$xmlDoc = simplexml_load_string($xml);
return $this->writeXml($xmlDoc);
}
public function writeXml($content){
$fileName = time().".xml";
//$content->saveXML($fileName);
Storage::put($fileName, $content);
Storage::move($fileName, 'storage/'.$fileName);
return $this->sendFilToNCS($fileName);
}
private function sendFilToNCS($fileName)
{
$content = Storage::disk('local')->url($fileName);
$ftp_server = "ftp.host.dk";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, "username", "xXxxXX");
// upload file
if (ftp_put($ftp_conn, $fileName, $content, FTP_ASCII))
{
// close connection
ftp_close($ftp_conn);
return true;
}
// close connection
ftp_close($ftp_conn);
return false;
}
}
Storage facade without any changes will put your files in storage/app. I do not see the point in moving the files afterwards. Imaging you would put your files in storage/app/xml for easier overview. This could be obtained like this.
$fileName = '/xml/' . $fileName;
Storage::put($fileName, $content);
When you want to get the file path, the storage facade has a helper for that. Which will return the absolute path, you will need for ftp_put().
$path = Storage::path($fileName)
Seems like you are using ftp_put() wrong. The third parameter is a path to the file, use the newly defined $path property.
ftp_put($ftp_conn, $fileName, $path, FTP_ASCII)
There is a lot of aspects in this code, but this seems like the most obvious errors, I'm not certain it will get you the whole way, but should get you to the next step in the process.
I want to write a class and save it into application/models/ folder.
The code is as below:-
function writeANewFile()
{
$path = "/LMSV1/application/models/";
$classname = "firstidgenerator";
$this->load->helper('file');
$data = "<?php class ".$classname." extends CI_Model {
function generateId(\$db)
{
\$data['orders'] = 'orders';
\$this->\$db->trans_start();
\$this->\$db->insert('$classname', \$data);
\$insert_id = \$this->\$db->insert_id();
\$this->\$db->trans_complete();
return \$insert_id;
}
} ";
$result = write_file(''.$path.''.$classname.'.php', $data);
echo json_encode($result);
} //end fucntion
If i give the $path = "c:/xampp/htdocs/FrameWorks/LMSV1/application/models/"; then it successfully saves a file in desired folder.
But if if i give $path = "/LMSV1/application/models/"; then it returns false and does not create a file.
The problem lies in setting path and i could not successfully figure out what should be the path to be given as parameter?
Codeigniter has a few path constants that are useful in this case. The constant APPPATH is what you need.
$path = APPPATH . "models/";
In my controller, there are three methods:
NOTICE: I use Codeigniter v3...
public funtion index(){
$data['code'] = $this->generate_random_string();
$myfile = fopen("C:\wamp\www\write.txt", "w") or die("Unable to open file!");
fwrite($myfile, $data['code']);
fclose($myfile);
$this->load->view('path_to_view/view1', $data);
}
//$param is numeric
public funtion send($param){
$data['code'] = $this->generate_random_string();
$myfile = fopen("C:\wamp\www\write.txt", "w") or die("Unable to open file!");
fwrite($myfile, $data['code']);
fclose($myfile);
$this->load->view('path_to_view/view2', $data);
}
public function generate_random_string(){
$this->load->helper('string');
$date = new DateTime();
return random_string('sha1', 40) . $date->getTimestamp();
}
in the first and second method, I generate a random string, assign it to $data['code'] and also save it in a file (write.txt), and then load a view and echo $data['code'].
The problem is: in first method, stored $data['code'] in file and printed one in view file is the same, but in second method (send) they are different!!!
Another thing to say is: when I add below statement in second method and print value in controller (instead of view), everything will be ok:
var_dump($data['code']);
I could not understand what happened! There is not any special code to affect these, just some loading view, header, footer.
Could anyone help to find possible issues or guess what is ?
thanks.
SOLVED: I check all view file, I couldn't find related code to this issue. But, when I comment below line in header, the problem is solved!
Could anyone explain about this? just a link element cause problem!
I'm creating a application that lets a user download a file. After the download i want the file to be deleted. The end of my code is like this:
return Response::download(public_path() . '/uploads/_tmp/' . urldecode($filename));
which means that the function ends on the return an i am not able to delete the file. I have tried to call a 'after' filter on the route but then the file gets deleted to quickly.
Any ideas?
You can use deleteFileAfterSend http://laravel.com/docs/5.0/responses#other-responses
return response()->download($filePath, $fileName, $headers)->deleteFileAfterSend(true);
I personally use the following;
$response = Response::make(file_get_contents($path_to_file), $status_code, $headers);
Status code is obviously the code which you want to return.
Within the $header parameter you can pass an array with the indexes Content-Type and Content-Disposition.
Then you can simply unlink $path_to_file and return $response.
Much easier way of deleting a file would be to use Jon's answer for versions of Laravel > 4.0.
You can use deleteFileAfterSend http://laravel.com/docs/5.0/responses#other-responses
return response()->download($filePath, $fileName, $headers)->deleteFileAfterSend(true);
Simply use this line of code:
return response()->download($file_path)->deleteFileAfterSend(true);
Here, inside download function the file path will be passed as an argument. Let's say for an example you want to backup your database in a file and also want to delete with downloading:
$date = Carbon::now()->format('Y-m-d_h-i');
$pub_path = public_path();
$file_path = $pub_path . '/application/db_backups/' . $date . '.sql';
$output = shell_exec('mysqldump -h58.84.34.65 -uwsit -pwsit97480 websms > ' . $file_path);
return response()->download($file_path)->deleteFileAfterSend(true);
If you want to delete the source file after downloading, simply write it as follows
return response()->download($filePath)->deleteFileAfterSend(true);
$filename = storage_path() . '/testing.txt';
App::finish(function($request, $response) use ($filename)
{
unlink($filename);
});
return Response::download($filename);
For Laravel 5.8 use stream download. In the callback function, delete the file after echo the contents.
Let's take a look at the solution:
return response()->streamDownload(function () use ($pathToTheFile) {
echo Storage::get($pathToTheFile);
Storage::delete($pathToTheFile);
}, 'my-awesome-file-name');
I don't know if it works for the oldest or the latest versions.
unlink('./path/filename.extension');
I am using dompdf to create a pdf file out of an html file that gets created on-the-fly for the sole purpose of it serving as input for the pdf generator, however I am having trouble doing this, I implemented the code in this thread and everything works fine (I could output a simple pdf) however when I try to give it a more specific url I get this error:
An Error Was Encountered Unable to
load the requested file
here's the code that has the problem:
function printPDF(){
//write_file() usa un helper (file)
$this->load->library('table');
$this->load->plugin('to_pdf');
// page info here, db calls, etc.
$query = $this->db->get('producto');
$data['table'] = $this->table->generate($query);
$path_url = base_url().'print/existencias.html';
write_file($path_url, $data['table']);
$html = $this->load->view($path_url, 'consulta', true);
pdf_create($html, 'consulta');
}
Not sure about the exact problem, but please check this:
1) as stated in CI's manual, load->view's second parameter should be an associative array or an objet, translated to vars via extract. That may generate some problem generating $html.
2) try making $path_url relative to application/views directory, as read in CI's manual.
you should use tcpdf to create a pdf.
//create controller for example :
public function create_pdf()
{
$this->load->library("Pdf");
$data['results'] = // your data
$this->load->view('pdfview',$data);
}
//pdfview is the page having tcpdf code and your pdf code.
You can try it like this
public function export_pdf() {
$filename = 'FILENAME.pdf';
header("Content-Description: Advertise Report");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/pdf; ");
$file = fopen('php://output', 'w');
$header = array("Question", "Answer", "Name", "Email", "Phone", "Date");
fputpdf($file, $header);
fputpdf($file, 'YOUR DATA');
fclose($file);
exit;
}