Zend 2:: getting public folder path or basePath() easily in controller action

别等时光非礼了梦想. 提交于 2019-12-07 01:59:31

问题


In my application, to move a file to a specific directory i need to know public folder path in controller action. I read different this type solution but not getting easy one. I know that in view we can get easily public folder path using $this->basePath(); view helper. I exactly want this in controller action. Anybody can guide me how can i achieve that. Thanks in advance.


回答1:


index.php sets the current working dir to you application root (the folder containing composer.json, init_autoloader.php, etc.)

As long as you haven't called chdir elsewhere in your application you can call getcwd() and it'll always return the path to your app root.

Since the public folder is relative to that, you can get the path using ...

$publicDir = getcwd() . '/public';



回答2:


In your public folder edit your file named index.php add only two lines

define('BASE_PATH', realpath(dirname(__DIR__)));
define('PUBLIC_PATH', BASE_PATH.'/public');

you can use in your code like

print_r(BASE_PATH);
print_r(PUBLIC_PATH);



回答3:


You could use view helpers from within a controller in ZF2 as it shown here and here. You may try this for your case :

$renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
$url = $renderer->basePath('the_ressource_you_want_to_get_from_public_folder');

Hope this is what you're looking for !




回答4:


If you want to include a file from public folder (independence with location of index.php file): include_one ("./public/your-file.php");




回答5:


You should try this if you want the public folder:

$publicPath = $_SERVER['DOCUMENT_ROOT'];

Or try this if you want the basepath:

$basePath = dirname($_SERVER['DOCUMENT_ROOT']);


来源:https://stackoverflow.com/questions/23720913/zend-2-getting-public-folder-path-or-basepath-easily-in-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!