Return JSON file listing

Lately I'm doing a lot of work and when I want to reuse some snippet from other work I can't find it. So I'm going to try to keep writing here so I will find everything easely.

This trick shows how to return a JSON source with the list of files in a directory usin CAKEPHP 1.3

The problem

I need to create a gallery of images with the files in a directory in the server. At the begining there will be some files and later they might want to add some other pictures. So I don't want to complicate the project doing database administration (CRUD operations). Just FTP uploading files and that's it.


The solution

In the server side I start by adding at the end of the config/routes.php this line:




In the controller which will manage these files I add these lines:


	var $components = array('RequestHandler');
	    function photos() {
	        if ($this->RequestHandler->ext == 'json') {
	            $thumbDirname = ROOT . DS . APP_DIR . DS . WEBROOT_DIR . DS . 'img' . DS . 'galeria' . DS . 'thumb' . DS;
	            $files = scandir($thumbDirname, 1); //Para que las últimas salgan las primeras.
	            $archives = array();
	            foreach ($files as $file) {
	                if ($file != '..' && $file != '.') {
	                    $archives[] = array(
	                        'Archive' => array(
	                            'big' => Router::url(DS . 'img' . DS . 'galeria' . DS . 'big' . DS . $file, true),
	                            'thumb' => Router::url(DS . 'img' . DS . 'galeria' . DS . 'thumb' . DS . $file, true),
	            $this->set('archives', $archives);


I have to create the file views/archives/json/photos.ctp

In my case I put the above snipped in the archives_controller.php, so that's why views/archives. And if you don't have json folder, create it.

Inside that file put this:


	<?php echo json_encode($archives); ?>


And that's it! The url http://yourdomain/archives/photos.json should return the json source with all the files of the folder specified.

Of course, this post is done quickly for me to remember how to do it and there are many things I'm not explaining so if you have any problem I will be happy to help you. Just comment!

Thanks for reading.



And few days later I had to come back to this post and I see that one step is missing:
- To create a 'json' folder inside 'views/layouts'.
- To create a 'default.ctp' file in folder above with this content:
<?php echo $content_for_layout; ?>

And that's it!

Fri, May 17th 2013, 13:50 | CakePHP


Add New Comment

Your name:
Your e-mail:
Your web page:
I would like to receive new comment notification.
Security code: