How to write a file using Codeigniter File Helper - php

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/";

Related

How to use JWPlayer in CodeIgniter?

So far i have tried below:
...
public function upload()
{
$jwplatform_api = new Jwplayer\JwplatformAPI('my_key', 'my_secret');
$target_file = 'upload/vids/course/bede6b9c266b876fc2f0dea7a86cf8bd.mp4';
$params = array();
$params['title'] = 'PHP API Test Upload';
$params['description'] = 'Video description here';
// Create video metadata
$create_response = json_encode($jwplatform_api->call('/videos/create', $params));
$decoded = json_decode(trim($create_response), TRUE);
$upload_link = $decoded['link'];
$upload_response = $jwplatform_api->upload($upload_link, $target_file);
print_r($upload_response);
}
...
But no luck, it says "Class 'Jwplayer\JwplatformAPI' not found".
And yeah, i have put the files I got from https://github.com/jwplayer/jwplatform-php in the ROOT position inside a folder named "jwplatform-php".
Ok since you don't want to use composer - here is a guide
1. Download as Zip
2. Create a folder
In your folder application/third_party/ create a folder called jwplatformapi/
3. Unpack the init.php and the src folder
Unpack from your zip file the init.php and the src folder into your application/third_party/jwplatformapi/ folder
it should looke like
4. Create your library
Create a file called Jwplatform_library.php in your application/libraries/ folder
class Jwplatform_library
{
private $key;
private $secret;
public function __construct($key = 'my_key', $secret = 'my_secret')
{
$this->key = $key;
$this->secret = $secret;
}
public function get()
{
require_once(APPPATH.'third_party/jwplatformapi/init.php');
return new Jwplayer\JwplatformAPI($this->key, $this->secret);
}
}
5. use it in one of your controllers
public function upload()
{
$this->load->library('Jwplatform_library', ['my_key', 'my_secret']);
$obj = $this->jwplatform_library->get();
var_dump($obj);
}

How to upload a file (Laravel)

I want to upload a file in Laravel:
I put this code in route
Route::post('upload', 'myconttest#test')->name('upload');
And put this code in controller
function test(Request $request){
$file=$request->file('myfile');
$filename=$file->getClinetOriginalName();
// $projectname;
$path='files/';
$file->move($path,$filename);
}
I create a folder in public called files. The code runs without error but the file is not saved.
Its a working code please see this
public function store(Request $request)
{
$checkval = implode(',', $request->category);
$input = $request->all();
$input['category'] = $checkval;
if ($request->hasFile('userpic')) {
$userpic = $input['pic'];
$file_path = public_path("avatars/$userpic");
if(File::exists($file_path)) {
File::delete($file_path);
}
$fileName = time().$request->userpic->getClientOriginalName();
$request->userpic->move(public_path('avatars'), $fileName);
$input['userpic'] = $fileName;
Product::create($input);
return redirect()->route('productCRUD.index')->with('success','Product created successfully');
}
}
Make sure your form is enabled to upload the file. So check that the following attribute is set or not.
<form action"" 'files' => true>
Use the following namespace
use Illuminate\Support\Facades\Input;
Then try this:
$file = Input::file('myfile');
$filename = $file->getClinetOriginalName();
move_uploaded_file($file->getPathName(), 'your_target_path/'.$filename);
I think you can try this:
First you give folder permission to files folder in public folder
function test(Request $request){
$file=$request->file('myfile');
$filename=$file->getClinetOriginalName();
$file->move(public_path().'/files/', $filename);
}
Hope this work for you !!!
In controller test function you need to given public path of files folder like
$path = public_path('files/');
for moving file on given public folder path.

Codeigniter deleting files in a directory not working

I am trying to delete pdf files from a folder. I have written the delete_files function as follows
public function delete_files($company_id)
{
$this->load->model('search_model');
$company = $this->search_model->get_company($company_id);
$username = $company[0]['username'];
$path=$this->config->base_url('/uploads/'.$username . '/' . 'uploaded');
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
}
when i did echo $path; it shows the right path where i want the files deleted but when i run the entire function nothing happens and i just get a white screen.
You need to use path to file and not resource locator.
$path = FCPATH . "uploads/$username/uploaded";
try this code
Use
$path = FCPATH . "uploads/$username/uploaded";
unset($path);

Load configuration file just once

I'm working on my script to convert legacy links to seo friendly urls.
index.php
require 'AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/router');
$urls = [
'index.php?option=com_index&task=articles&id=1',
'index.php?option=com_index&task=articles&slug=1-article-title',
'index.php?option=com_index&task=articles.category&cid=100-category1',
'index.php?option=com_shop&task=products&slug=100-amazing-product',
];
foreach($urls as $i=>$url) {
echo $router->getSefUrl($url);
}
AltoRouter.php
...
public function getSefUrl($url) {
$url_clean = str_replace('index.php?', '', $url);
parse_str($url_clean, $output);
$component = empty($output['option']) ? 'com_index' : $output['option'];
$task = empty($output['task']) ? 'index' : $output['task'];
$path = 'components/'.$component.'/routes/routes.json';
$data = json_decode(file_get_contents($path));
if (!empty($data)) {
foreach($data as $route) {
$this->map($route[0], $route[1], $route[2], $route[2]);
}
}
$route_info = $this->findUrlFromRoutes($task);
return empty($route_info) ? $url : $this->generate($route_info->task, $output);
}
...
My question: Every time when I'm using getSefUrl method I'm loading routes from external file. Is it ok? Or can I optimize code above some kind? If yes - how to?
Thanks!
You could avoid multiple fetches and decodes in your loop by breaking that out.
In AltoRouter.php
private $routes = array();
function getComponentRoutes($component)
{
if(! isset($this->routes[$component])) {
$path = 'components/'.$component.'/routes/routes.json';
$this->routes[$component] = json_decode(file_get_contents($path));
}
return $this->routes[$component];
}
You can replace that require with require_once or better use autoloading :
You may define an __autoload() function which is automatically called
in case you are trying to use a class/interface which hasn't been
defined yet. By calling this function the scripting engine is given a
last chance to load the class before PHP fails with an error.
Create a folder and put all your required classs in this folder:
function __autoload($class) {
require_once "Classes" . $class . '.php';
}

Dynamically define PHP class using a variable

I want to create a class of which I don't know the name. What is the best way to accomplish the following scenario in PHP?
$class_name = 'SomeClassName';
$code = "class {$class_name}_Control extends WP_Customize_Control {}";
eval( $code );
Thanks.
I just tested this and it works fine. And if you only need the class temporarily you can always throw an unlink() at the bottom. No exec() required.
<?php
// your dynamic classname
$fart = "poot";
// define your class, don't forget the "<?php"
$class = <<<YOYOYOHOMIE
<?php
class $fart{
public \$poop = "poop";
}
YOYOYOHOMIE;
// write the class to a file.
$filename = "dynamicClass".time().".php";
$fh = fopen($filename,"w+");
fwrite($fh, $class);
fclose($fh);
// require the file
require $filename;
// now your dynamically generated class is available
$tird = new $fart;
echo "<pre>";
var_dump($tird);

Categories