<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bagesh Singh&#039;s Blog &#187; php</title>
	<atom:link href="http://www.bageshsingh.com/bagesh-blog/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bageshsingh.com/bagesh-blog</link>
	<description>Shortest Distance to  Web Solutions &#38; Software Solutions</description>
	<lastBuildDate>Wed, 22 Feb 2012 18:42:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>How to Build Web Apps Faster in cakephp?</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-web-apps-faster-in-cakephp/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-web-apps-faster-in-cakephp/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 22:21:49 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[cakephp interview question]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[PHP Third Party Tools]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1637</guid>
		<description><![CDATA[The pressure is on. You’ve got limited time, and you need a system to catalogue your extensive movie collection in 15 minutes. Who ya gonna call? CakePHP of course! CakePHP is a rapid application development framework that covers all the common tasks required to get a web application up and running. Handling all the repetitive [...]]]></description>
			<content:encoded><![CDATA[<p>The pressure is on. You’ve got limited time, and you need a system to catalogue your extensive movie collection in 15 minutes. Who ya gonna call? CakePHP of course! CakePHP is a rapid application development framework that covers all the common tasks required to get a web application up and running. Handling all the repetitive tasks means you have more time for coffee, games, or whatever else you’d rather be doing. This introductory article will guide you through the creation of a media library application to record what movies you have.</p>
<p>&nbsp;</p>
<div></div>
<div><img src="http://www.tuxradar.com/files/cakephp/cakephp_01_1.jpg" alt="The CakePHP welcome page gives little clues as to the power that it provides - you need to get stuck in." />The CakePHP welcome page gives little clues as to the power that it provides &#8211; you need to get stuck in.</p>
</div>
<p>CakePHP requires very little to get up and going. You will need a web server, such as Apache, PHP 4+ (preferably 5+), MySQL 4+ and an editor of your choice. At the time of writing the latest release of CakePHP is v1.3.8.</p>
<p>You can download the latest from http://github.com/cakephp/cakephp/downloads as a compressed release, or use Git to clone the repository: http://github.com/cakephp/cakephp. Once downloaded or cloned, place the contents of the cakephp package into your document root. Once completed, you should have a docroot /directory containing the folders /app, /cake, /plugins and /vendors and the files .htaccess, index.php and README.</p>
<h2>Set up the database</h2>
<p>The next step is to set up a database. We’re using MySQL, as it’s the most common of the free database engines available, so go ahead and do:le for the movie application:</p>
<pre>CREATE DATABASE linux_format_tutorial;
CREATE TABLE `movies` (
  `id` CHAR(36) NOT NULL PRIMARY KEY,
  `title` VARCHAR(255),
  `genre` VARCHAR(45),
  `rating` VARCHAR(45),
  `format` VARCHAR(45),
  `length` VARCHAR(45),
  `created` DATETIME,
  `modified` DATETIME
);</pre>
<p>Sure, it’s a simple table, but it’s all we need to get the basic information stored and a working application as a result.</p>
<p>Note we’ve used a CHAR(36) field for the ID of each record in the database. CakePHP identifies this, and when storing new records it generates and stores a UUID rather than a numeric ID. This is a handy habit to get into, as it makes it easier to merge data from various databases later. This is one of the convention-based approaches of CakePHP in its ‘Convention over Configuration’ approach to application development.</p>
<div>
<h2>Fix those permissions</h2>
<p>CakePHP writes cache files and other goodies into the /app/tmp directory to speed things up. You need to ensure that the user running your web server has write access to that directory. The quickest way to achieve this is to allow all writing, with: chmod -R 777 app/tmp</p></div>
<p>Another example of this approach can be seen in the created and modified fields in the table. You don’t need to implement any of your own code to enable created to be populated with the correct date and time for each record when it is created, nor do you need to implement any code for the modified field. CakePHP jumps into action and takes care of this for you, making your application remarkably quick and easy to build.</p>
<p>Because we’re using the field name title for the movie title, which matches one of the default column names for CakePHP record-name identifiers, we see more magic as CakePHP automatically uses this field to display the name for records in lists etc. Create the table before moving on to the next step.</p>
<h2>Set up the database connection</h2>
<p>Getting the database configured in CakePHP is easy. There’s a sample database configuration ready for you at /app/config/database.php.default. The quickest way to get going is to create a copy of this file at /app/config/database.php. Edit the file copy you have created to contain credentials that match your database connection. For this application, you just need to configure the $default connection. It should look similar to the following:</p>
<pre>var $default = array(
	‘driver’ =&gt; ‘mysql’,
	‘persistent’ =&gt; ‘false’,
	‘host’ =&gt; ‘localhost’,
	‘port’ =&gt; ‘’,
	‘login’ =&gt; ‘username’,
	‘password’ =&gt; ‘password’,
	‘database’ =&gt; ‘linux_format_tutorial’,
	‘schema’ =&gt; ‘’,
	‘prefix’ =&gt; ‘’,
	‘encoding’ =&gt; ‘’
);</pre>
<p>You can now load the CakePHP welcome page by browsing to the location you set up on your server. You will notice a number of green bars indicating the successful setup of CakePHP. If you have any configuration issues, these green bars will appear in yellow, and will provide a detailed error message to help you solve the problem. For the purposes of this application, you an ignore any information about the Security Salt, or Cipher Key warnings on the CakePHP welcome page, as they are not required for this application.</p>
<p>Let’s start coding in earnest by creating MoviesController in /app/controllers/movies_controller.php.</p>
<pre>class MoviesController extends AppController {
	public $components = array(‘Session’);
}</pre>
<p>We have included a Session component here to handle error messages from page to page.</p>
<p>One by one we’ll create actions that will be available to users browsing your movie database. Actions are publicly accessible functions on a controller. For all the operations we want to perform on a movie in our movie database, we’ll create the CRUD actions on the Movies controller. CRUD is an acronym for: Create, Read, Update and Delete. Our actions will be named: index, add, edit, view and delete.</p>
<p>Let’s start with the index action, which will list all the movies in the database. The controller has an instance object called Movie, which is a model. It’s automatically included by CakePHP to match the controller name. We can call find() on this model and CakePHP converts those calls into database queries, meaning we don’t have to write a single line of SQL to retrieve data. Awesome! Below we call the find() method with the type all, and make the result available for the view to display.</p>
<pre>class MoviesController extends AppController {
	public $components = array(‘Session’);
	public function index() {
		$movies = $this-&gt;Movie-&gt;find(‘all’);
		$this-&gt;set(‘movies’, $movies);
	}
}</pre>
<p>That’s all we need for the index action. I know it looks simple, but that’s the beauty of CakePHP – there’s no point overcomplicating things.</p>
<div>
<h2>Search-engine friendly URLs</h2>
<p>CakePHP includes .htaccess files that work with mod_rewrite on Apache web servers to rewrite URLs effectively for you. These nicer URLs are not entirely necessary, but they do make your addresses easier to remember when available: URLs such as http://mysite.com/movies/add look better than http://mysite.com?url=movies/add. Install mod_rewrite for Apache if you don’t have it installed already, and enable it to use these URLs.</p></div>
<h2>Create your first view</h2>
<p>With the action complete on the controller, its time to create the view so we can see the data and interact with it. Views in CakePHP are simple PHP files with a ctp file extension. You can use regular old PHP in your view files.</p>
<div><img src="http://www.tuxradar.com/files/cakephp/cakephp_01_2.jpg" alt="The movie list" />The movie list</p>
</div>
<p>Create your first view in /app/views/movies/index.ctp. You will need to create the directory movies under the /app/views directory first. Add the following code:</p>
<pre>&lt;div&gt;
	&lt;h2&gt;Movies&lt;/h2&gt;
	&lt;table cellpadding="0" cellspacing="0"&gt;
		&lt;tr&gt;
			&lt;th&gt;Title&lt;/th&gt;
			&lt;th&gt;Genre&lt;/th&gt;
			&lt;th&gt;Rating&lt;/th&gt;
			&lt;th&gt;Format&lt;/th&gt;
			&lt;th&gt;Length&lt;/th&gt;
			&lt;th&gt;Actions&lt;/th&gt;
		&lt;/tr&gt;
	&lt;?php foreach ($movies as $movie): ?&gt;
	&lt;tr&gt;
		&lt;td&gt;&lt;?php echo $movie['Movie']['title']; ?&gt; &lt;/td&gt;
		&lt;td&gt;&lt;?php echo $movie['Movie']['genre']; ?&gt; &lt;/td&gt;
		&lt;td&gt;&lt;?php echo $movie['Movie']['rating']; ?&gt; &lt;/td&gt;
		&lt;td&gt;&lt;?php echo $movie['Movie']['format']; ?&gt; &lt;/td&gt;
		&lt;td&gt;&lt;?php echo $movie['Movie']['length']; ?&gt; &lt;/td&gt;
		&lt;td&gt;
			&lt;?php echo $this-&gt;Html-&gt;link('View',
array('action' =&gt; 'view', $movie['Movie']['id'])); ?&gt;
			&lt;?php echo $this-&gt;Html-&gt;link('Edit',
array('action' =&gt; 'edit', $movie['Movie']['id'])); ?&gt;
			&lt;?php echo $this-&gt;Html-&gt;link('Delete',
array('action' =&gt; 'delete', $movie['Movie']['id']),
null, sprintf('Are you sure you want to delete %s?', $movie['Movie']['title'])); ?&gt;
		&lt;/td&gt;
	&lt;/tr&gt;
	&lt;?php endforeach; ?&gt;
	&lt;/table&gt;
&lt;/div&gt;
&lt;div&gt;
	&lt;h3&gt;Actions&lt;/h3&gt;
	&lt;ul&gt;
		&lt;li&gt;&lt;?php echo $this-&gt;Html-&gt;link('New Movie', array('action' =&gt; 'add')); ?&gt;&lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt;</pre>
<p>This will look familiar to anyone who has used HTML and PHP previously. What differs is the use of CakePHP view helpers to output information such as links. The HTML helper allows us to pass array-based information for the View, Edit and Delete actions. These are transformed into URLs such as: http://mysite.com/movies/view/1234 (in the case of a view link).</p>
<p>The view iterates over the $movies variable, which was set by the MoviesController earlier, and outputs all of the entries in a table (this is tabular data, after all).</p>
<p>You can now browse to the /movies/index URL on your server and see the output from your new view. If you have set up the server to host only the CakePHP application we are developing, you can browse to your site address as follows: http://mysite.com/movies/index. Or, if you have set up this CakePHP application in a subdirectory, simply browse to that directory on your server: http://mysite.com/my_directory/movies/index.</p>
<p>For the moment there are no movies in the database. Let’s push on to create the movie addition functionality. We’re on the clock here!</p>
<h2>Create the add action and view</h2>
<p>Next we’ll build on our existing movies controller to include an add action. It will be used to process the addition of new movies to the database. We need to check to see if any form data has ben submitted, and if so, process that information and store it after checking for errors. That sounds like a lot to achieve, but CakePHP makes it easy, as you can see in the following listing:</p>
<pre>class MoviesController extends AppController {
	// .. components ..
	// .. index action ..

	public function add() {
		if (!empty($this-&gt;data)) {
			$this-&gt;Movie-&gt;create($this-&gt;data);
			if ($this-&gt;Movie-&gt;save()) {
				$this-&gt;Session-&gt;setFlash('The movie has been saved');
				$this-&gt;redirect(array('action' =&gt; 'index'));
			} else {
				$this-&gt;Session-&gt;setFlash
('The movie could not be saved. Please, try again.');
			}
		}
	}
}</pre>
<div><img src="http://www.tuxradar.com/files/cakephp/cakephp_01_3.jpg" alt="Adding a movie with the Add view. Yes it's simple, but the cool this is that it took so little code to produce." />Adding a movie with the Add view. Yes it&#8217;s simple, but the cool this is that it took so little code to produce.</p>
</div>
<p>The add view takes advantage of the CakePHP form helper, which makes light work of generating forms for all types of situations. Here we simply define what model we’re creating a form for (in this case, the Movie model), and what fields we want available to the users.</p>
<p>Create the following in /app/views/movies/add.ctp:</p>
<pre>&lt;div class=”movies form”&gt;
&lt;?php
echo $this-&gt;Form-&gt;create(‘Movie’);
echo $this-&gt;Form-&gt;inputs(array(‘title’, ‘genre’, ‘rating’, ‘format’, ‘length’));
echo $this-&gt;Form-&gt;end(‘Add’);
?&gt;
&lt;/div&gt;

&lt;div class=”actions”&gt;
	&lt;h3&gt;Actions&lt;/h3&gt;
	&lt;ul&gt;
		&lt;li&gt;&lt;?php echo $this-&gt;Html-&gt;link(‘List Movies’, array(‘action’ =&gt; ‘index’));?&gt;&lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt;</pre>
<p>The real form creation power of this view file is achieved in the three PHP echo lines at the top. The rest is HTML layout and a link to go back to the list of movies. You’re now able to view the CakePHP ‘movie add’ form by visiting the /movies/add URL, or by clicking on the New Movie link we added to the movie index page.</p>
<p>Brilliant! Now you can go ahead and add a couple of movies. The example in the next screenshot is adding Spider-Man 3 in Blu-ray format. As you add each entry, you are redirected back to the index view, which will show each new movie as it is added to the database.</p>
<h2>Enable movie deletion</h2>
<p>Perhaps you added a movie that you no longer have, or otherwise want to remove an entry from your database. We’ve created links in the views already that point to a delete action, so we’ll implement that one. The delete action does not require a view, as we don’t require any output as part of the process. The action will process the deletion, and then immediately redirect with an appropriate message.</p>
<p>Add the delete action to your Movies controller:</p>
<pre>class MoviesController extends AppController {
	// .. components ..
	// .. index action ..
	// .. add action ..
	public function delete($id = null) {
		if (!$id) {
			$this-&gt;Session-&gt;setFlash(‘Invalid id for movie’);
			$this-&gt;redirect(array(‘action’ =&gt; ‘index’));
		}
		if ($this-&gt;Movie-&gt;delete($id)) {
			$this-&gt;Session-&gt;setFlash(‘Movie deleted’);
		} else {
			$this-&gt;Session-&gt;setFlash(__(‘Movie was not deleted’,
 true));
		}
		$this-&gt;redirect(array(‘action’ =&gt; ‘index’));
	}
}</pre>
<p>We’ve already added ‘delete’ links to the index page in the previous steps. You can now remove entries from your database using the delete links! You will notice that on our index action, the code to implement the delete link was longer than the View and Edit actions. This is because we included a JavaScript alert mechanism to make sure that the user really wanted to delete that record. This is a safety mechanism to give the user a chance to back out, as there is no view associated with the action to prevent an accidental deletion.</p>
<div><img src="http://www.tuxradar.com/files/cakephp/cakephp_01_5.jpg" alt="We've added a delete confirmation box" />We&#8217;ve added a delete confirmation box</p>
</div>
<pre>&lt;?php echo $this-&gt;Html-&gt;link(‘Delete’, array(‘action’ =&gt;
 ‘delete’, $movie[‘Movie’][‘id’]), null,
sprintf(‘Are you sure you want to delete %s?’, $movie[‘Movie’][‘title’])); ?&gt;</pre>
<h2>Editing your data</h2>
<p>Even the best of us makes mistakes, so it’s a good idea to have an edit action available to jump in and correct any issues or changes with records as necessary. This action is very similar to the add action, with the main difference being the management of the existing record ID. In fact, they are so similar that seasoned CakePHP developers will combine the add and edit actions into a single action. Here&#8217;s the code:</p>
<pre>class MoviesController extends AppController {
	// .. components ..
	// .. index action ..
	// .. add action ..
	// .. delete action ..

	function edit($id = null) {
		if (!$id &amp;&amp; empty($this-&gt;data)) {
			$this-&gt;Session-&gt;setFlash('Invalid movie');
			$this-&gt;redirect(array('action' =&gt; 'index'));
		}
		if (!empty($this-&gt;data)) {
			if ($this-&gt;Movie-&gt;save($this-&gt;data)) {
				$this-&gt;Session-&gt;setFlash('The movie has been saved');
				$this-&gt;redirect(array('action' =&gt; 'index'));
			} else {
				$this-&gt;Session-&gt;setFlash('The movie could not be saved. Please, try again.');
			}
		}
		if (empty($this-&gt;data)) {
			$this-&gt;data = $this-&gt;Movie-&gt;read(null, $id);
		}
	}
}</pre>
<p>The main difference between the add and edit actions is that the edit action passes an ID to the action, and does not call the create() method on the Movie object. This is because it needs to retain any existing data for the record when saving to the database.</p>
<h2>Creating your edit view</h2>
<p>It should all be looking familiar by now. The edit view we’re about to create looks almost identical to the add form. Again, developers that have been exposed to CakePHP for some time will integrate the add and edit form to save repeating code. The only difference is the inclusion of an input for the id field in the form, and the label on the submit button.</p>
<p>Create the following in /app/views/movies/edit.ctp:</p>
<pre>&lt;div class=”movies form”&gt;
&lt;?php
echo $this-&gt;Form-&gt;create(‘Movie’);
echo $this-&gt;Form-&gt;inputs(array(‘id’, ‘title’, ‘genre’, ‘rating’, ‘format’, ‘length’));
echo $this-&gt;Form-&gt;end(‘Edit’);
?&gt;
&lt;/div&gt;
&lt;div class=”actions”&gt;
	&lt;h3&gt;Actions&lt;/h3&gt;
	&lt;ul&gt;
		&lt;li&gt;&lt;?php echo $this-&gt;Html-&gt;link(‘List Movies’,
array(‘action’ =&gt; ‘index’));?&gt;&lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt;</pre>
<div><img src="http://www.tuxradar.com/files/cakephp/cakephp_01_6.jpg" alt="The movie detal view." />The movie detal view.</p>
</div>
<h2>Save your view.</h2>
<p>Time to take it for a test drive. Load up your index action in your browser as before, and click through to the edit action of one of your movies. You will be presented with a screen that contains all the inputs and data for your record. Note that the id field is not shown. This is included as a hidden field, so the user cannot tamper with this information. Our final controller action and view will provide a detail view of each movie. It will contain all the information we didn’t show in the index view such as ‘created’ and ‘modified’ times. When browsing to the view action, an ID is passed in the URL to indicate what movie ID we want to view. Add the following view action to your Movies controller:</p>
<pre>class MoviesController extends AppController {
	// .. components ..
	// .. index action ..
	// .. add action ..
	// .. delete action ..
	// .. edit action ..

	function view($id = null) {
		if (!$id) {
			$this-&gt;Session-&gt;setFlash(‘Invalid movie’);
			$this-&gt;redirect(array(‘action’ =&gt; ‘index’));
		}
		$this-&gt;set(‘movie’, $this-&gt;Movie-&gt;findById($id));
	}
}</pre>
<h2>Create the detail view</h2>
<p>Our last view is a simple table displaying all the movie information. Create this view in the following location: /app/views/movies/view.ctp – here&#8217;s the the code:</p>
<pre>&lt;div&gt;
&lt;h2&gt;Movie&lt;/h2&gt;
	&lt;dl&gt;
		&lt;dt&gt;Title&lt;/dt&gt;
		&lt;dd&gt;&lt;?php echo $movie['Movie']['title']; ?&gt;&lt;/dd&gt;
		&lt;dt&gt;Genre&lt;/dt&gt;
		&lt;dd&gt;&lt;?php echo $movie['Movie']['genre']; ?&gt;&lt;/dd&gt;
		&lt;dt&gt;Rating&lt;/dt&gt;
		&lt;dd&gt;&lt;?php echo $movie['Movie']['rating']; ?&gt;&lt;/dd&gt;
		&lt;dt&gt;Format&lt;/dt&gt;
		&lt;dd&gt;&lt;?php echo $movie['Movie']['format']; ?&gt;&lt;/dd&gt;
		&lt;dt&gt;Length&lt;/dt&gt;
		&lt;dd&gt;&lt;?php echo $movie['Movie']['length']; ?&gt;&lt;/dd&gt;
		&lt;dt&gt;Created&lt;/dt&gt;
		&lt;dd&gt;&lt;?php echo $movie['Movie']['created']; ?&gt;&lt;/dd&gt;
		&lt;dt&gt;Modified&lt;/dt&gt;
		&lt;dd&gt;&lt;?php echo $movie['Movie']['modified']; ?&gt;&lt;/dd&gt;
	&lt;/dl&gt;
&lt;/div&gt;

&lt;div&gt;
	&lt;h3&gt;Actions&lt;/h3&gt;
	&lt;ul&gt;
		&lt;li&gt;&lt;?php echo $this-&gt;Html-&gt;link
('Edit Movie', array('action' =&gt; 'edit', $movie['Movie']['id'])); ?&gt; &lt;/li&gt;
		&lt;li&gt;&lt;?php echo $this-&gt;Html-&gt;link
('Delete Movie', array('action' =&gt; 'delete', $movie['Movie']['id']),
null, sprintf('Are you sure you want to delete # %s?', $movie['Movie']['id'])); ?&gt; &lt;/li&gt;
		&lt;li&gt;&lt;?php echo $this-&gt;Html-&gt;link
('List Movies', array('action' =&gt; 'index')); ?&gt; &lt;/li&gt;
		&lt;li&gt;&lt;?php echo $this-&gt;Html-&gt;link
('New Movie', array('action' =&gt; 'add')); ?&gt; &lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt;</pre>
<p>The last action we linked on the index page is now operational! Click through the ‘view’ link on one of the movies in your database to see the result of the detail view we have just created. Notice that it also includes a useful list of relevant actions for the current record.</p>
<p>As you edit information and create new records, you’ll see the created and modified fields for those records being updated by CakePHP for you. This is part of the automatic functionality that the framework provides. Edit a couple of records to see these fields change.</p>
<h2>Where to now?</h2>
<p>You now have a completely functional movie database application that you can host at home, or online. All in under 20 minutes. The next big issue you face is what you are going to do with all your spare time now that CakePHP is doing all the heavy lifting. Good luck, and be sure to let us know what you do with CakePHP at www.linuxformat.com/forums – whatever you do, I hope you save lots of precious time!</p>
<p><strong>We&#8217;ll be following this up with more CakePHP tutorials soon &#8211; stay tuned!</strong></p>
<div id="seo_alrp_related"><h2>Posts Related to How to Build Web Apps Faster in cakephp?</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/build-a-file-sharing-application-in-cakephp/" rel="bookmark">Build a file sharing application in cakephp</a></h3><p>The honeymoon is over baby. Now it’s time for the real work to begin. This iteration of our CakePHP tutorial series will result in your ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-a-bookmark-site-in-cakephp/" rel="bookmark">how to Build a bookmark site in cakephp?</a></h3><p>If you've followed our last few tutorials, you'll be a CakePHP expert by now: you know how to navigate controllers, delve into the depths of ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/cakephp-change-view-file-from-controlle/" rel="bookmark">CakePHP: Change View File From Controlle</a></h3><p>With CakePHP, the controller core automatically detects the file name of the view file which needs to be rendered from a controller action. You might ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/cake-php-interview-questions-and-answers/" rel="bookmark">Cake php interview questions and answers</a></h3><p>What is meant by MVC? model view controller, it is a software architecture, used to isolates business logic from presentation logic. cakephp is based on ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/08/peepli-live-movie-story-and-rating/" rel="bookmark">Peepli Live Movie Story and Rating</a></h3><p>Hello Friend, I have seen peepli live movie no doubt this is good movie but you can't see this movie with your family or parent ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-web-apps-faster-in-cakephp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Build a file sharing application in cakephp</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/09/build-a-file-sharing-application-in-cakephp/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/09/build-a-file-sharing-application-in-cakephp/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 21:58:42 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[cakephp interview question]]></category>
		<category><![CDATA[Home]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[PHP Third Party Tools]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1635</guid>
		<description><![CDATA[The honeymoon is over baby. Now it’s time for the real work to begin. This iteration of our CakePHP tutorial series will result in your very own file-sharing tool. This is handy in the situation that you have a file you need to send to a business partner or client, or share with a friend, [...]]]></description>
			<content:encoded><![CDATA[<p>The honeymoon is over baby. Now it’s time for the real work to begin. This iteration of our CakePHP tutorial series will result in your very own file-sharing tool. This is handy in the situation that you have a file you need to send to a business partner or client, or share with a friend, but you still want to retain control over who gets access to each specific file. For example, you may only want a client to access a file for a week, so we’ll build a system where you can remove that access at any time. What’s more, it’ll be quick, easy, and extensible once we’re done.</p>
<p>&nbsp;</p>
<div></div>
<p>For each file, we want to associate it with a user for ownership, but we also want to be able to associate it with many other users for sharing (read access). So we need to define two separate associations from file to user. We’re going to manage the sharing access with an association called “Has and belongs to many” or HABTM for short. HABTM utilises a join table to associate the two records, and has a standard within CakePHP that we’ll follow so the framework can do all the heavy lifting for us:</p>
<pre>CREATE DATABASE `fileshare`;
USE `fileshare`;

CREATE TABLE `uploads` (
	`id` CHAR(36) NOT NULL PRIMARY KEY,
	`user_id` CHAR(36) NOT NULL,
	`title` VARCHAR(45) NOT NULL,
	`description` TEXT,
	`filename` VARCHAR(255) NOT NULL,
	`filesize` INT(11) UNSIGNED NOT NULL DEFAULT 0,
	`filemime` VARCHAR(45) NOT NULL DEFAULT 'text/plain',
	`created` DATETIME,
	`modified` DATETIME
);

CREATE TABLE `users` (
	`id` CHAR(36) NOT NULL PRIMARY KEY,
	`username` VARCHAR(45) NOT NULL,
	`password` VARCHAR(255) NOT NULL,
	`email` VARCHAR(255) NOT NULL,
	`created` DATETIME,
	`modified` DATETIME
);</pre>
<p>The join table we mentioned identifies users that have been allowed access to specified files. The standards specify that a join table for a HABTM association is to be the tables in their plural form, joined with an underscore and listed in alphabetical order:</p>
<pre>CREATE TABLE `uploads_users` (
  `id` CHAR(36) NOT NULL PRIMARY KEY,
  `upload_id` CHAR(36) NOT NULL,
  `user_id` CHAR(36) NOT NULL
);</pre>
<p>Create your tables in a new database, and we’ll push on to baking the project and getting the basics running.</p>
<h2>Ready, set… bake!</h2>
<p>Bake is a special console command that ships with CakePHP, and is run from the console. In order for this to work effectively the cake/console path within the CakePHP package needs to be in your PATH environment variable. You can achieve this with the following in your shell: $ export PATH=”$PATH:/path/to/cakephp/cake/console” And of course you’ll need PHP available on the command line (usually available in a php-cli package, or similar). To create the skeleton structure for your project, run the following in your shell:</p>
<pre>$ cake bake project fileshare
$ cd fileshare</pre>
<p>Next, configure the app to connect to the database. Change the settings as shown in the following code in your config/database.php file to the appropriate settings for your databaseL</p>
<pre>class DATABASE_CONFIG {
	var $default = array(
		'driver' =&gt; 'mysql',
		'persistent' =&gt; false,
		'host' =&gt; 'localhost',
		'login' =&gt; 'username',
		'password' =&gt; 'password',
		'database' =&gt; 'fileshare',
		'prefix' =&gt; '',
	);
}</pre>
<p>Setting up the “default” connection is enough. And while we’re baking and having CakePHP handle all the hard work, lets bake the controllers, models and views to get the basis of our project in place.</p>
<pre>$ cake bake all user
$ cake bake all upload</pre>
<p>What we have at this stage is a completely ready-to-use website that associates users with many uploads and enables us to populate the database in an easy-to-use manner. But thus far, there’s no actual file upload capability, so we need to modify what CakePHP has baked for us to provide additional functionality processing the file uploads and to prevent people from adding and modifying other users’ information. Further to that, we want to secure the whole application so that only authenticated users can modify data.</p>
<h2>Locking things down</h2>
<p>We already have a ‘users’ table, and the user addition is working as part of the baking process if you browse to your application and append users to the URL. For example: http://localhost/fileshare/users. So what do we need to do? Well, passwords at this stage are being stored in cleartext, and we don’t seem to be asked to log in. Open up the app_controller.php file in the root of your project. This is an empty controller from which all the other controllers in the application inherit functionality. Anything we implement here will be used in all our controllers, so this is the perfect place to enforce logins. Add the Auth and Session components. Your AppController will now look like this:</p>
<pre>&lt;?php
class AppController extends Controller {
  var $components = array(‘Auth’, ‘Session’);
}
?&gt;</pre>
<p>If you try to refresh your users list, you’ll be presented with an error indicating that the login action doesn’t exist. If you look carefully, the URL has also been changed to /users/login. Fortunately all the juicy hard stuff has been implemented in CakePHP for us, so all we need to do is provide the action (function) on the controller, and a login form for users to view. Open up controllers/users_controller.php and add the login action:</p>
<pre>function login() {
}</pre>
<p>That’s not a mistake, it’s an empty function, and it’s all we need for authentication to log in on the controller side.</p>
<div>
<h2>Class Conflicts</h2>
<p>Without the availability of PHP namespaces, we can’t name classes the same as any that might be used from the CakePHP framework. Since CakePHP provides a File class, we’ve had to avoid calling our model in this example “File”, as a conflict would arise with class naming. As such, “Upload” has been used in its place. For a list of all classes in CakePHP, see the public API: http://api.cakephp.org.</p>
</div>
<p>Before we get too ahead of ourselves, we need to ensure that we can register a user in case you have not already registered one. Since we’re about to complete the user authentication section, we’d be locked out of all functionality and if we didn’t make an exception for the user registration page, we’d never be able to get into our funky new system. Create a beforeFilter method on the users controller, and add the following to tell the Auth component that we’re allowed to visit the register page even if we have not yet logged in:</p>
<pre>function beforeFilter() {
  $this-&gt;Auth-&gt;allow(‘add’);
  return parent::beforeFilter();
}</pre>
<p>Create the login view in a new file: views/users/login.ctp, as described here:</p>
<pre>&lt;div&gt;
&lt;?php echo $this-&gt;Form-&gt;create('User');?&gt;
	&lt;fieldset&gt;
 		&lt;legend&gt;&lt;?php __('Login'); ?&gt;&lt;/legend&gt;
	&lt;?php
	echo $this-&gt;Form-&gt;input('username');
	echo $this-&gt;Form-&gt;input('password');
	?&gt;
	&lt;/fieldset&gt;
&lt;?php echo $this-&gt;Form-&gt;end(__('Submit', true));?&gt;
&lt;/div&gt;</pre>
<p>Refresh the page that was giving an error message, and you’ll be presented with a login form. Notice that you will be allowed to visit the /users/add page, but everything else will be redirected to the /users/login page. Feel free at this point to register yourself a user. It will be useful in testing further points in the application. Take a moment to check out your database. You’ll notice that the password is hashed for us automatically. Awesome! It’s also handy to clean up some of the automatically generated fields and inputs that we won’t be using, to ensure that users only have access to things we permit. So remove the following input from both the user add and edit views in views/users/add.ctp and views/users/edit.ctp:</p>
<pre>echo $this-&gt;Form-&gt;input(‘Upload’);</pre>
<div><img src="http://www.tuxradar.com/files/cakephp/cake_03_02.jpg" alt="The user index is accessible until authentication is added." />The user index is accessible until authentication is added.</p>
</div>
<h2>Enabling file uploads</h2>
<p>It’s high time we got some file uploading action happening. First up, let’s make an uploads directory under the project directory to place our uploaded files, then assign ownership to the user running your web server. On some distributions this user is www-data, on others it’s apache or www. You’ll need to specify the appropriate user for your system.</p>
<pre>$ mkdir uploads
$ chown www-data uploads</pre>
<p>Time to dive into some code! Let’s start by adjusting the upload add page to accept files, and store them in a safe manner. The bake process has generated a fairly good form for us, but we’re going to remove a couple of the automatically generated fields and replace them with a file upload field. The columns we defined in our database are primarily for automatic population. The file upload will provide all the data we need. Remove the filename, filesize and filemime inputs from the upload add view in views/uploads/add.ctp, and add in a file input. We didn’t create a column called file in the database, so CakePHP isn’t going to do all the fancy behind-the-scenes work for that field, and we also need to tell it what type that field needs to be for the file input to be generated correctly. The other small change we’re making is to remove the user_id input that CakePHP had generated for us. Instead, we’ll add some code in our controller to automatically assign files to the user who is currently logged in. Your form inputs should now look like this:</p>
<pre>&lt;?php echo $this-&gt;Form-&gt;create(‘Upload’, array(‘type’ =&gt; ‘file’));?&gt;
  &lt;fieldset&gt;
     &lt;legend&gt;&lt;?php __(‘Add Upload’); ?&gt;&lt;/legend&gt;
  &lt;?php
  echo $this-&gt;Form-&gt;input(‘title’);
  echo $this-&gt;Form-&gt;input(‘description’);
  echo $this-&gt;Form-&gt;input(‘file’, array(‘type’ =&gt; ‘file’));
  echo $this-&gt;Form-&gt;input(‘User’);
  ?&gt;
  &lt;/fieldset&gt;
&lt;?php echo $this-&gt;Form-&gt;end(__(‘Submit’, true));?&gt;</pre>
<div><img src="http://www.tuxradar.com/files/cakephp/cake_03_04.jpg" alt="Enabling file uploads is simple." />Enabling file uploads is simple.</p>
</div>
<h2>Processing the uploaded file</h2>
<p>Sure, we’ve got a file in place, but we actually need to handle the file in some manner to show up an error when the file is not correctly uploaded, and to save it in our prepared writable uploads folder when it’s been completed successfully. For this we open up controllers/uploads_controller.php in the baked project, and modify the function add() to process the file if it’s available. On the third line of this function, the code attempts to save the model data. Modify the if statement to call a function that we’ll write in a moment called uploadFile(): if ($this-&gt;uploadFile() &amp;&amp; $this-&gt;Upload-&gt;save($this-&gt;data)) {</p>
<p>Sounds easy enough, doesn’t it? Now let’s create the uploadFile() function in the same controller:</p>
<pre>function uploadFile() {
  $file = $this-&gt;data[‘Upload’][‘file’];
  if ($file[‘error’] === UPLOAD_ERR_OK) {
    $id = String::uuid();
    if (move_uploaded_file($file[‘tmp_name’], APP.’uploads’.DS.$id)) {
      $this-&gt;data[‘Upload’][‘id’] = $id;
      $this-&gt;data[‘Upload’][‘user_id’] = $this-&gt;Auth-&gt;user(‘id’);
      $this-&gt;data[‘Upload’][‘filename’] = $file[‘name’];
      $this-&gt;data[‘Upload’][‘filesize’] = $file[‘size’];
      $this-&gt;data[‘Upload’][‘filemime’] = $file[‘type’];
      return true;
    }
  }
  return false;
}</pre>
<p>Again, we’re keeping things simple. We upload the file, and if we’re able to move it successfully into place, we return true. In the process of doing this, we are manually generating an ID which we use as a safe filesystem name for storage. This eliminates any issues that users may attempt to introduce with weird and potentially system-damaging filenames that would otherwise be directly stored on your filesystem. Manually generating the UUID with String::uuid() removes this security hole, and ensures a safe file upload, while maintaining the original filename in the database to send to the user when downloading.</p>
<p>The next thing we’re going to integrate is the ability to download files. But before going too far, try adding a couple of files. You’ll see them successfully being added to the database, and if you look at the uploads directory we created, matching ID named files start appearing within. If you experience any issues at this point, ensure that your web server user has write access to the uploads directory.</p>
<p>The other cool thing we’re doing here is assigning the user with $this-&gt;Auth-&gt;user(‘id’) which is the ID of the currently logged-in user. Since we locked down the security earlier, we know that users need to be logged in to reach this page, so the value will always be present and valid.</p>
<h2>Cleaning up associations</h2>
<p>You’ll notice that we’ve doubled up on our associations for both the User and Upload model. Take for example the User model in models/user.php; CakePHP has generated a hasMany and a hasAndBelongsToMany association both with the index Upload. This just won’t do, because the clash in naming will cause incorrect data to output in the views. Change the hasAndBelongsToMany association in the User model to be SharedUpload. And similarly for the Upload model in models/upload.php, change the HABTM association to be SharedUser:</p>
<pre>// User Model
var $hasAndBelongsToMany = array(
  ‘SharedUpload’ =&gt; array(
    ‘className’ =&gt; ‘Upload’,
    ...

// Upload Model
var $hasAndBelongsToMany = array(
  ‘SharedUser’ =&gt; array(
    ‘className’ =&gt; ‘User’,
      ..</pre>
<p>In order for these association key changes to correctly render in the views, you’ll need to change the index referenced on the views in the related section at the bottom of the view indexes. In views/users/view.ctp, the following two lines:</p>
<pre>&lt;?php if (!empty($user[‘pload’])):?&gt;
foreach ($user[‘Upload’] as $upload):</pre>
<p>are changed to:</p>
<pre>&lt;?php if (!empty($user[‘SharedUpload’])):?&gt;
foreach ($user[‘SharedUpload’] as $upload):</pre>
<p>At this point you can register a new user, log in to the system, upload files and assign users. We’ve achieved a massive amount of functionality for minimal code and effort. Give the system a good test before moving on the the next step.</p>
<h2>Viewing and downloading files</h2>
<p>If you have played around with the navigation in the views we have already, you’ll have come across the view page for one of your uploaded files. It shows all the meta information about the file, but at this point you can’t retrieve the file itself. Let’s tweak a few things to enable downloads so we can get at the files. The first thing to do is add a link to the view file views/uploads/view.ctp. You can add this wherever you like (I prefer to add it at the bottom of the existing data):</p>
<pre>&lt;dt&lt;?php if ($i % 2 == 0) echo $class;?&gt;&gt;&lt;?php __(‘Download’); ?&gt;&lt;/dt&gt;
&lt;dd&lt;?php if ($i++ % 2 == 0) echo $class;?&gt;&gt;
  &lt;?php echo $this-&gt;Html-&gt;link(__(‘Download’, true), array(‘action’ =&gt; ‘download’, $upload[‘Upload’][‘id’])); ?&gt;

&lt;/dd&gt;</pre>
<p>With the link created, it’s time to get our hands dirty again and put together the action for the controller to handle the file download. Open up your UploadsController in controllers/uploads_controller.php one more time and add the following download function. This forces download, and returns the file to the user with the original filename that was present when the file was uploaded. Here&#8217;s the code:</p>
<pre>function download($id = null) {
	if (!$id) {
		$this-&gt;Session-&gt;setFlash(__('Invalid id for upload', true));
		$this-&gt;redirect(array('action' =&gt; 'index'));
	}
	$this-&gt;Upload-&gt;bindModel(array('hasOne' =&gt; array('UploadsUser')));
	$upload = $this-&gt;Upload-&gt;find('first', array(
		'conditions' =&gt; array(
			'Upload.id' =&gt; $id,
			'OR' =&gt; array(
				'UploadsUser.user_id' =&gt; $this-&gt;Auth-&gt;user('id'),
				'Upload.user_id' =&gt; $this-&gt;Auth-&gt;user('id'),
			),
		)
	));
	if (!$upload) {
		$this-&gt;Session-&gt;setFlash(__('Invalid id for upload', true));
		$this-&gt;redirect(array('action' =&gt; 'index'));
	}
	$this-&gt;view = 'media';
	$filename = $upload['Upload']['filename'];
	$this-&gt;set(array(
		'id' =&gt; $upload['Upload']['id'],
		'name' =&gt; substr($filename, 0, strrpos($filename, '.')),
		'extension' =&gt; substr(strrchr($filename, '.'), 1),
		'path' =&gt; APP.'uploads'.DS,
		'download' =&gt; true,
	));
}</pre>
<div>
<h2>Tutorial Code</h2>
<p>The code for this article has been made available on GitHub under my account http://github.com/predominant/cakephp_linux_format. You can grab the code from here if you had any issues with the code generation through the bake facility, or if you just want to get the application up and running, you can clone the code without going through each of the steps in the article.</p>
</div>
<p>You can now try out your download link, and you’ll get the file being downloaded via your browser! There’s a fair bit going on in this function, but believe me, there’s far more being taken care of by CakePHP that you don’t need to worry about. We’re first inspecting the ID to ensure it was supplied. Next, we try to lookup an upload record from the database with that ID, and while we’re in there, we ensure that the ID of the upload is associated with the currently logged-in user, or that the file was originally uploaded by the user who is logged in. In either case, we are allowed access. If that query failed, the user is attempting to access a file to which they have not specifically been granted permission, so we redirect them to the index list of files.</p>
<h2>Showing only what users can access</h2>
<p>In order to make the file list make sense for all users, you’ll also need to modify the index() action on the Uploads controller, to perform similar filtering to show only the files that are permitted in the users rendered list, otherwise it’ll clog up with files they don’t actually have access to see! Adjust the index action thus:</p>
<pre>function index() {
  $this-&gt;Upload-&gt;bindModel(array(‘hasOne’ =&gt; array(‘UploadsUser’)), false);
  $this-&gt;paginate = array(
    ‘conditions’ =&gt; array(
      ‘OR’ =&gt; array(
        ‘UploadsUser.user_id’ =&gt; $this-&gt;Auth-&gt;user(‘id’),
        ‘Upload.user_id’ =&gt; $this-&gt;Auth-&gt;user(‘id’),
      ),
    )
  );
  $this-&gt;set(‘uploads’, $this-&gt;paginate());
}</pre>
<p>We’ve had to add the false parameter on the bindModel() call this time to ensure that the pagination result came out correctly. Pagination takes two separate database results to return the data. The first of these determines the number of elements in the table that match the query, and the second actually retrieve the data. The false parameter tells CakePHP to retain the binding beyond a single query. The simple rule, of course, is that if you are using bindModel and pagination, you need to add false on the end.</p>
<p>The view() action also benefits from the same filtering:</p>
<pre>function view($id = null) {
  if (!$id) {
    $this-&gt;Session-&gt;setFlash(__(‘Invalid upload’, true));
$this-&gt;redirect(array(‘action’ =&gt; ‘index’));
  }

  $this-&gt;Upload-&gt;bindModel(array(‘hasOne’ =&gt; array(‘UploadsUser’)));
  $upload = $this-&gt;Upload-&gt;find(‘first’, array(
    ‘conditions’ =&gt; array(
      ‘Upload.id’ =&gt; $id,
      ‘OR’ =&gt; array(
        ‘UploadsUser.user_id’ =&gt; $this-&gt;Auth-&gt;user(‘id’),
        ‘Upload.user_id’ =&gt; $this-&gt;Auth-&gt;user(‘id’),
      ),
    )
  ));
  if (!$upload) {
    $this-&gt;Session-&gt;setFlash(__(‘Invalid upload’, true));
    $this-&gt;redirect(array(‘action’ =&gt; ‘index’));
  }
  $this-&gt;set(‘upload’, $upload);
}</pre>
<h2>Wrapping it up</h2>
<p>The only last nicety that would be required to take this site live is a logout function. And I’ll be kind enough to give you the code to put on the UsersController for logout:</p>
<pre>public function logout() {
  $this-&gt;redirect($this-&gt;Auth-&gt;logout());
}</pre>
<p>There’s no view required, and redirection happens as soon as the user hits the /users/logout URL, after destroying the session and logging out the user.</p>
<p>So we’ve built a secure, file-uploading, multi-user sharing web application, and it’s only taken 20 minutes or so to get it all done. From here, you can add extra functionality such as thumbnail icons to preview content that users have uploaded, or a different sharing mechanism to select users without exposing the complete user list to everyone. You can also enable email notifications for users that you are sharing files with. I hope you’ve enjoyed this tutorial, and I hope it’s useful for you either as a case study, or as a deployable solution for client file sharing.</p>
<div><img src="http://www.tuxradar.com/files/cakephp/cake_03_05.jpg" alt="The additional link enables us to download files that have been uploaded." />The additional link enables us to download files that have been uploaded.</p>
</div>
<div id="seo_alrp_related"><h2>Posts Related to Build a file sharing application in cakephp</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/uploading-largebig-files-in-php-using-htaccess-2/" rel="bookmark">Uploading large(big) files in PHP using .htaccess</a></h3><p>I’ve seen that many of my friends are struggling with the uploads of the bigger or larger files in PHP. After looking at their struggle, ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-a-bookmark-site-in-cakephp/" rel="bookmark">how to Build a bookmark site in cakephp?</a></h3><p>If you've followed our last few tutorials, you'll be a CakePHP expert by now: you know how to navigate controllers, delve into the depths of ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-web-apps-faster-in-cakephp/" rel="bookmark">How to Build Web Apps Faster in cakephp?</a></h3><p>The pressure is on. You’ve got limited time, and you need a system to catalogue your extensive movie collection in 15 minutes. Who ya gonna ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/a-solution-for-e-mail-handling-in-cakephp/" rel="bookmark">A solution for e-mail handling in CakePHP</a></h3><p>The emailComponent (cake\libs\controller\components\email.php) is a way for you to using the same concepts of layouts and view ctp files to send formated messages as text, ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/21-things-you-must-know-about-cakephp/" rel="bookmark">21 Things You Must Know About CakePHP</a></h3><p>Easily creating static pages I needed to create several pages that didn't use any models and contained static data inside the default layout. My first ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/09/build-a-file-sharing-application-in-cakephp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>how to Build a bookmark site in cakephp?</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-a-bookmark-site-in-cakephp/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-a-bookmark-site-in-cakephp/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 21:57:53 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[cakephp interview question]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[PHP Third Party Tools]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1633</guid>
		<description><![CDATA[If you&#8217;ve followed our last few tutorials, you&#8217;ll be a CakePHP expert by now: you know how to navigate controllers, delve into the depths of models and create views that astound your viewers. But having a taste of the sweet rapid development that CakePHP offers you, you want more, and you want to do more [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve followed our last few tutorials, you&#8217;ll be a CakePHP expert by now: you know how to navigate controllers, delve into the depths of models and create views that astound your viewers. But having a taste of the sweet rapid development that CakePHP offers you, you want more, and you want to do more in less time. Fair enough too, so in our last project for this series, we&#8217;re going to take a look at using CakePHP plugins to extend the functionality of our app. This is the result of the DRY principle (Don&#8217;t repeat yourself). Solve a problem once, package it in a reusable manner, and then release it to the world for everyone to contribute to and benefit from your solution. While you&#8217;re at it, grab some code that other people have already written, and include those plugins to save you huge amounts of time.</p>
<p>We&#8217;re jumping in the deep end, and build a bookmarking site that will not only store URLs and associated information for us, but generate some pretty sweet thumbnails and store those for use too. Because we&#8217;re a social community these days, we&#8217;ll include some nifty tools from a useful plugin to enable quick and easy social network sharing and publishing to get the word out about a URL that we&#8217;ve published.</p>
<div>
<p><img src="http://www.tuxradar.com/files/cakephp/cake_04_01.jpg" alt="Using the Authentication component automatically encrypts passwords" />Using the Authentication component automatically encrypts passwords</p>
</div>
<p>As always, we put in some time ensuring that our database fits the CakePHP conventions and standards so that the heavy lifting later on is handled by CakePHP. Don&#8217;t stress though, if you want to deviate from the standards or structure here, it&#8217;s extremely easy to customise, depending on what you&#8217;re changing. Check out http://book.cakephp.org/view/901/CakePHP-Conventions for a list of the conventions adopted by the core, and for information on what you need to do to break free and go your own way.</p>
<p>Take a moment to consider the data we need to store. We&#8217;ll need: URLs, users and ratings, so that when we share the bookmarked URLs via Twitter, Facebook or whatever our preferred social network giant is, people can rate the content if they like it.</p>
<pre>CREATE DATABASE `bookmark`;
USE `bookmark`;
CREATE TABLE `urls` (
	`id` CHAR(36) NOT NULL PRIMARY KEY,
	`user_id` CHAR(36) NOT NULL,
	`name` VARCHAR(128) NOT NULL,
	`url` TEXT,
	`created` DATETIME,
	`modified` DATETIME
);
CREATE TABLE `users` (
	`id` CHAR(36) NOT NULL PRIMARY KEY,
	`username` VARCHAR(45) NOT NULL,
	`password` VARCHAR(255) NOT NULL,
	`email` VARCHAR(255) NOT NULL,
	`created` DATETIME,
	`modified` DATETIME
);</pre>
<p>Hang on a moment… surely that can&#8217;t be all the tables we need? That list of information we wanted to include for each bookmark was pretty long. And it doesn&#8217;t look like there are enough fields in that table to hold all the data &#8211; except that each plugin is capable of distributing database information that it needs in a segregated way to ensure that you have all the functionality you need packaged in the plugin that provides it, including the database storage requirements.</p>
<p>Okay, but how does it work? Its done by using either the &#8216;Schema&#8217; shell, which comes with CakePHP, or by using the &#8216;Migrations&#8217; plugin, which is developed by the Cake Development Corporation. We&#8217;ll run through the migrations plugin, because it provides much more functionality, while still remaining easy to use.</p>
<h2>Time to hit the oven, baking time!</h2>
<p>Bake is a console command for CakePHP, and it enables you to generate code, run migrations, run tests and much more. In order for this to work effectively from your console, the cake/console path within the CakePHP package needs to be in your PATH environment variable. You can achieve this with the following in your shell:</p>
<pre>$ export PATH="$PATH:/path/to/cakephp/cake/console"</pre>
<p>The only other requirement is that you have PHP available on your command line. Most distros have a php-cli package or similar to provide a command line interface PHP binary.</p>
<p>Bake a new project to create the skeleton structure we need to get moving. Run the following in your shell:</p>
<pre>$ cake bake project bookmark
$ cd bookmark</pre>
<p>CakePHP has created a basic app structure for you to use. This includes the directories and some basic initial files for you to use to serve static pages. Feel free to dig around and see exactly what has been produced for you. It&#8217;s a good idea to get familiar with the file structure that CakePHP adopts.</p>
<p>Before we bake, let&#8217;s tell CakePHP how to connect to our database. Take a copy of the /config/database.php.default file and rename it to /config/database.php. Enter in your database configuration to match the user details for your local database install. Here&#8217;s what my config shows:</p>
<pre>&lt;?php
class DATABASE_CONFIG {
	var $default = array(
		'driver' =&gt; 'mysql',
		'persistent' =&gt; false,
		'host' =&gt; 'localhost',
		'login' =&gt; 'dev',
		'password' =&gt; 'dev',
		'database' =&gt; 'bookmark',
		'prefix' =&gt; '',
	);
}</pre>
<p>You&#8217;ll note that I have removed the test database configuration from the file. The test configuration is used for unit testing, and in this tutorial we won&#8217;t be touching on it.</p>
<div>
<p><img src="http://www.tuxradar.com/files/cakephp/cake_04_02.jpg" alt="We can already add a new URL to our bookmarking service" />We can already add a new URL to our bookmarking service</p>
</div>
<p>Let&#8217;s get cracking on the baking of models, views and controllers for the database tables we created earlier. Baking will generate all the code we need to get the common functionality working, and will enable us to customise from there, saving a whole lotta time.</p>
<pre>$ cake bake all user
$ cake bake all url</pre>
<p>Don&#8217;t be alarmed by the amount of output text from the bake command; the more it outputs, the more time it has saved you through generating code. If you take a look at the output, you&#8217;ll see file paths and names to all the files that have been created for you. You now have a user and URL management system, and can browse through to add and edit that information. Try browsing to /users on your site. For example, I baked into my webroot, and so the URL I use is: http://localhost/bookmark/users. You&#8217;ll be greeted with the users index page, and from here you can navigate around to add and edit users.</p>
<h2>Enabling authentication</h2>
<p>We&#8217;ll quickly run through locking the system down so we can create users and log in, but not access anything else until we are logged in. This is a great way to secure your system, and its dead easy to do!</p>
<p>Open up the app_controller.php file in the root of your project. This is an empty controller from which all the other controllers in the application inherit functionality. Anything we implement here will be used in all our controllers, so this is the perfect place to enforce user authentication, and keep out nasty guests from editing data. Add the “Auth&#8221; and “Session&#8221; components. Your AppController will now look like this:</p>
<pre>&lt;?php
class AppController extends Controller {
	var $components = array('Auth', 'Session');
	function beforeFilter() {
		$this-&gt;set('authUser', $this-&gt;Auth-&gt;user());
		return parent::beforeFilter();
	}
}</pre>
<p>You&#8217;ll note we snuck in a set call in the function beforeFilter there. This will ensure that we have access to the current user information in the views throughout the site. If there is no user currently logged in, this will be set to null.</p>
<p>Next, open up /controllers/users_controller.php and add a login action. This can be empty, as CakePHP handles the tricky stuff behind the scenes. While we&#8217;re digging around, also add the logout function for logging out users:</p>
<pre>function login() {
}

function logout() {
	return $this-&gt;redirect($this-&gt;Auth-&gt;logout());
}</pre>
<p>Finally, on the controller side, we want to ensure that we don&#8217;t have to log in to create a user, otherwise we&#8217;d be stuck with no users, and no way to create one! Add the following to your users controller:</p>
<pre>function beforeFilter() {
	$this-&gt;Auth-&gt;allow('add');
	return parent::beforeFilter();
}</pre>
<p>The final piece of this puzzle is the view file, which isn&#8217;t created with the CakePHP bake tool. This will take the username and password and enable users to log in. Create the login view in a new file: /views/users/login.ctp:</p>
<pre>&lt;div&gt;
&lt;?php echo $this-&gt;Form-&gt;create('User', array('url' =&gt; array('action' =&gt; 'login')));?&gt;
	&lt;fieldset&gt;
 		&lt;legend&gt;&lt;?php __('Login'); ?&gt;&lt;/legend&gt;
	&lt;?php
	echo $this-&gt;Form-&gt;input('username');
	echo $this-&gt;Form-&gt;input('password');
	?&gt;
	&lt;/fieldset&gt;
&lt;?php echo $this-&gt;Form-&gt;end(__('Login', true));?&gt;
&lt;/div&gt;</pre>
<p>Browse back to your users list (http://localhost/bookmark/users) and you&#8217;ll immediately be redirected to the user login form. Now, try visiting the user addition page (http://localhost/bookmark/users/add) and you&#8217;ll note that you are allowed to view this page, and thus not redirected away to log in. Brilliant! It couldn&#8217;t get any easier!</p>
<div>
<p><img src="http://www.tuxradar.com/files/cakephp/cake_04_04.jpg" alt="Enabling users to share your site's content will increase your traffic and popularity." />Enabling users to share your site&#8217;s content will increase your traffic and popularity.</p>
</div>
<p>Time for a fresh coffee and a pat on the back. Your data is secure, and your site works. Take a spin around the app and create a new user. Log in and test that it works correctly, and add a URL or two. Once you are happy with how that is operating and you are familiar with the site, we&#8217;ll move on to including plugins, and getting the cool stuff working!</p>
<p>Back in school they&#8217;d kick you out for it.. But here you&#8217;re welcome to grab people&#8217;s code and use it in your project to enhance functionality, or just save time. Just remember to check the licensing of the plugins you choose to use, as they may not be compatible with the project you are building.</p>
<h2>How to cheat</h2>
<p>Let&#8217;s go hunting for plugins, grab what we need and set up the directories in /app/plugins. For the purposes of this plugin installation, I&#8217;m going to assume that you have Git installed. Using Git will speed up the download and organisation of our application plugins for usage. And while you&#8217;re at it, its a great way to get used to using Git for version control if you&#8217;re not already familiar with it.</p>
<p>Run the following Git commands in your console:</p>
<pre>git clone https://github.com/CakeDC/migrations.git plugins/migrations
git clone https://github.com/CakeDC/ratings.git plugins/ratings
git clone https://github.com/CakeDC/search.git plugins/search
git clone https://github.com/predominant/cake_social.git plugins/cake_social
git clone https://github.com/predominant/goodies.git plugins/goodies</pre>
<p>You&#8217;ve just saved yourself months of development time. No kidding. You&#8217;re utilising a bunch of open source plugins that are available to any CakePHP developer who wants to use it, to cover the common functionality in your application. This saves time and money and lets you get on to leisure time quicker than the rest of the developers. Bonus!</p>
<div>
<h2>Re-using plugins</h2>
<p>If you are using a central installation of CakePHP and it&#8217;s on your php.ini include_path (See http://book.cakephp.org/view/1645/Deployment for more information on deployment and development setups and the best approaches), then you can add your plugins to the /cake/plugins directory, and each of the plugins immediately becomes available to any CakePHP application using that core. This is a super awesome way to ensure your plugins are up to date, and saves time from checking out many copies or copying files all over the place.</p>
</div>
<h2>Running migrations</h2>
<p>Earlier I mentioned that we had a lack of database tables, but that would be taken care of by database migrations. That time has come, and you&#8217;ll see how simple database table creation can be for plugins and code reuse through projects. Not all plugins need or have migrations. Those that do will have a migrations directory in their config directory. For example, you will see the directory /plugins/ratings/config/migrations. You can check through to see what needs migrations, or just run them all, and you&#8217;ll get an error message for those that didn&#8217;t actually have migrations available, which is fine.</p>
<p>Run the following to complete the table setup for the plugins we&#8217;ve introduced:</p>
<pre>$ cake migration -plugin ratings all</pre>
<p>You should now have all the tables you need for the site!</p>
<p>Let&#8217;s start by enabling ratings. We want those accessible for URLs only. Adding the component is really easy. Open up the UrlsController in /controllers/urls_controller.php and add the Ratings component. Your resulting code will now look like the following:</p>
<pre>class UrlsController extends AppController {
	var $components = array('Ratings.Ratings');
		// ... existing code ...
}</pre>
<p>What&#8217;s super cool about this is that the component we&#8217;ve just added takes care of including the helper that you need to display the ratings form, as well as handles the saving and loading of ratings information for you. So all you need to do is set up your view as you like it to show the form for ratings, through the ratings helper, and the rating itself. Now being a truly portable and flexible plugin, the ratings information isn&#8217;t averaged or calculated for you on load, since that would be making the assumption that we know what maths you need applied for your specific situation. So some effort is required to get the right value showing, and to get the form showing only when users have not yet rated it.</p>
<p>The next section of code is pretty big;</p>
<pre>&lt;?php
$rated = Set::extract('/Rating[user_id=' . $authUser['User']['id'] . ']', $url);
if (empty($rated)): ?&gt;
	&lt;dt&lt;?php if ($i % 2 == 0) echo $class;?&gt;&gt;&lt;?php __('Rate'); ?&gt;&lt;/dt&gt;
	&lt;dd&lt;?php if ($i++ % 2 == 0) echo $class;?&gt;&gt;
	&lt;?php echo $this-&gt;Rating-&gt;display(array(
	    'item' =&gt; $url['Url']['id'],
	    'type' =&gt; 'radio',
	    'stars' =&gt; 5,
	    'createForm' =&gt; array(
			'url' =&gt; array_merge(
				$this-&gt;passedArgs,
				array(
					'rate' =&gt; $url['Url']['id'],
					'redirect' =&gt; true))
			)
	)); ?&gt;

	&lt;/dd&gt;
&lt;?php else: ?&gt;
	&lt;dt&lt;?php if ($i % 2 == 0) echo $class;?&gt;&gt;&lt;?php __('Rating'); ?&gt;&lt;/dt&gt;
	&lt;dd&lt;?php if ($i++ % 2 == 0) echo $class;?&gt;&gt;
		&lt;?php
		$ratings = Set::extract('/Rating/value', $url);
		echo array_sum($ratings) / count($ratings); ?&gt;

	&lt;/dd&gt;
&lt;?php endif; ?&gt;</pre>
<p>There are two main sections to the code: the first shows the form if you have not already rated the current bookmark, and the second displays our rating. Both sections of code use the Set class, which makes it easy to handle larger collections of data, and enables filtering. Add the code just after the dl tag at the start of your URLs view in /views/urls/view.ctp.</p>
<p>Browsing to a URL now shows a set of radio buttons, and a Rate Submission button. Sweet! Give it a go, rate a URL &#8211; you&#8217;ll be redirected to the same page, and the resulting rating will be displayed for you. Feel free to test this out some more by using another user, and see how the resulting rating changes to be the average of all the rates submitted. Pretty darn cool!</p>
<h2>Using gravatars</h2>
<p>The URL view page is pretty bland. There, I said it! What we really should do is at least include some more imagery and items to represent the information on the page in a more rapid manner for visitors. We&#8217;ll leave the complexities of CSS and styling the page to perfection to the web designers, but we will make their job easy through using gravatars to show user icons from the user information we have for each URL. A gravatar is a global avatar, and is provided for free through http://gravatar.com. We included a Goodies plugin when we cloned all the plugins, and the gravatar helper is just one of the awesome things that this plugin provides.</p>
<p>Enough sales talk.. Lets get some gravatars showing. If you have not done already, head over to the gravatar website, register your account for free, and set up a gravatar. Next, open up the URLs view (/views/urls/view.ctp). Scroll down to where the User information is output. The line we&#8217;re going to replace is:</p>
<pre>&lt;?php echo $this-&gt;Html-&gt;link($url['User']['id'], array('controller' =&gt; 'users', 'action' =&gt; 'view', $url['User']['id'])); ?&gt;</pre>
<p>Replace this with a similar code link, but this time, include the output of the gravatar helper:</p>
<pre>&lt;?php echo $this-&gt;Html-&gt;link(
	$this-&gt;Gravatar-&gt;image($url['User']['email']),
	array('controller' =&gt; 'users', 'action' =&gt; 'view', $url['User']['id']),
	array('escape' =&gt; false)); ?&gt;
&lt;?php echo $url['User']['username']; ?&gt;</pre>
<p>Finally, include the helper in your AppController in /app_controller.php:</p>
<pre>class AppController extends Controller {
	var $helpers = array('Html', 'Form', 'Session', 'Goodies.Gravatar');
	// ... existing code ...
}</pre>
<p>This will show the user&#8217;s gravatar based on their email address supplied at registration time, and also their username, instead of that ugly UUID string. Go ahead, refresh the page or browse to another URL to view it, and the gravatar will be shown in place of the user information.</p>
<h2>Adding a social sharing widget</h2>
<p>Let&#8217;s do one more step to fancy up the extra information and add some social sharing capabilities to promote more people to visit our site, and to enable users to share the bookmarks they really like. This functionality comes from the CakeSocial plugin we added at the beginning. The CakeSocial plugin includes a helper for the “ShareThis&#8221; service, which makes social sharing really simple. So a simple plugin for a simple service, should be super simple, right? Judge for yourself. Add the helper to the AppController in /app_controller.php:</p>
<pre>class AppController extends Controller {
	var $helpers = array('Html', 'Form', 'Session', 'Goodies.Gravatar', 'CakeSocial.ShareThis');
	// ... existing code ...
}</pre>
<p>And just before the closing tag on your view for URLSs /views/urls/view.ctp include the following:</p>
<pre>&lt;dt&lt;?php if ($i % 2 == 0) echo $class;?&gt;&gt;&lt;?php __('Share'); ?&gt;&lt;/dt&gt;
&lt;dd&lt;?php if ($i++ % 2 == 0) echo $class;?&gt;&gt;
	&lt;?php echo $this-&gt;ShareThis-&gt;display(); ?&gt;

&lt;/dd&gt;</pre>
<p>Whoa! There are five lines of code for that view, but only one is doing the social output. The rest is wrapping styles for the output, and a label. Reload your page and you&#8217;ll have the ShareThis social helpers appear, and you can share on a list of default services.</p>
<h2>Icing on the cake: Web thumbnails</h2>
<p>Since we saved so much time using plugins and getting these awesome features included, we have some spare time to include a cool feature like thumbnailing. Wouldn&#8217;t it be cool to have a small picture of the website pop up when we&#8217;re looking at the view page for a URL? That really would be the icing on the cake.</p>
<p>We&#8217;re going to take advantage of another helper from the Goodies plugin to grab the thumbnail from the Thumboo service (http://www.thumboo.com). Fetching on each view is not loading your server, as the request is handled by the external service, and it ensures that your thumbs are always up to date!</p>
<div>
<p><img src="http://www.tuxradar.com/files/cakephp/cake_04_05.jpg" alt="The website thumbnails really make a difference to a bookmarking service" />The website thumbnails really make a difference to a bookmarking service</p>
</div>
<p>Head over to Thumboo (http://www.thumboo.com) and create an account for free. You&#8217;ll be given an API Access key. Hold on to that, you&#8217;ll need it later.</p>
<p>Once more unto the breach! Or, once more we&#8217;ll edit the AppController `/app_controller.php`, and add a helper. Add the Thumboo helper from the Goodies plugin:</p>
<pre>class AppController extends Controller {
	var $helpers = array('Html', 'Form', 'Session', 'Goodies.Gravatar', 'CakeSocial.ShareThis', 'Goodies.Thumboo');

	// ... existing code ...
}</pre>
<p>Almost there! Switch back to the view for urls `/views/urls/view.ctp` and add the following immediately after the heading at the top of the file:</p>
<pre>&lt;?php echo $this-&gt;Thumboo-&gt;image($url['Url']['url']); ?&gt;</pre>
<p>We&#8217;ve used the smallest form possible to call the helper, and we have not yet supplied that extremely easy to remember API key that Thumboo has provided us with. For this, we&#8217;re going to create a configuration file, and CakePHP will load this up as it needs it to read the key value. Using this method lets you keep configuration separate from code, and its a great way to kep your secure information safe.</p>
<p>Create a new file in `/config/thumboo.php` and add the following, replacing the key value with what you were supplied after signup:</p>
<pre>&lt;?php
$config = array(
	'Thumboo' =&gt; array(
		'Key' =&gt; 'MY KEY HERE',
	)
);</pre>
<p>Reload your page and revel in the beauty of what has been achieved in such a short period of time. You&#8217;ve earned yourself a beer.</p>
<p>Where to now? The app you have built today is a good example of how quickly you can build apps with CakePHP, and the quality of the plugins that are available for free within the community. The current app has a lot of potential to expand to provide extra details like private URLs, a REST service for integration, a bookmarklet that uses Ajax that you can include for your browser, some styling, and removal of some default data and pages. The possibilities are endless!</p>
<div id="seo_alrp_related"><h2>Posts Related to how to Build a bookmark site in cakephp?</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-web-apps-faster-in-cakephp/" rel="bookmark">How to Build Web Apps Faster in cakephp?</a></h3><p>The pressure is on. You’ve got limited time, and you need a system to catalogue your extensive movie collection in 15 minutes. Who ya gonna ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/build-a-file-sharing-application-in-cakephp/" rel="bookmark">Build a file sharing application in cakephp</a></h3><p>The honeymoon is over baby. Now it’s time for the real work to begin. This iteration of our CakePHP tutorial series will result in your ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/21-things-you-must-know-about-cakephp/" rel="bookmark">21 Things You Must Know About CakePHP</a></h3><p>Easily creating static pages I needed to create several pages that didn't use any models and contained static data inside the default layout. My first ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/cakephp-interview-questions/" rel="bookmark">cakephp interview questions</a></h3><p>Questionnaire started with some of the questions from core php like what all functions do you use in your development can you just list them ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/a-solution-for-e-mail-handling-in-cakephp/" rel="bookmark">A solution for e-mail handling in CakePHP</a></h3><p>The emailComponent (cake\libs\controller\components\email.php) is a way for you to using the same concepts of layouts and view ctp files to send formated messages as text, ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-build-a-bookmark-site-in-cakephp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to optimize php code.</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-optimize-php-code/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-optimize-php-code/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 20:40:19 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[As a last resort]]></category>
		<category><![CDATA[Avoid calling the dl() function]]></category>
		<category><![CDATA[Avoid mod_access if you can]]></category>
		<category><![CDATA[best of luck. What is the process for PHP code Optimisation]]></category>
		<category><![CDATA[big and small - they slow things down]]></category>
		<category><![CDATA[Compress your output to save network bandwidth]]></category>
		<category><![CDATA[Don't fret about Apache 2.0]]></category>
		<category><![CDATA[Don't rely on references without testing; they are rarely as effective as you'd think]]></category>
		<category><![CDATA[Get a good understanding of how garbage collection works]]></category>
		<category><![CDATA[How to optimize php code]]></category>
		<category><![CDATA[In this post we are going to learn how to optimize our php code]]></category>
		<category><![CDATA[Listen to all errors]]></category>
		<category><![CDATA[Optimise compilation of your PHP binary if possible]]></category>
		<category><![CDATA[Pre-increment where possible]]></category>
		<category><![CDATA[Priorities optimisation of tight loops for the most payback]]></category>
		<category><![CDATA[Store a local pointer to an array element to save indexing into the array each time you need it]]></category>
		<category><![CDATA[try inlining function]]></category>
		<category><![CDATA[Try to avoid using PHP in CGI mode]]></category>
		<category><![CDATA[Use persistent resource where appropriate]]></category>
		<category><![CDATA[Use the comma operator to join arguments when calling echo]]></category>
		<category><![CDATA[Use the Zend Optimizer and a code cache]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1629</guid>
		<description><![CDATA[In this post we are  going to learn how to optimize our php code. once you optimize your php code then your applicationa and website will be very fast this will make quality code. Hi php programmer don&#8217;t forget these rules if you want to be good in php and want to work in MNC [...]]]></description>
			<content:encoded><![CDATA[<p>In this post we are  going to learn how to optimize our php code.</p>
<p>once you optimize your php code then your applicationa and website will be very fast<br />
this will make quality code. Hi php programmer don&#8217;t forget these rules if you want to<br />
be good in php and want to work in MNC because all mnc and all good companies follow<br />
these rules strictly even this is gud question for interview for php. best of luck.</p>
<p>What is the process for PHP code Optimisation.</p>
<p>Use the Zend Optimizer and a code cache</p>
<p>Use the comma operator to join arguments when calling echo</p>
<p>Priorities optimisation of tight loops for the most payback</p>
<p>Pre-increment where possible</p>
<p>Don&#8217;t rely on references without testing; they are rarely as effective as you&#8217;d think</p>
<p>Get a good understanding of how garbage collection works</p>
<p>Listen to all errors, big and small &#8211; they slow things down</p>
<p>Store a local pointer to an array element to save indexing into the array each time you need it</p>
<p>Compress your output to save network bandwidth</p>
<p>Try to avoid using PHP in CGI mode</p>
<p>Avoid calling the dl() function</p>
<p>Use persistent resource where appropriate</p>
<p>Optimise compilation of your PHP binary if possible</p>
<p>Avoid mod_access if you can</p>
<p>Don&#8217;t fret about Apache 2.0</p>
<p>As a last resort, try inlining function</p>
<div id="seo_alrp_related"><h2>Posts Related to How to optimize php code.</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-optimize-mysql-query-and-mysql-database/" rel="bookmark">How to optimize mysql query and mysql database?</a></h3><p>There is lots of way to optimize mysql. once you optimize your query and database of mysql it will make your website and application very ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-make-controller-without-a-model-in-cakephp/" rel="bookmark">How To Make Controller Without a Model in cakephp ?</a></h3><p>class MyController extends AppController {     // var $uses = null; works too     var $uses = array();     function index()     {     } } If you omit the ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/programmer-vs-company-how-any-programmer-will-feel-secure-in-company/" rel="bookmark">Programmer VS Company : How any programmer will feel secure in Company?</a></h3><p>Programmer VS Company All of friends I am going to share my Experience about the company and Programmer ,what I feel in last 7 Years ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/inserting-multiple-rows-in-cakephp/" rel="bookmark">Inserting Multiple Rows in Cakephp</a></h3><p>I had a situation where I needed to iterate through a list of items and insert new rows for each. I quickly discovered that if ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/04/using-custom-table-for-custom-module-in-magento/" rel="bookmark">Using Custom Table for Custom Module in Magento</a></h3><p>If you want to create a custom module in Magento that has something to do with storing data into a custom table and using that ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/09/how-to-optimize-php-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What Is the Difference Between Mysql_Connect() and Mysql_Pconnect()?</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/what-is-the-difference-between-mysql_connect-and-mysql_pconnect/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/what-is-the-difference-between-mysql_connect-and-mysql_pconnect/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 18:38:11 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[mysql interview question]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1591</guid>
		<description><![CDATA[When they are using mysql_connect() function, every time it is opening and closing the database connection, depending on the request . mysql_connect() and mysql_pconnect() both are working for database connection but with small difference. In mysql_pconnect(), â€˜pâ€™ stands for persistence connection. But in case of mysql_pconnect() function, first, when connecting, the function would try to [...]]]></description>
			<content:encoded><![CDATA[<p>When they are using mysql_connect() function, every time it is opening and closing the database connection, depending on the request .</p>
<p>mysql_connect() and mysql_pconnect() both are working for database connection but with small difference. In mysql_pconnect(), â€˜pâ€™ stands for persistence connection.</p>
<p>But in case of mysql_pconnect() function,<br />
first, when connecting, the function would try to find a (persistent) connection thatâ€™s already open with the same host, username and password. If three is found, an identifier for it will be returned in lieu of opening a new connection.<br />
Second, the connection to the SQL server won’t be closed when the execution of the script ends. In lieu, the connection will remain open for future use (mysql_close() won’t close connection established by mysql_pconnect()).</p>
<p>Mysql_pconncet() is useful when you have a lot of traffic on your site. At that time for every request it won’t open a connection but will take it from the pool. This will increase the efficiency of your site. But for general use mysql_connect() is best.</p>
<div id="seo_alrp_related"><h2>Posts Related to What Is the Difference Between Mysql_Connect() and Mysql_Pconnect()? </h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-ftp-functions-list/" rel="bookmark">PHP FTP Functions List</a></h3><p>ftp_cdup — Changes to the parent directory ftp_chdir — Changes directories on a FTP server ftp_close — Closes an FTP connection ftp_connect — Opens an ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-oracle-function-list/" rel="bookmark">PHP Oracle Function List</a></h3><p>Ora_Bind — bind a PHP variable to an Oracle parameter Ora_Close — close an Oracle cursor Ora_ColumnName — get name of Oracle result column Ora_ColumnSize ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-make-dsn-and-dsn-less-connections/" rel="bookmark">How to make DSN and DSN-less connections</a></h3><p>DSN stands for 'Data Source Name'. It is an easy way to assign useful and easily rememberable names to data sources which may not be ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-mysql-functions-list/" rel="bookmark">PHP Mysql Functions List</a></h3><p>mysql_affected_rows — Get number of affected rows in previous MySQL operation mysql_change_user — Change logged in user of the active connection mysql_client_encoding — Returns the ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/03/advanced-integration-method-aim/" rel="bookmark">Advanced Integration Method (AIM)</a></h3><p>AIM is Authorize.Net's recommended connection method and offers the most secure and flexible integration. AIM allows merchants to host their own secure payment form and ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/what-is-the-difference-between-mysql_connect-and-mysql_pconnect/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CURL URLS with a get variable</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-urls-with-a-get-variable/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-urls-with-a-get-variable/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 18:34:19 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[cURL PHP]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1580</guid>
		<description><![CDATA[I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &#38;amp when the page is read by the curl function. If you code a script to find all hyperlinks, it will use &#38;amp instead of &#38;, especially using a regular expression search. [...]]]></description>
			<content:encoded><![CDATA[<p>I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &amp;amp when the page is read by the curl function.</p>
<p>If you code a script to find all hyperlinks, it will use &amp;amp instead of &amp;, especially using a regular expression search.</p>
<p>It is hard to detect because when you output the url to the browser it renders the html. To fix, add a line to replace the &amp;amp with &amp;.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
</td>
<td>
<div>
<div><code>&lt;?php</code></div>
<div><code>function</code> <code>processURL(</code><code>$url</code><code>){</code></div>
<div><code>    </code><code>$url</code><code>=</code><code>str_replace</code><code>(</code><code>'&amp;amp;'</code><code>,</code><code>'&amp;'</code><code>,</code><code>$url</code><code>);</code></div>
<div><code>    </code><code>$ch</code><code>=curl_init();</code></div>
<div><code>    </code><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_URL, </code><code>$url</code><code>);</code></div>
<div><code>    </code><code>curl_setopt (</code><code>$ch</code><code>, CURLOPT_RETURNTRANSFER, 1);</code></div>
<div><code>    </code><code>$xml</code> <code>= curl_exec (</code><code>$ch</code><code>);</code></div>
<div><code>    </code><code>curl_close (</code><code>$ch</code><code>);</code></div>
<div><code>    </code><code>echo</code> <code>$xml</code><code>;</code></div>
<div><code>}</code></div>
<div><code>?&gt;</code></div>
</div>
</td>
</tr>
</tbody>
</table>
<div id="seo_alrp_related"><h2>Posts Related to CURL URLS with a get variable</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/example-download-website-webpage-trough-curl-php/" rel="bookmark">Example: Download Website / Webpage Trough CURL PHP</a></h3><p>You can access / display any webpage through the following code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/simple-curl-php-example/" rel="bookmark">Simple CURL PHP Example</a></h3><p>Following code returns the curl output as a string. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-email-this-page-to-a-friend/" rel="bookmark">CURL PHP: Email this page to a friend</a></h3><p>Using curl to take snapshots of the current page for emailing the HTML is a clever little idea. (ie: Email this page to a friend) ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/disadvantage-of-curl-library-php-example/" rel="bookmark">Disadvantage of cURL Library PHP example</a></h3><p>Although it has been noted that cURL outperforms both file_get_contents and fopen when it comes to getting a file over a HTTP link, the disadvantage ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-curl-functions-list/" rel="bookmark">PHP Curl Functions List</a></h3><p>curl_close — Close a CURL session curl_errno — Return an integer containing the last error number curl_error — Return a string containing the last error ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-urls-with-a-get-variable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CURL PHP wrapper for https results</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-wrapper-for-https-results/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-wrapper-for-https-results/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 18:33:52 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[cURL PHP]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1578</guid>
		<description><![CDATA[If you want to write a sort of php wrapper to include the results of another http(s) request maybe pointing to a totally different site or just different code (mod_perl with HTML::Mason, in my case) into a php based layout, and just pass-thru all GET and POST variables to the sub-request, the following snippet can [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to write a sort of php wrapper to include the results of another http(s) request maybe pointing to a totally different site or just different code (mod_perl with HTML::Mason, in my case) into a php based layout, and just pass-thru all GET and POST variables to the sub-request, the following snippet can be used. Note there is no error handling, so this is subject to the underlying application.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
<div>17</div>
<div>18</div>
</td>
<td>
<div>
<div><code>&lt;?php</code></div>
<div><code>$ch</code> <code>= curl_init(</code><code>$sub_req_url</code><code>);</code></div>
<div><code>$encoded</code> <code>= </code><code>''</code><code>;</code></div>
<div><code>// include GET as well as POST variables; your needs may vary.</code></div>
<div><code>foreach</code><code>(</code><code>$_GET</code> <code>as</code> <code>$name</code> <code>=&gt; </code><code>$value</code><code>) {</code></div>
<div><code>  </code><code>$encoded</code> <code>.= urlencode(</code><code>$name</code><code>).</code><code>'='</code><code>.urlencode(</code><code>$value</code><code>).</code><code>'&amp;'</code><code>;</code></div>
<div><code>}</code></div>
<div><code>foreach</code><code>(</code><code>$_POST</code> <code>as</code> <code>$name</code> <code>=&gt; </code><code>$value</code><code>) {</code></div>
<div><code>  </code><code>$encoded</code> <code>.= urlencode(</code><code>$name</code><code>).</code><code>'='</code><code>.urlencode(</code><code>$value</code><code>).</code><code>'&amp;'</code><code>;</code></div>
<div><code>}</code></div>
<div><code>// chop off last ampersand</code></div>
<div><code>$encoded</code> <code>= </code><code>substr</code><code>(</code><code>$encoded</code><code>, 0, </code><code>strlen</code><code>(</code><code>$encoded</code><code>)-1);</code></div>
<div><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_POSTFIELDS,  </code><code>$encoded</code><code>);</code></div>
<div><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_HEADER, 0);</code></div>
<div><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_POST, 1);</code></div>
<div><code>curl_exec(</code><code>$ch</code><code>);</code></div>
<div><code>curl_close(</code><code>$ch</code><code>);</code></div>
<div><code>?&gt;</code></div>
</div>
</td>
</tr>
</tbody>
</table>
<div id="seo_alrp_related"><h2>Posts Related to CURL PHP wrapper for https results </h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-url-functions-list/" rel="bookmark">PHP URL Functions List</a></h3><p>base64_decode — Decodes data encoded with MIME base64 base64_encode — Encodes data with MIME base64 parse_url — Parse a URL and return its components rawurldecode ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/what-are-the-advantages-of-curl-library/" rel="bookmark">What Are the Advantages of CURL Library?</a></h3><p>PHP supports libcurl is a library that allows you to connect and communicate to many different types of servers with many different types of protocols. ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-connect-to-a-secure-server/" rel="bookmark">cURL PHP: Connect to a Secure Server</a></h3><p>If you want to connect to a secure server for posting info/reading info, you need to make cURL with the openSSL options. Then the sequence ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/curl-to-submit-to-an-aspaspx-page/" rel="bookmark">cURL to submit to an ASP/ASPX page</a></h3><p>For anyone trying to use cURL to submit to an ASP/ASPX page that uses an image as the submit button. Make sure that you have ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/load-json-data-with-jquery-php-and-mysql/" rel="bookmark">Load JSON data with jQuery, PHP and MySQL</a></h3><p>This post shows how to populate a select box based on the value of the another, by getting JSON data with jQuery from a PHP ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-wrapper-for-https-results/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CURL PHP: Get information regarding a specific transfercurl_getinfo â€” Get information regarding a specific transfer – curl_getinfo()</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-get-information-regarding-a-specific-transfercurl_getinfo-ae%e2%80%9d-get-information-regarding-a-specific-transfer-%e2%80%93-curl_getinfo/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-get-information-regarding-a-specific-transfercurl_getinfo-ae%e2%80%9d-get-information-regarding-a-specific-transfer-%e2%80%93-curl_getinfo/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 18:33:25 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[cURL PHP]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1576</guid>
		<description><![CDATA[&#60;?php // Create a curl handle $ch = curl_init('http://www.yahoo.com/'); // Execute curl_exec($ch); // Check if any error occured if(!curl_errno($ch)) {  $info = curl_getinfo($ch);  echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']; } // Close handle curl_close($ch); ?&#62; Posts Related to CURL PHP: Get information regarding a specific [...]]]></description>
			<content:encoded><![CDATA[<div>
<div><code>&lt;?php</code></div>
<div><code>// Create a curl handle</code></div>
<div><code>$ch</code> <code>= curl_init(</code><code>'<a href="http://www.yahoo.com/">http://www.yahoo.com/</a>'</code><code>);</code></div>
<div></div>
<div><code>// Execute</code></div>
<div><code>curl_exec(</code><code>$ch</code><code>);</code></div>
<div></div>
<div><code>// Check if any error occured</code></div>
<div><code>if</code><code>(!curl_errno(</code><code>$ch</code><code>))</code></div>
<div><code>{</code></div>
<div><code> </code><code>$info</code> <code>= curl_getinfo(</code><code>$ch</code><code>);</code></div>
<div></div>
<div><code> </code><code>echo</code> <code>'Took '</code> <code>. </code><code>$info</code><code>[</code><code>'total_time'</code><code>] . </code><code>' seconds to send a request to '</code> <code>. </code><code>$info</code><code>[</code><code>'url'</code><code>];</code></div>
<div><code>}</code></div>
<div></div>
<div><code>// Close handle</code></div>
<div><code>curl_close(</code><code>$ch</code><code>);</code></div>
<div><code>?&gt;</code></div>
</div>
<div id="seo_alrp_related"><h2>Posts Related to CURL PHP: Get information regarding a specific transfercurl_getinfo â€” Get information regarding a specific transfer – curl_getinfo() </h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-curl-functions-list/" rel="bookmark">PHP Curl Functions List</a></h3><p>curl_close — Close a CURL session curl_errno — Return an integer containing the last error number curl_error — Return a string containing the last error ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/a-simple-whoisdomain-availability-check-using-curl-php/" rel="bookmark">A simple whois/domain availability check using cURL PHP</a></h3><p>CURL Register Your domain but check its availability: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/simple-curl-php-example/" rel="bookmark">Simple CURL PHP Example</a></h3><p>Following code returns the curl output as a string. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/example-download-website-webpage-trough-curl-php/" rel="bookmark">Example: Download Website / Webpage Trough CURL PHP</a></h3><p>You can access / display any webpage through the following code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-trouble-on-server-2003-iis-6-php_curl/" rel="bookmark">CURL PHP : Trouble on server 2003, IIS 6 php_curl</a></h3><p>run (as an administrator) php.exe -i &gt; C:\phpinfo.txt and go open C:\phpinfo.txt, look in the file to see if CURL was loading, if it’s there ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-get-information-regarding-a-specific-transfercurl_getinfo-ae%e2%80%9d-get-information-regarding-a-specific-transfer-%e2%80%93-curl_getinfo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Example: Download Website / Webpage Trough CURL PHP</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/example-download-website-webpage-trough-curl-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/example-download-website-webpage-trough-curl-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 18:33:04 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[cURL PHP]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1574</guid>
		<description><![CDATA[You can access / display any webpage through the following code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 [...]]]></description>
			<content:encoded><![CDATA[<p>You can access / display any webpage through the following code:</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
<div>17</div>
<div>18</div>
<div>19</div>
<div>20</div>
<div>21</div>
<div>22</div>
<div>23</div>
<div>24</div>
<div>25</div>
<div>26</div>
<div>27</div>
<div>28</div>
<div>29</div>
<div>30</div>
<div>31</div>
<div>32</div>
<div>33</div>
<div>34</div>
<div>35</div>
<div>36</div>
<div>37</div>
<div>38</div>
<div>39</div>
<div>40</div>
<div>41</div>
<div>42</div>
<div>43</div>
<div>44</div>
<div>45</div>
<div>46</div>
<div>47</div>
<div>48</div>
</td>
<td>
<div>
<div><code>&lt;?php</code></div>
<div><code>    </code><code>echo</code> <code>DownloadUrl(</code><code>'<a href="http://www.imjan.com/">http://www.imjan.com</a>'</code><code>); // Type Website URL to download</code></div>
<div></div>
<div><code>    </code><code>function</code> <code>DownloadUrl(</code><code>$Url</code><code>){</code></div>
<div></div>
<div><code>            </code><code>// is curl installed?</code></div>
<div><code>            </code><code>if</code> <code>(!function_exists(</code><code>'curl_init'</code><code>)){</code></div>
<div><code>                    </code><code>die</code><code>(</code><code>'CURL is not installed!'</code><code>);</code></div>
<div><code>            </code><code>}</code></div>
<div></div>
<div><code>            </code><code>// create a new curl resource</code></div>
<div><code>            </code><code>$ch</code> <code>= curl_init();</code></div>
<div></div>
<div><code>            </code><code>/*</code></div>
<div><code>            </code><code>Here you find more options for curl:</code></div>
<div></div>
<div><code><a href="http://www.php.net/curl_setopt">http://www.php.net/curl_setopt</a></code></div>
<div></div>
<div><code>            </code><code>*/</code></div>
<div></div>
<div><code>            </code><code>// set URL to download</code></div>
<div><code>            </code><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_URL, </code><code>$Url</code><code>);</code></div>
<div></div>
<div><code>            </code><code>// set referer:</code></div>
<div><code>            </code><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_REFERER, </code><code>"<a href="http://www.google.com/">http://www.google.com/</a>"</code><code>);</code></div>
<div></div>
<div><code>            </code><code>// user agent:</code></div>
<div><code>            </code><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_USERAGENT, </code><code>"MozillaXYZ/1.0"</code><code>);</code></div>
<div></div>
<div><code>            </code><code>// remove header? 0 = yes, 1 = no</code></div>
<div><code>            </code><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_HEADER, 0);</code></div>
<div></div>
<div><code>            </code><code>// should curl return or print the data? true = return, false = print</code></div>
<div><code>            </code><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_RETURNTRANSFER, true);</code></div>
<div></div>
<div><code>            </code><code>// timeout in seconds</code></div>
<div><code>            </code><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_TIMEOUT, 10);</code></div>
<div></div>
<div><code>            </code><code>// download the given URL, and return output</code></div>
<div><code>            </code><code>$output</code> <code>= curl_exec(</code><code>$ch</code><code>);</code></div>
<div></div>
<div><code>            </code><code>// close the curl resource, and free system resources</code></div>
<div><code>            </code><code>curl_close(</code><code>$ch</code><code>);</code></div>
<div></div>
<div><code>            </code><code>// print output</code></div>
<div><code>            </code><code>return</code> <code>$output</code><code>;</code></div>
<div><code>    </code><code>}</code></div>
<div><code>?&gt;</code></div>
</div>
</td>
</tr>
</tbody>
</table>
<div id="seo_alrp_related"><h2>Posts Related to Example: Download Website / Webpage Trough CURL PHP</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/simple-curl-php-example/" rel="bookmark">Simple CURL PHP Example</a></h3><p>Following code returns the curl output as a string. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-curl-functions-list/" rel="bookmark">PHP Curl Functions List</a></h3><p>curl_close — Close a CURL session curl_errno — Return an integer containing the last error number curl_error — Return a string containing the last error ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/curl-urls-with-a-get-variable/" rel="bookmark">CURL URLS with a get variable</a></h3><p>I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &amp;amp when ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/disadvantage-of-curl-library-php-example/" rel="bookmark">Disadvantage of cURL Library PHP example</a></h3><p>Although it has been noted that cURL outperforms both file_get_contents and fopen when it comes to getting a file over a HTTP link, the disadvantage ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/a-simple-whoisdomain-availability-check-using-curl-php/" rel="bookmark">A simple whois/domain availability check using cURL PHP</a></h3><p>CURL Register Your domain but check its availability: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/example-download-website-webpage-trough-curl-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CURL PHP: Email this page to a friend</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-email-this-page-to-a-friend/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-email-this-page-to-a-friend/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 18:32:29 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[cURL PHP]]></category>
		<category><![CDATA[Home]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1572</guid>
		<description><![CDATA[Using curl to take snapshots of the current page for emailing the HTML is a clever little idea. (ie: Email this page to a friend) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 &#60;?php //to be explained below! session_write_close(); $pageurl = "http://www.site.com/content.php?PHPSESSID=123XYZ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); [...]]]></description>
			<content:encoded><![CDATA[<p>Using curl to take snapshots of the current page for emailing the HTML is a clever little idea. (ie: Email this page to a friend)</p>
<div>
<div id="highlighter_396792">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
<div>17</div>
<div>18</div>
</td>
<td>
<div>
<div><code>&lt;?php</code></div>
<div><code>//to be explained below!</code></div>
<div><code>session_write_close();</code></div>
<div></div>
<div><code>$pageurl</code> <code>= "http:</code><code>//www.site.com/content.php?PHPSESSID=123XYZ</code></div>
<div><code>curl_setopt(</code><code>$ch</code><code>, CURLOPT_RETURNTRANSFER, 1);</code></div>
<div></div>
<div><code>curl_setopt (</code><code>$ch</code><code>, CURLOPT_URL, </code><code>$pageurl</code> <code>);</code></div>
<div><code>$html</code> <code>= curl_exec ( </code><code>$ch</code> <code>);</code></div>
<div><code>curl_close(</code><code>$ch</code><code>);</code></div>
<div></div>
<div><code>//then you need to fix pathing to absolute</code></div>
<div><code>$search</code> <code>= </code><code>"/(src|href|background)="</code><code>[^:,^&gt;,^\</code><code>"]*\"/i"</code><code>;</code></div>
<div></div>
<div><code>preg_match_all ( </code><code>$search</code><code>, </code><code>$html</code><code>, </code><code>$a_matches</code> <code>);</code></div>
<div></div>
<div><code>//you can figure out the rest ! but thought the reg expression is useful as well</code></div>
<div><code>?&gt;</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>But here is the catch, you may want to make sure curl connects to the server under the same session as the browser. So naturally you pass the session cookie through the curl system either by the cookie jar system, or through the query string in the path.</p>
<p>This is where you will get stuck. PHP will need write access to the same session file simultaneously!! causing serious hanging issues!</p>
<p>This is why you should close off your session before you make curl take a page snapshot!</p>
<div id="seo_alrp_related"><h2>Posts Related to CURL PHP: Email this page to a friend </h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-curl-functions-list/" rel="bookmark">PHP Curl Functions List</a></h3><p>curl_close — Close a CURL session curl_errno — Return an integer containing the last error number curl_error — Return a string containing the last error ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/curl-urls-with-a-get-variable/" rel="bookmark">CURL URLS with a get variable</a></h3><p>I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &amp;amp when ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-trouble-on-server-2003-iis-6-php_curl/" rel="bookmark">CURL PHP : Trouble on server 2003, IIS 6 php_curl</a></h3><p>run (as an administrator) php.exe -i &gt; C:\phpinfo.txt and go open C:\phpinfo.txt, look in the file to see if CURL was loading, if it’s there ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/03/how-to-do-file-uploading-using-php-curl/" rel="bookmark">how to do File Uploading Using PHP Curl</a></h3><p>File uploading through PHP Curl is very simple. You just have to append @ in front of path of file name &amp; send it to ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-get-the-current-page-url/" rel="bookmark">How to Get the Current Page URL</a></h3><p>Sometimes, you might want to get the current page URL that is shown in the browser URL window. For example if you want to let ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/curl-php-email-this-page-to-a-friend/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

