<?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>PHP Archives - Cube Websites</title>
	<atom:link href="https://cubewebsites.com/category/development/php/feed/" rel="self" type="application/rss+xml" />
	<link>https://cubewebsites.com/category/development/php/</link>
	<description>web design and development</description>
	<lastBuildDate>Tue, 03 Jan 2023 15:21:16 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://cubewebsites.com/wp-content/uploads/2019/04/cropped-favicon-32x32.png</url>
	<title>PHP Archives - Cube Websites</title>
	<link>https://cubewebsites.com/category/development/php/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>HOW TO: Using Laravel with Directus 9</title>
		<link>https://cubewebsites.com/development/laravel/how-to-using-laravel-with-directus-9/</link>
					<comments>https://cubewebsites.com/development/laravel/how-to-using-laravel-with-directus-9/#respond</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Tue, 03 Jan 2023 15:21:16 +0000</pubDate>
				<category><![CDATA[Laravel]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[directus]]></category>
		<category><![CDATA[laravel]]></category>
		<guid isPermaLink="false">https://cubewebsites.com/?p=1199</guid>

					<description><![CDATA[<p>If you need to use Directus with Laravel then this guide will take you through the steps needed to get connected in just a few minutes. The general idea is to use a composer package to interact with Directus. We&#8217;ll register it in our AppServiceProvider which means we can call a pre-configured instance anywhere in [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/development/laravel/how-to-using-laravel-with-directus-9/">HOW TO: Using Laravel with Directus 9</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you need to use Directus with Laravel then this guide will take you through the steps needed to get connected in just a few minutes.</p>



<p>The general idea is to use a composer package to interact with Directus.  We&#8217;ll register it in our AppServiceProvider which means we can call a pre-configured instance anywhere in our app using dependency-injection.</p>



<p><strong>In Directus</strong></p>



<ul class="wp-block-list">
<li>It&#8217;s advisable to create a new role for your Laravel Application.  To make it easy to track I give it the name &#8216;laravel-app&#8217;</li>



<li>Create a new user for your Laravel Application and assign it the new Role you just created</li>



<li>On the Edit User screen, find the &#8216;Token&#8217; field.  Generate a token and <strong>make a note of it somewhere</strong></li>
</ul>



<p><strong>In Laravel</strong></p>



<ul class="wp-block-list">
<li>Now switch to your Laravel app.  For this integration, I&#8217;m using a composer package from https://github.com/alantiller/directus-php-sdk</li>



<li>Install the package:</li>
</ul>



<pre class="wp-block-code"><code>composer require alantiller/directus-php-sdk</code></pre>



<ul class="wp-block-list">
<li>In your <code>.env</code> file add the following:</li>
</ul>



<pre class="wp-block-code"><code>DIRECTUS_URL=https://directus.example.com
DIRECTUS_TOKEN=-YOURTOKEN</code></pre>



<ul class="wp-block-list">
<li>Replace the Url with your actual Directus URL</li>



<li>Replace YOURTOKEN with the Token you generated for your Laravel user in Directus</li>



<li>In config/services.php add the following:</li>
</ul>



<pre class="wp-block-code"><code>'directus' =&gt; &#91;<br>    'url'   =&gt; env('DIRECTUS_URL'),<br>    'token' =&gt; env('DIRECTUS_TOKEN'),<br>],</code></pre>



<p>In app/providers/AppServiceProvider.php add the following to the <code>register()</code> method</p>



<pre class="wp-block-code"><code>$this-&gt;app-&gt;singleton(Directus::class, function ($app) {<br>    $directus = new Directus($app&#91;'config']&#91;'services']&#91;'directus']&#91;'url'],'');<br>    $directus-&gt;auth_token($app&#91;'config']&#91;'services']&#91;'directus']&#91;'token']);<br>    return $directus;<br>});</code></pre>



<p>In your code you&#8217;ll be able to now use Directus with the standard dependency injection.  You can find examples on how to use the <a href="https://github.com/alantiller/directus-php-sdk" target="_blank" rel="noreferrer noopener nofollow">alantiller/directus-php-sdk package on Github</a>.</p>



<p>Example:</p>



<pre class="wp-block-code"><code>php artisan make:command DirectusTest</code></pre>



<p>In the <code>handle</code> method of the generated command:</p>



<pre class="wp-block-code"><code>&lt;?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class DirectusTest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'directus:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(\Slations\DirectusSdk\Directus $directus)
    {
        dd($directus->users_me());
    }
}</code></pre>



<p>Call the command:</p>



<pre class="wp-block-code"><code>php artisan directus:tset</code></pre>



<p>The output should show you details of the Laravel App user you added on Directus.  Once it&#8217;s working delete the command.</p>



<p>This is all it takes to have a fully working Directus integration with Laravel.  The package does most of the work, but registering it in your AppServiceProvider means you&#8217;ll get a connected instance whenever you need to use it instead of having to instantiate it.</p>



<p>Note that this application uses an application token which is tied to a single user.  If you need multi-user support then the package supports <code>login</code> so you can authenticate users and use their auth token.</p>
<p>The post <a href="https://cubewebsites.com/development/laravel/how-to-using-laravel-with-directus-9/">HOW TO: Using Laravel with Directus 9</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/development/laravel/how-to-using-laravel-with-directus-9/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>HOW TO: Using Laravel with Vite on MAMP</title>
		<link>https://cubewebsites.com/development/laravel/how-to-using-laravel-with-vite-on-mamp/</link>
					<comments>https://cubewebsites.com/development/laravel/how-to-using-laravel-with-vite-on-mamp/#respond</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Wed, 28 Dec 2022 11:34:42 +0000</pubDate>
				<category><![CDATA[Guides]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Laravel]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[laravel]]></category>
		<category><![CDATA[mamp]]></category>
		<category><![CDATA[vite]]></category>
		<guid isPermaLink="false">https://cubewebsites.com/?p=1186</guid>

					<description><![CDATA[<p>I recently needed to help someone out who was using MAMP on a MacBook Pro on a Laravel 9 project. The project was configured to: The Problem When running the default project with yarn run dev and accessing the project in the browser via the hostname configured in MAMP, the hot reload feature was not [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/development/laravel/how-to-using-laravel-with-vite-on-mamp/">HOW TO: Using Laravel with Vite on MAMP</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I recently needed to help someone out who was using MAMP on a MacBook Pro on a Laravel 9 project.</p>



<p>The project was configured to:</p>



<ul class="wp-block-list">
<li>run on MAMP</li>



<li>the MAMP host was configured to use SSL</li>



<li>Laravel 9</li>



<li>Vite</li>



<li>InertiaJS</li>
</ul>



<h2 class="wp-block-heading">The Problem</h2>



<p>When running the default project with <code>yarn run dev</code> and accessing the project in the browser via the hostname configured in MAMP, the hot reload feature was not working and the network and console tabs in Developer Tools were polluted with lots of 404 errors about the failure to connect to the Vite Ping URL e.g. <code>__vite_ping</code> to which it keeps trying to reconnect to.</p>



<h2 class="wp-block-heading">How to fix</h2>



<p>You have to configure Vite to run on https.  This can be done in a number of ways, but the easiest is to use the <a href="https://www.npmjs.com/package/@vitejs/plugin-basic-ssl" target="_blank" rel="noreferrer noopener nofollow">@vitejs/plugin-basic-ssl</a> plugin.  It&#8217;s really easy to get started:</p>



<ol class="wp-block-list">
<li>Add the plugin to your project
<ul class="wp-block-list">
<li>with yarn: <code>yarn add --dev @vitejs/plugin-basic-ssl</code></li>



<li>with npm: <code>npm i @vitejs/plugin-basic-ssl</code></li>
</ul>
</li>



<li>Open the <code>vite.config.js</code> file in your Laravel project</li>



<li>Import the plugin at the top of the file:
<ul class="wp-block-list">
<li><code>import basicSsl from '@vitejs/plugin-basic-ssl'</code></li>
</ul>
</li>



<li>Enable the plugin using the defineConfig block e.g.</li>
</ol>



<pre class="wp-block-preformatted">export default {
  plugins: [
    basicSsl()
  ]
}</pre>



<p>Note: you might already have other plugins or config options in the <code>defineConfig</code> block, but you just need to make sure you add the called to <code>basicSsl()</code> in the plugins section.</p>



<p>After this when you run your project using <code>yarn run dev</code> it will provide you with a Local URL e.g.</p>



<pre class="wp-block-code"><code>11:15:06 &#91;vite] vite.config.js changed, restarting server...
11:15:06 &#91;vite] server restarted.

  > Local: https://localhost:3000/
  > Network: use `--host` to expose</code></pre>



<p>Open that Local URL in your browser and you&#8217;ll receive an SSL warning.  Accept the risks to accept the SSL certificate generated by the plugin.</p>



<p>Once that&#8217;s done when you visit your application dev URL, you&#8217;ll see all the Vite 404 errors have disappeared and you&#8217;re left with one neat little log that tells you Vite is now connected.</p>



<pre class="wp-block-code"><code>&#91;vite] connecting... <a href="https://127.0.0.1:3000/src/client/client.ts">client.ts:16:8</a>
&#91;vite] connected. client.ts:53:14</code></pre>



<p>Hope this helps!</p>
<p>The post <a href="https://cubewebsites.com/development/laravel/how-to-using-laravel-with-vite-on-mamp/">HOW TO: Using Laravel with Vite on MAMP</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/development/laravel/how-to-using-laravel-with-vite-on-mamp/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Getting Started With Laravel and Ember</title>
		<link>https://cubewebsites.com/development/ember/getting-started-laravel-ember/</link>
					<comments>https://cubewebsites.com/development/ember/getting-started-laravel-ember/#comments</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Mon, 07 Mar 2016 18:56:43 +0000</pubDate>
				<category><![CDATA[Ember]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ember]]></category>
		<category><![CDATA[laravel]]></category>
		<guid isPermaLink="false">https://cubewebsites.com/?p=461</guid>

					<description><![CDATA[<p>Introduction This guide will show you how to setup a new project using Ember and Laravel, JSON-API and token based authentication.  The deployed version of your application will be a Laravel backend which serves up the Ember frontend using a Laravel route. Software At the time of writing the tools used are: Laravel 5.1 (LTS) [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/development/ember/getting-started-laravel-ember/">Getting Started With Laravel and Ember</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>This guide will show you how to setup a new project using Ember and Laravel, JSON-API and token based authentication.  The deployed version of your application will be a Laravel backend which serves up the Ember frontend using a Laravel route.</p>
<p><strong>Software</strong></p>
<p>At the time of writing the tools used are:</p>
<ul>
<li><a href="https://laravel.com/docs/5.1">Laravel 5.1</a> (LTS)</li>
<li><a href="http://emberjs.com/builds/">Ember 2.4.1</a> (LTS) with <a href="http://ember-cli.com/">Ember-CLI 2.4.1</a></li>
<li><a href="https://github.com/dingo/api">Dingo API</a> 1.0.0 (beta)</li>
<li><a href="https://github.com/tymondesigns/jwt-auth">Tymon jwt-auth</a> 0.5.9</li>
<li><a href="https://github.com/simplabs/ember-simple-auth">ember-simple-auth</a> 1.0.1</li>
<li><a href="https://github.com/jpadilla/ember-simple-auth-token">ember-simple-auth-token</a> 1.0.0</li>
</ul>
<p><strong>Prerequisites</strong></p>
<ol>
<li><a href="http://ember-cli.com/">Ember CLI 2.4.1</a></li>
<li><a href="https://laravel.com/docs/5.1#installation">Laravel Requirements</a></li>
<li><a href="https://getcomposer.org/">Composer</a></li>
<li><a href="https://git-scm.com/">Git</a> or any other VCS that you prefer</li>
</ol>
<p><span id="more-461"></span></p>
<h2><strong>Initial Setup</strong></h2>
<p>The basic project structure will be a <strong>backend</strong> directory for the Laravel part, and a <strong>frontend</strong> directory for Ember.</p>
<pre>#create a directory called sample-project
mkdir sample-project
# go into the sample-project directory
cd sample-project
# make the project a Git project
git init .</pre>
<p>For .gitignore files I prefer using <a href="http://gitignore.io/">gitignore.io</a> which creates a <code>.gitignore</code> file for the software that you use.  Just generate one that matches your needs, I use the following: <code>OSX, Composer, Laravel, PHPStorm, Vagrant</code> but you can customise for your own needs.  Just generate and add this to the root of your sample project e.g.</p>
<pre>wget "https://www.gitignore.io/api/osx%2Ccomposer%2Claravel%2Cphpstorm%2Cvagrant" -O .gitignore</pre>
<p>NOTE: I don&#8217;t like that gitignore&#8217;s Laravel setup excludes the full storage directory &#8211; which can cause problems during deployment.  Instead I manually remove the following line from the .gitignore file and use the .gitignore files already provided by Laravel in each storage subdirectory.</p>
<p><code>storage/</code></p>
<p>It also selectively excludes certain PHPStorm files (.idea) whereas I prefer ignoring the full .idea directory:</p>
<pre># Add .idea to the .gitignore file
echo ".idea" &gt;&gt; .gitignore</pre>
<h2><strong>Laravel (Backend) Setup<br />
</strong></h2>
<p>I prefer to use the LTS releases of Laravel, so will be installing version 5.1</p>
<pre># Install Laravel 5.1 to a directory called backend
composer create-project laravel/laravel backend "5.1.*"
# Switch into the backend (Laravel) directory
cd backend</pre>
<p>Your current project structure should now look like this:</p>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-15.26.03.png" rel="attachment wp-att-463"><img loading="lazy" decoding="async" class="alignnone size-medium wp-image-463" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-15.26.03.png" alt="Screen Shot 2016-03-06 at 15.26.03" width="137" height="57" /></a></p>
<pre># Delete the .git directory from backend as we already have our Git project setup in the project root
# Make sure you are in the backend directory (don't delete .git in your project root directory)
rm -Rf .git</pre>
<pre># Add all the Laravel files and commit the project
git add .
git commit -a -m "Added Laravel 5.1"</pre>
<p>Add your database configuration to the <code>.env</code> file by updating the following lines:</p>
<pre>DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret</pre>
<pre># Migrate the default Laravel tables
php artisan migrate</pre>
<h3><strong>Install Dingo API</strong></h3>
<p>The <a href="https://github.com/dingo/api">Dingo API</a> package has <a href="https://github.com/dingo/api/wiki">comprehensive documentation available</a> but for the sake of this guide I&#8217;ll go through a quick setup.  I highly recommend you read through the documentation and configuration so that you can make your API work appropriately for you.</p>
<pre># Install the Dingo API package
composer require dingo/api:1.0.x@dev</pre>
<p>Add the Dingo API service provider class to the list of Laravel providers (<code>config/app.php</code>)</p>
<pre>Dingo\Api\Provider\LaravelServiceProvider::class,</pre>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.35.50.png" rel="attachment wp-att-465"><img loading="lazy" decoding="async" class="alignnone size-medium wp-image-465" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.35.50-300x221.png" alt="Screen Shot 2016-03-06 at 19.35.50" width="300" height="221" srcset="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.35.50-300x221.png 300w, https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.35.50.png 316w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>Publish the Dingo API config file</p>
<pre>php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"</pre>
<p>Add some basic config options to the <code>.env</code> file</p>
<pre>API_PREFIX=api
API_VERSION=v1
API_DEBUG=true</pre>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.36.26.png" rel="attachment wp-att-466"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-466" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.36.26.png" alt="Screen Shot 2016-03-06 at 19.36.26" width="164" height="116" /></a></p>
<pre># Git commit the changes (Dingo API Installation)
git add .
git commit -a -m "Installed Dingo API"</pre>
<h3><strong>Install Tymon JWT-Auth</strong></h3>
<p>The JWT-Auth token package is only required if JWT (JSON Web Tokens) is an authentication method that you plan to use in your application.  This tutorials assuems that you will be using it, but if you&#8217;re not then just skip the appropriate parts.</p>
<p>This package also has <a href="https://github.com/tymondesigns/jwt-auth/wiki">great documentation available</a> that you&#8217;re advised to read through to make sure you set it up in a way that works for you but the few steps below will get you started</p>
<pre># Install Tymon JWT-Auth
composer require tymon/jwt-auth</pre>
<p>Add the JWTAuth Service provider to the providers section in <code>config/app.php</code>:</p>
<pre>Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,</pre>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.37.21.png" rel="attachment wp-att-467"><img loading="lazy" decoding="async" class="alignnone size-medium wp-image-467" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.37.21-300x87.png" alt="Screen Shot 2016-03-06 at 19.37.21" width="300" height="87" srcset="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.37.21-300x87.png 300w, https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.37.21.png 367w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>Add the JWTAuth facade to the aliases section in <code>config/app.php</code></p>
<pre>'JWTAuth' =&gt; 'Tymon\JWTAuth\Facades\JWTAuth',</pre>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.37.28.png" rel="attachment wp-att-468"><img loading="lazy" decoding="async" class="alignnone size-medium wp-image-468" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.37.28-300x95.png" alt="Screen Shot 2016-03-06 at 19.37.28" width="300" height="95" srcset="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.37.28-300x95.png 300w, https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.37.28.png 369w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<pre># Publish the JWTAuth config file
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
# Generate JWT Auth secret key
php artisan jwt:generate</pre>
<p>Now that the JWT Auth and API packages are installed, we need to configure the API to use JWT for it&#8217;s authentication method.  Luckily this can be done very easily in the API config file located in <code>config/api.php</code></p>
<p>Find the following section:</p>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.42.42.png" rel="attachment wp-att-469"><img loading="lazy" decoding="async" class="alignnone size-medium wp-image-469" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.42.42-300x159.png" alt="Original API Auth Configuration" width="300" height="159" srcset="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.42.42-300x159.png 300w, https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.42.42.png 467w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>And add the following within the auth array:</p>
<pre>'jwt' =&gt; 'Dingo\Api\Auth\Provider\JWT',</pre>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.44.56.png" rel="attachment wp-att-470"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-470" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.44.56.png" alt="Dingo API using JWT Auth" width="277" height="64" /></a></p>
<pre>git add .
git commit -a -m "JWT auth package installed"</pre>
<h3><strong>Using JSON API</strong></h3>
<p>JSON API is a standard for APIs that use JSON data and has been the default adapter setting in Ember since version 2.0.  In order to make the API return JSON API formatted data we just need to configure Dingo API to use the JsonApiSerializer that it comes bundled with.</p>
<p>in <code>app/Providers/AppServiceProvider.php</code></p>
<p>First add the following use statements:</p>
<pre>use Dingo\Api\Transformer\Adapter\Fractal;
use Illuminate\Support\ServiceProvider;
use League\Fractal\Manager;
use League\Fractal\Serializer\JsonApiSerializer;</pre>
<p>Add the following to the boot() method within this service provider:</p>
<pre>// API uses JSON API
$this-&gt;app['Dingo\Api\Transformer\Factory']-&gt;setAdapter(function ($app) {
     $fractal = new Manager();
     $fractal-&gt;setSerializer(new JsonApiSerializer());
     return new Fractal($fractal);
});</pre>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.54.05.png" rel="attachment wp-att-471"><img loading="lazy" decoding="async" class="alignnone size-medium wp-image-471" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.54.05-300x270.png" alt="Dingo API JSON API serializer" width="300" height="270" srcset="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.54.05-300x270.png 300w, https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-19.54.05.png 511w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<pre>git add .
git commit -a -m "API uses JSON API serializer"</pre>
<h3><strong>Setting up the Laravel Router</strong></h3>
<p>Below you&#8217;ll find the template of the Laravel routes file (<code>app/Http/routes.php</code>) that which you can download from my <a href="https://github.com/cubewebsites/laravel-ember-starter/blob/master/laravel/app/Http/routes.php">laravel-ember-starter repo</a></p>
<pre>&lt;?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

// API Routes come first
$api = app('Dingo\Api\Routing\Router');
$api-&gt;version('v1',function($api){
    header('Access-Control-Allow-Origin: http://localhost:4200');
    header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE');

    // API
    $api-&gt;group(['namespace'=&gt;'App\Http\Controllers\Api'],function($api){
        // Auth
        $api-&gt;post('auth/login','Auth\AuthController@postLogin');
        $api-&gt;post('auth/token-refresh','Auth\AuthController@refreshToken');
        $api-&gt;post('users','Auth\UsersController@store');

        // Protected methods (require auth)
        $api-&gt;group(['middleware'=&gt;'api.auth'],function($api){
            
        });

        // Public methods
        
    });
});

// Catchall - Displays Ember app
Route::any('{catchall}',function(){
    return view('index');
})-&gt;where('catchall', '(.*)');
</pre>
<p>Few notes on the above routes.php file:</p>
<ol>
<li><code>http://localhost:4200</code> is the default address when using Ember serve to develop your app</li>
<li>All the API requests are handled first</li>
<li>All non-API requests are caught by the final catch all rule, which returns the index view</li>
<li>The index view will return the Ember application</li>
<li>I prefer to use App\Http\Controllers\Api as my root namespace for API controllers, but you can amend this as necessary</li>
</ol>
<h3><strong>Authentication</strong></h3>
<p>As you can see in the above routes file, we have two Authentication routes:</p>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-21.12.24.png" rel="attachment wp-att-474"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-474" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-21.12.24.png" alt="Laravel JWT Auth Routes" width="422" height="37" srcset="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-21.12.24.png 422w, https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-06-at-21.12.24-300x26.png 300w" sizes="(max-width: 422px) 100vw, 422px" /></a></p>
<p>To implement these methods we&#8217;ll first need to create the <code>app/Http/Controllers/Api/Auth/AuthController.php</code> file and setup the authentication methods</p>
<pre>&lt;?php
namespace app\Http\Controllers\Api\Auth;


use App\Http\Controllers\Controller;
use Dingo\Api\Http\Request;
use Dingo\Api\Routing\Helpers;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class AuthController extends Controller
{

    use Helpers;

    public function postLogin(Request $request)
    {
        // grab credentials from the request
        $credentials = $request-&gt;only('email', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = \JWTAuth::attempt($credentials)) {
                throw new UnauthorizedHttpException("Email address / password do not match");
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            throw new HttpException("Unable to login");
        }

        // all good so return the token
        return $this-&gt;response-&gt;array(compact('token'));
    }

    public function refreshToken(Request $request)
    {
        $token  =   $request-&gt;get('token');
        if(!$token)
        {
            return $this-&gt;response-&gt;errorBadRequest('Token not provided');
        }
        try {
            $token  =   \JWTAuth::refresh($token);
        }
        catch(TokenInvalidException $e) {
            return $this-&gt;response-&gt;errorForbidden('Invalid token provided');
        }
        return $this-&gt;response-&gt;array(compact('token'));
    }

}</pre>
<p>The <code>login</code> method will get the email and password from the request, try to authenticate and then return errors on failure (Dingo handles exceptions) and a token on success<br />
<code>refreshToken</code> gets the token from the request, and then attempts to refresh the token (generating a new token).</p>
<p>Full contents of the controller including traits and use statements can be downloaded from <a href="https://github.com/cubewebsites/laravel-ember-starter/blob/master/laravel/app/Http/Controllers/Api/Auth/AuthController.php">my laravel-ember-starter repo</a></p>
<pre>git add .
git commit -a -m "Added Authentication methods"</pre>
<h3><strong>Laravel Finishing Touches</strong></h3>
<p>In <code>app/Http/Kernel.php</code> comment out or delete the line:</p>
<pre>\App\Http\Middleware\VerifyCsrfToken::class,</pre>
<p>If you want to create a test user (change the credentials to whatever you want) to test your authentication</p>
<pre># Create a dummy user
php artisan tinker
App\User::create(['email'=&gt;'<a class="linkification-ext" title="Linkification: mailto:email@domain.com','password'=" href="mailto:email@domain.com','password'=">email@domain.com','password'=</a>&gt;bcrypt('password')]);
exit</pre>
<pre>git add .
git commit -a -m "Laravel Setup complete"</pre>
<h3>Laravel Summary</h3>
<p>That&#8217;s it with the Laravel setup for now.  Whilst there&#8217;s quite a few steps the idea is quite simple:</p>
<ol>
<li>Install Laravel</li>
<li>Add API support</li>
<li>Add JWT setup</li>
<li>Setup the API to use JSON API</li>
<li>Add authentication methods</li>
</ol>
<h2>Ember Frontend Setup</h2>
<p>Now that the API setup is ready we focus on creating a new Ember project to use as the frontend.</p>
<h3>Initialize Project with Ember-CLI</h3>
<pre># go back up to the project root directory
cd ..
# create a new Ember project called 'frontend'
ember new frontend
# go into the 'frontend' directory
cd frontend
# delete the .git folder created by Ember (in the frontend directory - don't delete the one in your project root)
rm -Rf .git
# add the Ember project to our Git repo
git add .
git commit -a -m "Added Ember project"</pre>
<p>When developing applications I use Vagrant for serving the Laravel app, and the Ember-CLI built in server.  This gives me two URLs:</p>
<ol>
<li><code>http://myapp.local</code> &#8211; which goes to the Laravel application running on Vagrant</li>
<li><code>http://localhost:4200</code> &#8211; the default URL for the Ember application using ember serve</li>
</ol>
<p>For the application to work, we need to make the Ember application aware of the Laravel URL so that we can make API requests to it.  To do this I specify the API url as a config setting in Ember.  In <code>config/environment.js</code> add the following line (replace the URL with your Laravel application URL):</p>
<pre>ENV.apiBaseUrl = 'http://sample-project.local';</pre>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-07-at-12.00.46.png" rel="attachment wp-att-489"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-489" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-07-at-12.00.46.png" alt="Updated Ember environment file" width="467" height="329" srcset="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-07-at-12.00.46.png 467w, https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-07-at-12.00.46-300x211.png 300w" sizes="(max-width: 467px) 100vw, 467px" /></a></p>
<p>You&#8217;ll notice in that config file that there&#8217;s sections where you can specify environment specific settings (e.g. development and production) which means you can set the above option separately for each environment.</p>
<h3>Add Authentication Packages</h3>
<p>For authentication with Ember we&#8217;ll use Ember Simple Auth base package, with Ember Simple Auth Token since we need JWT support.</p>
<pre># Install Ember Simple Auth
ember install ember-simple-auth
# Install Ember Simple Auth Token
ember install ember-simple-auth-token</pre>
<p>Then to configure the Auth packages add the following to config/environment.js:</p>
<pre>ENV['ember-simple-auth'] = {
  authorizer: 'authorizer:token'
};
ENV['ember-simple-auth-token'] = {
  refreshAccessTokens: true,
  timeFactor: 1000,
  refreshLeeway: 300,
  serverTokenEndpoint: ENV.apiBaseUrl + '/api/auth/login',
  serverTokenRefreshEndpoint: ENV.apiBaseUrl + '/api/auth/token-refresh',
  identificationField: 'email'
};</pre>
<p><a href="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-07-at-18.43.25.png" rel="attachment wp-att-506"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-506" src="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-07-at-18.43.25.png" alt="Ember Simple Auth Token Configuration" width="450" height="241" srcset="https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-07-at-18.43.25.png 450w, https://cubewebsites.com/wp-content/uploads/2016/03/Screen-Shot-2016-03-07-at-18.43.25-300x161.png 300w" sizes="(max-width: 450px) 100vw, 450px" /></a><br />
You can update the options to suit your requirements if necessary</p>
<h3>Login</h3>
<pre># generate the login route
ember g route login</pre>
<p>Create a simple form in the login template <code>app/templates/login.hbs</code></p>
<pre>{{#if errorMessage}}
    {{errorMessage}}
{{/if}}
&lt;form {{action 'authenticate' on='submit'}}&gt;
  &lt;label for="identification"&gt;Login&lt;/label&gt;
  {{input id='identification' placeholder='Enter Login' value=identification}}
  &lt;label for="password"&gt;Password&lt;/label&gt;
  {{input id='password' placeholder='Enter Password' type='password' value=password}}
  &lt;button type="submit"&gt;Login&lt;/button&gt;
&lt;/form&gt;</pre>
<p>Make the route available only when the user isn&#8217;t logged in, and clear the errors when the user goes to a different page by editing the login route file in <code>app/routes/login.js</code></p>
<pre>import Ember from 'ember';
import UnauthenticatedRouteMixin from 'ember-simple-auth/mixins/unauthenticated-route-mixin';

export default Ember.Route.extend(UnauthenticatedRouteMixin,{
    resetController(controller,isExiting)
    {
        if(isExiting){
            controller.set('errorMessage', '');
        }
    }
});</pre>
<pre># Create the login controller
ember generate controller login</pre>
<p>Handle authentication attempts in the login controller <code>app/controllers/login.js</code></p>
<pre>import Ember from 'ember';

export default Ember.Controller.extend({
  session: Ember.inject.service(),

  actions: {
    authenticate: function() {
      var credentials = this.getProperties('identification', 'password'),
        authenticator = 'authenticator:jwt';

      this.get('session').authenticate(authenticator, credentials).catch((message) =&gt; {
        this.set('errorMessage', message.message);
      });
    }
  }
});</pre>
<h3>Authenticating API Requests</h3>
<p>At this point authentication should be working properly, but we still need to configure Ember to send the token in API requests to access protected endpoints.  In order to do this we&#8217;ll extend the Ember JSON API adapter and configure it to use the Token Authorizer from Ember Simple Auth Token.</p>
<pre># Create the adapter
ember g adapter application</pre>
<p>Update the adapter in <code>app/adapters/application.js</code></p>
<pre>import DS from 'ember-data';
import ENV from 'frontend/config/environment';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin,{
	host: ENV.apiBaseUrl,
	namespace:'api',
	authorizer: 'authorizer:token',
	handleResponse: function(status, headers, payload){
		// If the response is 422 (Unprocessable Entity) then format the errors into JSONAPI format
		if(status === 422 &amp;&amp; payload.errors){
			let error_response	=	[];
			for(var key in payload.errors) {
				error_response.push({id:key,title:payload.errors[key][0]});
			}
			return new DS.InvalidError(error_response);
		}
		return this._super(...arguments);
	}
});</pre>
<p>As well as setting the authorizer the above adapter also sets the following options:</p>
<ol>
<li><code>host</code> &#8211; tells the adapter to make all requests to the apiBaseUrl that we specified in the config</li>
<li><code>namespace</code> &#8211; Use the &#8216;api&#8217; namespace for all requests (to match all the Laravel route structure)</li>
<li><code>handleResponse</code> &#8211; format the errors for 422 errors</li>
</ol>
<h3>Logout</h3>
<p>Logout is an action that can be accessed from any page with the application, so we&#8217;ll handle the logout action in the application controller.</p>
<pre># create application controller
ember g controller application</pre>
<p>Create the invalidateSession method in the application controller: app/controllers/application.js</p>
<pre>import Ember from 'ember';

export default Ember.Controller.extend({
	session: Ember.inject.service('session'),
	actions: {
		invalidateSession() {
			this.get('session').invalidate();
		}
	}
});</pre>
<p>Of course you&#8217;ll want to add the logout link in your application template <code>app/templates/application.hbs</code></p>
<pre>&lt;ul&gt;
    {{#if session.isAuthenticated}}
        &lt;li&gt;&lt;a {{action 'invalidateSession'}}&gt;Logout&lt;/a&gt;&lt;/li&gt;
    {{else}}
        &lt;li&gt;{{#link-to 'login'}}Login{{/link-to}}&lt;/li&gt;
        &lt;li&gt;{{#link-to 'register'}}Register{{/link-to}}&lt;/li&gt;
    {{/if}}
&lt;/ul&gt;</pre>
<pre># git commit
git add .
git commit -a -m "Ember authentication implemented"</pre>
<h3>Registration</h3>
<p>If your application requires user registration then use the steps below, and if you don&#8217;t need registration just comment out the line from backend/app/Http/routes.php:</p>
<pre>$api-&gt;post('users','Auth\UsersController@store');</pre>
<h4>Backend Setup</h4>
<p>We&#8217;ve already defined a route for creating new users in the backend/app/Http/routes.php file:</p>
<pre>$api-&gt;post('users','Auth\UsersController@store');</pre>
<p>The next step is to create a new controller with the Laravel project directory: </p>
<pre># Switch to the 'backend' directory
cd ../backend</pre>
<p>Create <code>app/Http/Controllers/Api/Auth/UsersController.php</code> and populate the store action:</p>
<pre>&lt;?php
/**
 * Created by PhpStorm.
 * User: ash
 * Date: 02/03/2016
 * Time: 10:06
 */

namespace app\Http\Controllers\Api\Auth;


use App\Http\Controllers\Controller;
use App\User;
use Dingo\Api\Exception\StoreResourceFailedException;
use Dingo\Api\Http\Request;
use Dingo\Api\Routing\Helpers;

class UsersController extends Controller
{
    use Helpers;

    public function store(Request $request)
    {
        $data   =   $request-&gt;get('data')['attributes'];
        $validator  =   \Validator::make($data,[
            'email'     =&gt;  'required|email|unique:users',
            'password'  =&gt;  'required'
        ]);
        if($validator-&gt;fails()){
            throw new StoreResourceFailedException('Invalid user data',$validator-&gt;errors());
        }
        User::create(['email'=&gt;$data['email'],'password'=&gt;bcrypt($data['password'])]);
        return $this-&gt;response-&gt;noContent();
    }
}</pre>
<p>The submitted data is validated, and detailed errors returned if validation fails. Otherwise we send back a success response with no content, which the Ember app will use to notify the user that registration is successful and that they can now login</p>
<p>The next step is to create a registration route and a user model:</p>
<pre># Switch back to the 'frontend' directory
cd ../frontend
ember g route register
ember g model user email:string password:string</pre>
<p>Setup the registration template in <code>app/templates/register.hbs</code></p>
<pre>{{#if registered}}
    &lt;h1&gt;Registered!&lt;/h1&gt;
    &lt;p&gt;Registration was successful.  You can {{link-to 'now login' 'login'}} with the credentials you registered with.&lt;/p&gt;
{{else}}
{{#if errorMessage}}
    {{errorMessage}}
{{/if}}
&lt;form {{action 'register' on='submit'}}&gt;
    &lt;p&gt;Create a New Account&lt;/p&gt;
    &lt;label for="identification"&gt;Email&lt;/label&gt;
    {{input id='identification' placeholder='Email Address' value=model.email type='email'}}
    &lt;label for="password"&gt;Password&lt;/label&gt;
    {{input id='password' placeholder='Enter Password' type='password' value=model.password}}
    &lt;button type="submit"&gt;Register&lt;/button&gt;
&lt;/form&gt;
{{/if}}</pre>
<p>The registration route needs a couple of updates to make it accessible to unauthenticated users, and to clear the error messages when the user leaves the page so update <code>app/routes/register.js</code></p>
<pre>import Ember from 'ember';
import UnauthenticatedRouteMixin from 'ember-simple-auth/mixins/unauthenticated-route-mixin';

export default Ember.Route.extend(UnauthenticatedRouteMixin,{
    model() {
      return this.store.createRecord('user');
    },
    resetController(controller,isExiting)
    {
        if(isExiting){
            controller.get('model').rollbackAttributes();
            controller.set('errorMessage', '');
        }
    }
});</pre>
<p>Handle registration attempts in the register controller: <code>app/controllers/register.js</code></p>
<pre># Create the register controller
ember g controller register</pre>
<pre>import Ember from 'ember';

export default Ember.Controller.extend({
    session: Ember.inject.service(),
    registered: false,
    actions: {
        register(){
            let self = this;
            this.get('model').save().then(()=&gt;{
                self.set('registered',1);
            }).catch((error)=&gt;{
                this.set('errorMessage',"Registration failed.");
            });
        }
    }
});
</pre>
<h3>Setup Complete</h3>
<p>That concludes the setup for the project. You have working logins and registration, a JSON API with authenticated routes and an Ember application ready for your custom code.</p>
<h3>Deployments</h3>
<p>You might have noticed that during the Laravel setup we setup a catchall route that returns an index view but we didn&#8217;t actually create the view. This is because it&#8217;s not required during development &#8211; we use Ember serve to load our Ember application instead.</p>
<p>Once you&#8217;re ready to deploy your project to production or staging you&#8217;ll need to build the Ember application and copy across the files into the Laravel public directory. I&#8217;ve created a simple script that I use for staging (and a similar script for production deployments). The idea is to have a production branch in the Git repo which is deployed on the server.</p>
<p>You can use the script below and modify it to suit your needs:</p>
<pre># create the publish-staging script
touch publish-staging.sh
# make the publish script executable
chmod a+x publish-staging.sh</pre>
<p>Set the contents of the publish script <code>publish-staging.sh</code></p>
<pre>#!/usr/bin/env bash

# PUBLISH STAGING

# make sure we're in the master branch
git checkout master
git add .
git commit -a -m "Pre-publish commit"
git push
# switch to staging branch
git checkout staging
# merge master into staging
git merge master
# build the Ember application
cd frontend &amp;&amp; ember build --environment staging &amp;&amp; cd ..;
# clear public
rm -Rf backend/public/assets;
rm -Rf backend/public/fonts;
rm -Rf backend/public/index.html;
rm -Rf backend/public/crossdomain.xml;
# copy the new Ember build into the Laravel application
cp -R frontend/dist/assets backend/public
cp -R frontend/dist/fonts backend/public
cp -R frontend/dist/index.html backend/resources/views/index.blade.php
cp -R frontend/dist/crossdomain.xml backend/public
# git commit
git add .
git commit -a -m "Fresh Staging build"
git push origin staging

# switch back to master
git checkout master</pre>
<p>This publish script goes in the project root and just make sure you stop your ember server before running it to prevent conflicts. The other thing to be aware of is uncommitted changes &#8211; as you can see the script above will switch to master and commit all uncommitted changes, which will cause problems if you&#8217;re currently working on a feature branch with uncommitted changes.</p>
<h2>Summary</h2>
<p>That&#8217;s a pretty full on guide to setting up a project that uses a Laravel backend and Ember as the frontend. Once complete you can get on with the meat and bones of the application.</p>
<h2>Code Availability</h2>
<p>You can find the files created and used within this application in <a href="https://github.com/cubewebsites/laravel-ember-starter" target="_blank">my laravel-ember-starter project repo</a>. If you like I can make the whole sample app available on Github so that you can have everything served to you without having to work through all the steps yourself. I&#8217;m reluctant to do this upfront as there&#8217;s a lot going on in the tutorial and I&#8217;d advise you to read through and understand what&#8217;s going on and make any neccessary changes as you see fit.</p>
<p>Feel free to leave comments and suggestions for improvements in the discussion area below.</p>
<p>The post <a href="https://cubewebsites.com/development/ember/getting-started-laravel-ember/">Getting Started With Laravel and Ember</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/development/ember/getting-started-laravel-ember/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>[GUIDE] Find and Replace Markdown Image URLs in PHP</title>
		<link>https://cubewebsites.com/development/php/guide-find-and-replace-markdown-image-urls-in-php/</link>
					<comments>https://cubewebsites.com/development/php/guide-find-and-replace-markdown-image-urls-in-php/#respond</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Mon, 29 Feb 2016 21:40:55 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[laravel]]></category>
		<category><![CDATA[markdown]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[regex]]></category>
		<guid isPermaLink="false">https://cubewebsites.com/?p=453</guid>

					<description><![CDATA[<p>The Code // Inline Style Images $content = preg_replace_callback('/!\[(.*)\]\s?\((.*)(.png&#124;.gif&#124;.jpg&#124;.jpeg)(.*)\)/',function($match){ return str_replace('your_search_term','your_replacement',$match[0]); },$content); // Reference Style Images $content = preg_replace_callback('/\[(.*)\]:\s?(.*)(.png&#124;.gif&#124;.jpg&#124;.jpeg)/',function($match){ return str_replace('your_search_term','your_replacement',$match[0]); },$content); Why Would You Need This? I had to use the above code in a Laravel project where the content is entered into a frontend form in Markdown format. When saving the data in [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/development/php/guide-find-and-replace-markdown-image-urls-in-php/">[GUIDE] Find and Replace Markdown Image URLs in PHP</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>The Code</strong></p>
<pre>// Inline Style Images
$content    =   preg_replace_callback('/!\[(.*)\]\s?\((.*)(.png|.gif|.jpg|.jpeg)(.*)\)/',function($match){
    return str_replace('your_search_term','your_replacement',$match[0]);
},$content);

// Reference Style Images
$content    =   preg_replace_callback('/\[(.*)\]:\s?(.*)(.png|.gif|.jpg|.jpeg)/',function($match){
    return str_replace('your_search_term','your_replacement',$match[0]);
},$content);</pre>
<p><strong>Why Would You Need This?</strong></p>
<p>I had to use the above code in a Laravel project where the content is entered into a frontend form in Markdown format.  When saving the data in my Laravel backend app I wanted to replace the image URL with a placeholder so that the sites URL itself isn&#8217;t hardcoded into the database.  When displaying the data, the placeholder is replaced with the URL of the site again.  This means that if the URL ever changes (different dev environment, staging, production etc) then the images would still load providing that the files still existed in the same location on the server.</p>
<p>Your use case might be different but the above regex should provide you with a decent starting point to actually find the image tags (both inline and reference style) and then manipulate them however you wish.</p>
<p>The post <a href="https://cubewebsites.com/development/php/guide-find-and-replace-markdown-image-urls-in-php/">[GUIDE] Find and Replace Markdown Image URLs in PHP</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/development/php/guide-find-and-replace-markdown-image-urls-in-php/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>FIX: Telegram Webhooks Not Working</title>
		<link>https://cubewebsites.com/guides/fix-telegram-webhooks-not-working/</link>
					<comments>https://cubewebsites.com/guides/fix-telegram-webhooks-not-working/#comments</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Sat, 04 Jul 2015 11:40:35 +0000</pubDate>
				<category><![CDATA[Guides]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[nginx]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[telegram]]></category>
		<guid isPermaLink="false">http://www.cubewebsites.com/blog/?p=438</guid>

					<description><![CDATA[<p>Telegram messenger recently released an API that lets you easily create bots for their platform.  After deciding to have a bit of a play with it, I found that I had an issue where the webhooks would not send any updates to my server with no apparent error. The Problem I made all the following [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/guides/fix-telegram-webhooks-not-working/">FIX: Telegram Webhooks Not Working</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Telegram messenger recently released an API that lets you easily create bots for their platform.  After deciding to have a bit of a play with it, I found that I had an issue where the webhooks would not send any updates to my server with <em>no apparent error.</em></p>
<p><strong>The Problem</strong></p>
<p>I made all the following checks:</p>
<ol>
<li>Valid SSL certificate</li>
<li>Webhook successfully registered using the Telegram setWebhook method</li>
<li>The method responded properly when I sent a test request using a REST service tester</li>
<li>Server access logs &#8211; look like Telegram had never even hit the server</li>
</ol>
<p><strong>The Solution</strong></p>
<p>After a full day of searching, testing and bashing my head against the keyboard, I found <a href="https://www.reddit.com/r/Telegram/comments/3b4z1k/bot_api_recieving_nothing_on_a_correctly/csjmj8y">this thread</a> on Reddit, where the user described a problem where a full chained certificate was required on the server, not just the server certificate.</p>
<p>To create chained certificate you&#8217;ll need to have a look at what instructions your certificate issuer provides.</p>
<p>In my case the certificate being used was a Comodo PositiveSSL, for which I downloaded all the certificates that they sent, which contained:</p>
<ul>
<li>Root CA Certificate &#8211; AddTrustExternalCARoot.crt</li>
<li>Intermediate CA Certificate &#8211; COMODORSAAddTrustCA.crt</li>
<li>Intermediate CA Certificate &#8211; COMODORSADomainValidationSecureServerCA.crt</li>
<li>Your PositiveSSL Certificate &#8211; my_domain.crt</li>
</ul>
<p>I had to combine them all into a file in the following order:</p>
<ul>
<li>my_domain.crt</li>
<li>COMODORSADomainValidationSecureServerCA.crt</li>
<li>COMODORSAAddTrustCA.crt</li>
<li>AddTrustExternalCARoot.crt</li>
</ul>
<p>For the example above the command would have been:</p>
<pre>cat my_domain.crt COMODORSADomainValidationSecureServerCA.crt AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt &gt; bundle.crt</pre>
<p>After that it was just a case of uploading the new bundle.crt to my server, updating the nginx config, and hey presto, within minutes I was receiving all the responses for my webhooks</p>
<p>The post <a href="https://cubewebsites.com/guides/fix-telegram-webhooks-not-working/">FIX: Telegram Webhooks Not Working</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/guides/fix-telegram-webhooks-not-working/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>FREEBIE: Concrete5 Testimonials Package</title>
		<link>https://cubewebsites.com/development/php/freebie-concrete5-testimonials-package/</link>
					<comments>https://cubewebsites.com/development/php/freebie-concrete5-testimonials-package/#respond</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Mon, 27 Aug 2012 11:29:49 +0000</pubDate>
				<category><![CDATA[Concrete5]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[concrete5]]></category>
		<category><![CDATA[freebie]]></category>
		<category><![CDATA[package]]></category>
		<category><![CDATA[php]]></category>
		<guid isPermaLink="false">http://www.cubewebsites.com/blog/?p=416</guid>

					<description><![CDATA[<p>Hi folks, I&#8217;m back with another freebie for you.  This time it&#8217;s a Concrete5 package that lets you create, manage and display testimonials on your website. The following fields are available to you: Title Author Department Quote URL Display Order When adding a block you can choose specific testimonials to display, or display all. Additionally, [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/development/php/freebie-concrete5-testimonials-package/">FREEBIE: Concrete5 Testimonials Package</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p style="text-align: center;"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-417" title="icon" src="http://www.cubewebsites.com/blog/wp-content/uploads/2012/08/icon.png" alt="" width="97" height="97" /></p>
<p style="text-align: left;">Hi folks, I&#8217;m back with another freebie for you.  This time it&#8217;s a Concrete5 package that lets you create, manage and display testimonials on your website.</p>
<p>The following fields are available to you:</p>
<ul>
<li>Title</li>
<li>Author</li>
<li>Department</li>
<li>Quote</li>
<li>URL</li>
<li>Display Order</li>
</ul>
<p>When adding a block you can choose specific testimonials to display, or display all. Additionally, you can sort by display order, or in a random order.</p>
<p><strong>Requirements</strong></p>
<p>All you need is a Concrete5 website running on 5.5.0 or greater.</p>
<p><strong>Usage</strong></p>
<p>You can find full documentation on the <a href="https://github.com/cubewebsites/c5-testimonials" target="_blank">Github page</a></p>
<p><strong>License</strong></p>
<p>It&#8217;s totally free and open-source so you can do whatever you like with it!  It&#8217;s quite easy to adapt into a management system for any other kind of object like people, books or even managing your own movie database.</p>
<p><strong>Screenshots</strong></p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-418 alignnone" title="Screen Shot 2012-08-27 at 12.11.24" src="http://www.cubewebsites.com/blog/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.11.24.png" alt="" width="566" height="216" srcset="https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.11.24.png 566w, https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.11.24-300x114.png 300w, https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.11.24-500x190.png 500w" sizes="(max-width: 566px) 100vw, 566px" /></p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-419 alignnone" title="Screen Shot 2012-08-27 at 12.11.50" src="http://www.cubewebsites.com/blog/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.11.50.png" alt="" width="443" height="367" srcset="https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.11.50.png 443w, https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.11.50-300x248.png 300w, https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.11.50-362x300.png 362w" sizes="(max-width: 443px) 100vw, 443px" /></p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-420" title="Screen Shot 2012-08-27 at 12.12.16" src="http://www.cubewebsites.com/blog/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.16.png" alt="" width="952" height="344" srcset="https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.16.png 952w, https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.16-300x108.png 300w, https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.16-500x180.png 500w" sizes="(max-width: 952px) 100vw, 952px" /></p>
<p><a href="http://www.cubewebsites.com/blog/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.30.png"><img loading="lazy" decoding="async" class="alignnone size-medium wp-image-421" title="Screen Shot 2012-08-27 at 12.12.30" src="http://www.cubewebsites.com/blog/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.30-300x171.png" alt="" width="300" height="171" srcset="https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.30-300x171.png 300w, https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.30-500x285.png 500w, https://cubewebsites.com/wp-content/uploads/2012/08/Screen-Shot-2012-08-27-at-12.12.30.png 953w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p style="text-align: left;"><strong>Download</strong></p>
<p style="text-align: left;">I&#8217;ve submitted the package to the Marketplace and will update this post will a link once it&#8217;s live.  In the meantime you can download from Github.</p>
<p style="text-align: left;"><a href="https://github.com/cubewebsites/c5-testimonials" target="_blank">Download here</a></p>
<p style="text-align: left;"><strong>Support</strong></p>
<p style="text-align: left;">If you have any issues or feature requests please get in touch via the comments, <a href="http://twitter.com/cubewebsites" target="_blank">Twitter</a>, or email</p>
<p>The post <a href="https://cubewebsites.com/development/php/freebie-concrete5-testimonials-package/">FREEBIE: Concrete5 Testimonials Package</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/development/php/freebie-concrete5-testimonials-package/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Baobab: PHP/MySQL Library For The Nested Set Model</title>
		<link>https://cubewebsites.com/development/php/baobab-phpmysql-library-for-nested-set-model/</link>
					<comments>https://cubewebsites.com/development/php/baobab-phpmysql-library-for-nested-set-model/#comments</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Fri, 30 Dec 2011 21:58:02 +0000</pubDate>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[nested set]]></category>
		<category><![CDATA[open-source]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://www.cubewebsites.com/blog/?p=326</guid>

					<description><![CDATA[<p>Introduction When working with databases, you may want a table structure which allows your record to have a parent record (heirachical recordset).  In simple scenarios it&#8217;s easy enough to simply have a parent_id column. However, for displaying the entire tree you&#8217;ll need a lot of recursion to go through all the top level nodes, test [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/development/php/baobab-phpmysql-library-for-nested-set-model/">Baobab: PHP/MySQL Library For The Nested Set Model</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>When working with databases, you may want a table structure which allows your record to have a parent record (heirachical recordset).  In simple scenarios it&#8217;s easy enough to simply have a parent_id column. However, for displaying the entire tree you&#8217;ll need a lot of recursion to go through all the top level nodes, test for children, and then test the children for children etc.  It soon proves to be very long-winded and inefficient.</p>
<p>Instead of using the standard parent_id approach, there&#8217;s a database structure known as the <strong>Nested Set Model</strong>.  The nested set model uses an algorithm which basically uses tree traversal to number each node, and once the numbering is complete it becomes very easy to query the tree and search, whether its for root nodes (base node), leaf nodes (nodes with no children) or branches (the path from the root node to a particular node).</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-327" title="nestedset" src="http://www.cubewebsites.com/blog/wp-content/uploads/2011/12/nestedset.jpg" alt="" width="633" height="300" srcset="https://cubewebsites.com/wp-content/uploads/2011/12/nestedset.jpg 633w, https://cubewebsites.com/wp-content/uploads/2011/12/nestedset-300x142.jpg 300w, https://cubewebsites.com/wp-content/uploads/2011/12/nestedset-500x236.jpg 500w" sizes="(max-width: 633px) 100vw, 633px" /></p>
<p><strong>Performance</strong></p>
<p>As the tree traversal for numbering the nodes is required, the Nested Set Model requires slightly more overhead when updating the table (each node needs to be renumbered when a change is made), but as mentioned earlier, is very efficient when it comes to actually querying the table.</p>
<p><strong>Example Usage Scenario</strong></p>
<p>A simple use for Nested Set Model would be a category table for a website, where categories can have subcategories.  And even subcategories can have subcategories.  Categories are generally setup in the admin on most sites, and even then are rarely updated so the fact that updating a Nested Set can be a bit slow isn&#8217;t actually a issue.  On the frontend the visitors and customers will simply be viewing categories, so they&#8217;ll be reaping the benefits of the efficiency and great performance of the Nested Set Model.</p>
<p><strong>Introducing Baobab</strong></p>
<p><a href="http://www.sideralis.org/baobab/index.html">Baobab</a> is a free PHP/MySQL implementation of the Nested Set Model.  It can be modified to work with other database systems too.  Baobab uses the Nested Set Model, but also the offers the advantage of supporting multiple trees in the same table, or alternatively you can setup different trees in individual tables, depending on your requirements.</p>
<p>It takes an Object-Oriented approach (OOP) and provides you with an entire API of useful methods including:</p>
<ul>
<li>getRoot()</li>
<li>appendChild()</li>
<li>getTreeHeight()</li>
<li>deleteNode()</li>
</ul>
<p>Just take a look at the <a href="http://www.sideralis.org/baobab/api.html">documentation page</a> to see how much Baobab has to offer.</p>
<p><strong>Download and Install</strong></p>
<p>Getting started with Baobab is dead simple.  It&#8217;s an open-source project hosted on GitHub which you can <a href="https://github.com/riquito/Baobab/downloads">download here</a>.  Once you&#8217;ve got the code it&#8217;s a simple case of placing the classes wherever you need them, include them in your PHP and use the <a href="http://www.sideralis.org/baobab/example_animals.html">Simple Tree Example</a> to get started.  If you&#8217;re more confident then you can have a look at the <a href="http://www.sideralis.org/baobab/example_forum.html">Multiple Tree Example</a>.</p>
<p><a href="https://github.com/riquito/Baobab">Baobab on GitHub</a></p>
<p><strong>Conclusion</strong></p>
<p>I&#8217;ve found Baobab particularly useful in my projects and have extended it to tie in with my own PHP library.  It offers you the power of using nested sets, without requiring you to code your own implementation of nested.  There&#8217;s a lot of useful functions in there, plus the default SQL structure can easily be extended to contain your own table fields too.</p>
<p>It&#8217;s great, it&#8217;s free and if you need to hold data in a tree structure then it&#8217;s certainly worth checking out.</p>
<p>The post <a href="https://cubewebsites.com/development/php/baobab-phpmysql-library-for-nested-set-model/">Baobab: PHP/MySQL Library For The Nested Set Model</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/development/php/baobab-phpmysql-library-for-nested-set-model/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>HOW TO: Disable Deprecated Function Notices in PHP</title>
		<link>https://cubewebsites.com/development/php/how-to-disable-deprecated-function-notices-in-php/</link>
					<comments>https://cubewebsites.com/development/php/how-to-disable-deprecated-function-notices-in-php/#comments</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Wed, 20 Oct 2010 15:04:46 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[depracation notice]]></category>
		<category><![CDATA[error reporting]]></category>
		<guid isPermaLink="false">http://www.cubewebsites.com/blog/?p=251</guid>

					<description><![CDATA[<p>Here&#8217;s a quick tip on how to disable notices like this one appearing on your site: Deprecated: Function eregi() is deprecated in&#8230; At the top of your application (bootstrap or index file) just add the following line of PHP: This tells your application to show all errors EXCEPT for Notices and Deprecation errors.  Obviously you [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/development/php/how-to-disable-deprecated-function-notices-in-php/">HOW TO: Disable Deprecated Function Notices in PHP</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Here&#8217;s a quick tip on how to disable notices like this one appearing on your site:</p>
<blockquote><p><strong>Deprecated</strong>:  Function eregi() is deprecated in&#8230;</p></blockquote>
<p>At the top of your application (bootstrap or index file) just add the following line of PHP:</p>
<pre class="brush: php; title: ; notranslate">error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);</pre>
<p>This tells your application to show all errors EXCEPT for Notices and Deprecation errors.  Obviously you can show Notices if you prefer by removing &amp; ~E_NOTICE from that function</p>
<p>Hope this helps!</p>
<p>The post <a href="https://cubewebsites.com/development/php/how-to-disable-deprecated-function-notices-in-php/">HOW TO: Disable Deprecated Function Notices in PHP</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/development/php/how-to-disable-deprecated-function-notices-in-php/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>HOW TO: Catch PHP Errors and Warnings</title>
		<link>https://cubewebsites.com/development/php/how-to-catch-php-errors-and-warnings/</link>
					<comments>https://cubewebsites.com/development/php/how-to-catch-php-errors-and-warnings/#respond</comments>
		
		<dc:creator><![CDATA[Cube Websites]]></dc:creator>
		<pubDate>Thu, 02 Sep 2010 08:14:53 +0000</pubDate>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[error handler]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[warnings]]></category>
		<guid isPermaLink="false">http://www.cubewebsites.com/blog/?p=192</guid>

					<description><![CDATA[<p>This morning I was faced with an issue with SwiftMailer where the PHP code was throwing an error message as it failed to connect with the mail server. To solve it I first thought of using a try/catch, but obviously that wouldn&#8217;t work due to the fact that the function only throws a Warning, not [&#8230;]</p>
<p>The post <a href="https://cubewebsites.com/development/php/how-to-catch-php-errors-and-warnings/">HOW TO: Catch PHP Errors and Warnings</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>This morning I was faced with an issue with SwiftMailer where the PHP code was throwing an error message as it failed to connect with the mail server.</p>
<p>To solve it I first thought of using a try/catch, but obviously that wouldn&#8217;t work due to the fact that the function only throws a Warning, not an Exception.</p>
<p>The solution was quite straight forward&#8230;</p>
<ol>
<li>Create a custom error handler, to gracefully capture the warning and display a custom message</li>
<li>Set the custom error handler before attempting to call the function causing the warning (in this case it was fsockopen)</li>
<li>Reset the error handler to the default PHP one after calling the function.</li>
</ol>
<p>Here&#8217;s an example of an error handler function you can use.  I&#8217;m using Smarty for my output, but you can send your output to the users browser in any way you wish.</p>
<pre class="brush: php; title: ; notranslate">
function errorHandler($errno,$errmsg,$errfile) {		
	   	//email yourself the error message and code
	   	$email	=	&quot;An error {$erro} occured on page &quot;.$_SERVER&#x5B;'REQUEST_URI'].&quot;, in the file {$errfile}.\r\n\r\nThe error is shown below:\r\n{$errmsg}&quot;;
	   	mail(&quot;email@domain.com&quot;,&quot;PHP Error Notification&quot;,$email);
	   	
	   	//output a friendly message for the user	
	   	$wrapper	=	new SmartyTemplate(); 
	   	$msg		=	&quot;Thank  you for your message.  Unfortunately we have been unable to send your email, please go back and resubmit the form or call us on 0800 123 456 directly.  Sorry for any inconvenience caused&quot;;   	
	   	$wrapper-&gt;assign(&quot;content&quot;, $msg);   		
	   	$wrapper-&gt;display(&quot;display_wrapper.tpl&quot;);
		exit();		
	}
</pre>
<p>The next step is to set our new error handler before the call to the function that causes the warning.  As mentioned, my issue was with fsockopen in in SwiftMailer, but the fix is the same for anything.  Here&#8217;s how I did it in Swift.<br />
find the offending function (in Swift/Transport/StreamBuffer.php)</p>
<pre class="brush: php; title: ; notranslate">if(!$this-&gt;_stream = fsockopen($host, $this-&gt;_params&#x5B;'port'], $errno, $errstr, $timeout)) {</pre>
<p>and add set the error handler before it.</p>
<pre class="brush: php; title: ; notranslate">set_error_handler(&quot;errorHandler&quot;);
    if(!$this-&gt;_stream = fsockopen($host, $this-&gt;_params&#x5B;'port'], $errno, $errstr, $timeout)) { </pre>
<p>As I only want my error handler to run for that particular function, and not for every function in the entire site, I just have to make sure I remove my custom error handler after the function.<br />
Just add this after your function:</p>
<pre class="brush: php; title: ; notranslate">restore_error_handler();</pre>
<p>Which will cause PHP to revert to it&#8217;s normal error handling method once it&#8217;s gotten back your function.</p>
<p><strong>Extras</strong><br />
My usage of error handling was very specific to a single function.  Of course you can have a site wide error handler instead which gracefully handles every PHP error/warning/notice within a single function.  You could just declare the function a common file and then handle each kind of error independently.  The PHP website has a great example of this:</p>
<pre class="brush: php; title: ; notranslate">
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() &amp; $errno)) {
        // This error code is not included in error_reporting
        return;
    }

    switch ($errno) {
    case E_USER_ERROR:
        echo &quot;&lt;b&gt;My ERROR&lt;/b&gt; &#x5B;$errno] $errstr&lt;br /&gt;\n&quot;;
        echo &quot;  Fatal error on line $errline in file $errfile&quot;;
        echo &quot;, PHP &quot; . PHP_VERSION . &quot; (&quot; . PHP_OS . &quot;)&lt;br /&gt;\n&quot;;
        echo &quot;Aborting...&lt;br /&gt;\n&quot;;
        exit(1);
        break;

    case E_USER_WARNING:
        echo &quot;&lt;b&gt;My WARNING&lt;/b&gt; &#x5B;$errno] $errstr&lt;br /&gt;\n&quot;;
        break;

    case E_USER_NOTICE:
        echo &quot;&lt;b&gt;My NOTICE&lt;/b&gt; &#x5B;$errno] $errstr&lt;br /&gt;\n&quot;;
        break;

    default:
        echo &quot;Unknown error type: &#x5B;$errno] $errstr&lt;br /&gt;\n&quot;;
        break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}
</pre>
<p>It would be quite easy to tweak that function so that it emailed you a log of the error (and/or stored it in the DB) and then redirected the user to a nice looking page notifying them that there&#8217;s an error, but you&#8217;re aware of it.</p>
<p>The post <a href="https://cubewebsites.com/development/php/how-to-catch-php-errors-and-warnings/">HOW TO: Catch PHP Errors and Warnings</a> appeared first on <a href="https://cubewebsites.com">Cube Websites</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://cubewebsites.com/development/php/how-to-catch-php-errors-and-warnings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
