<p>For running Craft from the console you just need to copy all the content of /directory/toCraft/app/index.php to another file, called what you want. </p>

<p>Comment the last instruction </p>

<pre><code>$app-&gt;run();
</code></pre>

<p>and finally add this instructions in the beginning of the file:</p>

<pre><code>$_SERVER['DOCUMENT_ROOT']   = '/some/path/to/craft.dev';
$_SERVER['HTTP_HOST']       = 'craft.dev';
$_SERVER['HTTPS']           = 'off';
$_SERVER['PHP_SELF']        = '/index.php';
$_SERVER['REQUEST_URI']     = '/index.php';
$_SERVER['SERVER_PORT']     = 80;
$_SERVER['SCRIPT_FILENAME'] = '/some/path/to/craft.dev/index.php';
$_SERVER['SCRIPT_NAME']     = '/index.php';

$_SERVER['HTTP_USER_AGENT']     = 'Super User Agent';
$_SERVER['REMOTE_ADDR']     = 1;
</code></pre>

<p>this doesn't do nothing especial, just emulate a connection</p>

CC BY-SA 3.0
2014-07-21T19:59:07.667Z
2014-07-21T19:59:07.667Z
jhon
<p>I get the Craft loaded with another application on PHP and I try to create a Entry, no problems deleting and getting the entries but when I try to create a new one Craft doesn't show me anything, and also doesn't create an Entry. </p>

<p>The problem is, when I run some "file.php" from the console in order to create a new Entry the error appears, so if I wanna load all the dependencies, I need a Http request.</p>

<p>But I want to create an Entry by console.</p>

<p>I set YII_DEBUG on false and this message appear: </p>

<blockquote>
  <p>Notice: Undefined property: Craft\WebApp::$userSession in /Applications/MAMP/htdocs/craft/craft/app/etc/templating/twigextensions/CraftTwigExtension.php on line 350</p>
</blockquote>

<p>Here's an example:</p>

<pre class="lang-php prettyprint-override"><code>$entry = new \Craft\EntryModel(); 

$entry-&gt;sectionId  = 2; 
$entry-&gt;typeId     = 2; 
$entry-&gt;authorId   = 1; 
$entry-&gt;enabled    = true;

$entry-&gt;getContent()-&gt;setAttributes(array(     
    'title' =&gt; "Console Entrie 1!",     
    'body'  =&gt; "&lt;p&gt;I can’t believe I literally just called this “Hello World!”.&lt;/p&gt;" 
)); 

$success = \Craft\craft()-&gt;entries-&gt;saveEntry($entry);
</code></pre>

<p>My bootstrap file:</p>

<pre class="lang-php prettyprint-override"><code>// Make sure this is PHP 5.3 or later
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID &lt; 50300)
{
    exit('Craft requires PHP 5.3.0 or later, but you&amp;rsquo;re running '.PHP_VERSION.'. Please talk to your host/IT department about upgrading PHP or your server.');
}

/**
 * Quit early if this is just an omitScriptNameInUrls or usePathInfo test request
 */

// Is this a script name redirect test?
if ((isset($_SERVER['PATH_INFO']) &amp;&amp; $_SERVER['PATH_INFO'] == '/testScriptNameRedirect')
    || (isset($_SERVER['QUERY_STRING']) &amp;&amp; strpos($_SERVER['QUERY_STRING'], 'testScriptNameRedirect') !== false))
{
    exit('success');
}

// Is this a PATH_INFO test?
if (isset($_SERVER['PATH_INFO']) &amp;&amp; $_SERVER['PATH_INFO'] == '/testPathInfo')
{
    exit('success');
}

/**
 * Path constants and validation
 */

// We're already in the app/ folder, so let's use that as the starting point.
// Make sure it doesn't look like we're on a network share that starts with \\
$appPath = realpath(dirname(__FILE__));
if (isset($appPath[0]) &amp;&amp; isset($appPath[1]))
{
    if ($appPath[0] !== '\\' &amp;&amp; $appPath[1] !== '\\')
    {
        $appPath = str_replace('\\', '/', $appPath);
    }
}

$_SERVER['DOCUMENT_ROOT']   = '/some/path/to/craft.dev';
$_SERVER['HTTP_HOST']       = 'craft.dev';
$_SERVER['HTTPS']           = 'off';
$_SERVER['PHP_SELF']        = '/index.php';
$_SERVER['REQUEST_URI']     = '/index.php';
$_SERVER['SERVER_PORT']     = 80;
$_SERVER['SCRIPT_FILENAME'] = '/some/path/to/craft.dev/index.php';
$_SERVER['SCRIPT_NAME']     = '/index.php';

//define('YII_ENABLE_EXCEPTION_HANDLER', false);
//define('YII_ENABLE_ERROR_HANDLER', false);
// define('YII_DEBUG', true);

defined('CRAFT_APP_PATH') || define('CRAFT_APP_PATH', $appPath.'/');

// The app/ folder goes inside craft/ by default, so work backwards from app/
defined('CRAFT_BASE_PATH') || define('CRAFT_BASE_PATH', realpath(CRAFT_APP_PATH.'..').'/');

// Everything else should be relative from craft/ by default
defined('CRAFT_CONFIG_PATH')       || define('CRAFT_CONFIG_PATH',       CRAFT_BASE_PATH.'config/');
defined('CRAFT_PLUGINS_PATH')      || define('CRAFT_PLUGINS_PATH',      CRAFT_BASE_PATH.'plugins/');
defined('CRAFT_STORAGE_PATH')      || define('CRAFT_STORAGE_PATH',      CRAFT_BASE_PATH.'storage/');
defined('CRAFT_TEMPLATES_PATH')    || define('CRAFT_TEMPLATES_PATH',    CRAFT_BASE_PATH.'templates/');
defined('CRAFT_TRANSLATIONS_PATH') || define('CRAFT_TRANSLATIONS_PATH', CRAFT_BASE_PATH.'translations/');

function craft_createFolder($path)
{
    // Code borrowed from IOHelper...
    if (!is_dir($path))
    {
        $oldumask = umask(0);

        if (!mkdir($path, 0755, true))
        {
            exit('Tried to create a folder at '.$path.', but could not.');
        }

        // Because setting permission with mkdir is a crapshoot.
        chmod($path, 0755);
        umask($oldumask);
    }
}

function craft_ensureFolderIsReadable($path, $writableToo = false)
{
    $realPath = realpath($path);

    // !@file_exists('/.') is a workaround for the terrible is_executable()
    if ($realPath === false || !is_dir($realPath) || !@file_exists($realPath.'/.'))
    {
        exit (($realPath !== false ? $realPath : $path).' doesn\'t exist or isn\'t writable by PHP. Please fix that.');
    }

    if ($writableToo)
    {
        if (!is_writable($realPath))
        {
            exit ($realPath.' isn\'t writable by PHP. Please fix that.');
        }
    }
}

// Validate permissions on craft/config/ and craft/storage/
craft_ensureFolderIsReadable(CRAFT_CONFIG_PATH);
craft_ensureFolderIsReadable(CRAFT_STORAGE_PATH, true);

// Create the craft/storage/runtime/ folder if it doesn't already exist
craft_createFolder(CRAFT_STORAGE_PATH.'runtime/');
craft_ensureFolderIsReadable(CRAFT_STORAGE_PATH.'runtime/', true);

/**
 * Load the config
 */

// Set the environment
defined('CRAFT_ENVIRONMENT') || define('CRAFT_ENVIRONMENT', $_SERVER['SERVER_NAME']);

// We need to special case devMode in the config because YII_DEBUG has to be set as early as possible.
$devMode = false;
$generalConfigPath = CRAFT_CONFIG_PATH.'general.php';

if (file_exists($generalConfigPath))
{
    $generalConfig = require $generalConfigPath;

    if (is_array($generalConfig))
    {
        // Normalize it to a multi-environment config
        if (!array_key_exists('*', $generalConfig))
        {
            $generalConfig = array('*' =&gt; $generalConfig);
        }

        // Loop through all of the environment configs, figuring out what the final word is on Dev Mode
        foreach ($generalConfig as $env =&gt; $envConfig)
        {
            if ($env == '*' || strpos(CRAFT_ENVIRONMENT, $env) !== false)
            {
                if (isset($envConfig['devMode']))
                {
                    $devMode = $envConfig['devMode'];
                }
            }
        }
    }
}

if ($devMode)
{
    error_reporting(E_ALL &amp; ~E_STRICT);
    ini_set('display_errors', 1);
    defined('YII_DEBUG') || define('YII_DEBUG', true);
    defined('YII_TRACE_LEVEL') || define('YII_TRACE_LEVEL', 3);
}
else
{
    error_reporting(0);
    ini_set('display_errors', 0);
    defined('YII_DEBUG') || define('YII_DEBUG', false);
}

/**
 * Load Yii, Composer dependencies, and the app
 */

// Load Yii, if it's not already
if (!class_exists('Yii', false))
{
    require CRAFT_APP_PATH.'framework/yii.php';
}

// Guzzle makes use of these PHP constants, but they aren't actually defined in some compilations of PHP
// See http://it.blog.adclick.pt/php/fixing-php-notice-use-of-undefined-constant-curlopt_timeout_ms-assumed-curlopt_timeout_ms/
defined('CURLOPT_TIMEOUT_MS')        || define('CURLOPT_TIMEOUT_MS',        155);
defined('CURLOPT_CONNECTTIMEOUT_MS') || define('CURLOPT_CONNECTTIMEOUT_MS', 156);

// Load up Composer's files
require CRAFT_APP_PATH.'vendor/autoload.php';

// Disable the PHP include path
Yii::$enableIncludePath = false;

// Load 'em up
require CRAFT_APP_PATH.'Craft.php';
require CRAFT_APP_PATH.'etc/web/WebApp.php';
require CRAFT_APP_PATH.'Info.php';

// Set some aliases for Craft::import()
Yii::setPathOfAlias('app', CRAFT_APP_PATH);
Yii::setPathOfAlias('plugins', CRAFT_PLUGINS_PATH);

// Load the full config
$config = require CRAFT_APP_PATH.'etc/config/main.php';

// Initialize Craft\WebApp this way so it doesn't cause a syntax error on PHP &lt; 5.3
$appClass = '\Craft\WebApp';
$app = new $appClass($config);

//$app-&gt;run();`
</code></pre>

CC BY-SA 3.0
2014-07-14T22:57:08.413Z
Hi @jhon and welcome to the Craft CMS Stack Exchange site! Could you explain what you mean by "I get the Craft loaded with another application on PHP"? You might want to start by checking `craft/storage/runtime/logs` for anything suspicious.
Matt Stein
CC BY-SA 3.0
2014-07-14T23:19:42.397Z
Hi, I mean [this](http://craftcms.stackexchange.com/questions/608/bootstrap-craft-from-another-app), I load just the core of Craft, and use the Api functions.
jhon
CC BY-SA 3.0
2014-07-14T23:37:21.697Z
CraftTwigExtension shouldn’t be getting loaded if you’re just loading Craft and calling `Craft\craft()->entries->saveEntry()`. Can you please post all of your code?
Brandon Kelly
CC BY-SA 3.0
2014-07-14T23:53:42.367Z
@jhon I edited your original question with the examples from your comments. Please fix anything I might have messed up!
Matt Stein
CC BY-SA 3.0
2014-07-15T00:12:29.277Z
Is any of that code (starting with `$entry = new \Craft\EntryModel();`) actually getting called? Can you post the code you’re using to actually load Craft? That “bootstrap file” is just setting some server variables; not actually loading Craft.
Brandon Kelly
CC BY-SA 3.0
2014-07-15T00:48:32.767Z
i can get the Entries, also I can delete them using this code: `\Craft\craft()->entries->deleteEntryById($entryId);` why doesn't the saveEntry() work?
jhon
CC BY-SA 3.0
2014-07-15T15:06:25.053Z
At the end I used other option, working with a craft Http service, what makes load all the dependencies of Craft, without problems.
jhon
CC BY-SA 3.0
2014-07-16T01:15:30.357Z
@jhon Please consider adding your answer to this question if you think it might benefit others!
Matt Stein
<entry-type><bootstrap-craft>
Problems creating an entry using app()->entries->saveEntry()
# Problems creating an entry using app()->entries->saveEntry()

(Asked by: username_0 on 2014-07-14)

I get the Craft loaded with another application on PHP and I try to create a Entry, no problems deleting and getting the entries but when I try to create a new one Craft doesn't show me anything, and also doesn't create an Entry. 
The problem is, when I run some "file.php" from the console in order to create a new Entry the error appears, so if I wanna load all the dependencies, I need a Http request.
But I want to create an Entry by console.
I set YII_DEBUG on false and this message appear: 

Notice: Undefined property: Craft\WebApp::$userSession in /Applications/MAMP/htdocs/craft/craft/app/etc/templating/twigextensions/CraftTwigExtension.php on line 350

Here's an example:
$entry = new \Craft\EntryModel(); 

$entry->sectionId  = 2; 
$entry->typeId     = 2; 
$entry->authorId   = 1; 
$entry->enabled    = true;

$entry->getContent()->setAttributes(array(     
    'title' => "Console Entrie 1!",     
    'body'  => "I can’t believe I literally just called this “Hello World!”." 
)); 

$success = \Craft\craft()->entries->saveEntry($entry);

My bootstrap file:
// Make sure this is PHP 5.3 or later
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300)
{
    exit('Craft requires PHP 5.3.0 or later, but you’re running '.PHP_VERSION.'. Please talk to your host/IT department about upgrading PHP or your server.');
}

/**
 * Quit early if this is just an omitScriptNameInUrls or usePathInfo test request
 */

// Is this a script name redirect test?
if ((isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] == '/testScriptNameRedirect')
    || (isset($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'testScriptNameRedirect') !== false))
{
    exit('success');
}

// Is this a PATH_INFO test?
if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] == '/testPathInfo')
{
    exit('success');
}

/**
 * Path constants and validation
 */

// We're already in the app/ folder, so let's use that as the starting point.
// Make sure it doesn't look like we're on a network share that starts with \\
$appPath = realpath(dirname(__FILE__));
if (isset($appPath[0]) && isset($appPath[1]))
{
    if ($appPath[0] !== '\\' && $appPath[1] !== '\\')
    {
        $appPath = str_replace('\\', '/', $appPath);
    }
}

$_SERVER['DOCUMENT_ROOT']   = '/some/path/to/craft.dev';
$_SERVER['HTTP_HOST']       = 'craft.dev';
$_SERVER['HTTPS']           = 'off';
$_SERVER['PHP_SELF']        = '/index.php';
$_SERVER['REQUEST_URI']     = '/index.php';
$_SERVER['SERVER_PORT']     = 80;
$_SERVER['SCRIPT_FILENAME'] = '/some/path/to/craft.dev/index.php';
$_SERVER['SCRIPT_NAME']     = '/index.php';

//define('YII_ENABLE_EXCEPTION_HANDLER', false);
//define('YII_ENABLE_ERROR_HANDLER', false);
// define('YII_DEBUG', true);

defined('CRAFT_APP_PATH') || define('CRAFT_APP_PATH', $appPath.'/');

// The app/ folder goes inside craft/ by default, so work backwards from app/
defined('CRAFT_BASE_PATH') || define('CRAFT_BASE_PATH', realpath(CRAFT_APP_PATH.'..').'/');

// Everything else should be relative from craft/ by default
defined('CRAFT_CONFIG_PATH')       || define('CRAFT_CONFIG_PATH',       CRAFT_BASE_PATH.'config/');
defined('CRAFT_PLUGINS_PATH')      || define('CRAFT_PLUGINS_PATH',      CRAFT_BASE_PATH.'plugins/');
defined('CRAFT_STORAGE_PATH')      || define('CRAFT_STORAGE_PATH',      CRAFT_BASE_PATH.'storage/');
defined('CRAFT_TEMPLATES_PATH')    || define('CRAFT_TEMPLATES_PATH',    CRAFT_BASE_PATH.'templates/');
defined('CRAFT_TRANSLATIONS_PATH') || define('CRAFT_TRANSLATIONS_PATH', CRAFT_BASE_PATH.'translations/');

function craft_createFolder($path)
{
    // Code borrowed from IOHelper...
    if (!is_dir($path))
    {
        $oldumask = umask(0);

        if (!mkdir($path, 0755, true))
        {
            exit('Tried to create a folder at '.$path.', but could not.');
        }

        // Because setting permission with mkdir is a crapshoot.
        chmod($path, 0755);
        umask($oldumask);
    }
}

function craft_ensureFolderIsReadable($path, $writableToo = false)
{
    $realPath = realpath($path);

    // !@file_exists('/.') is a workaround for the terrible is_executable()
    if ($realPath === false || !is_dir($realPath) || !@file_exists($realPath.'/.'))
    {
        exit (($realPath !== false ? $realPath : $path).' doesn\'t exist or isn\'t writable by PHP. Please fix that.');
    }

    if ($writableToo)
    {
        if (!is_writable($realPath))
        {
            exit ($realPath.' isn\'t writable by PHP. Please fix that.');
        }
    }
}

// Validate permissions on craft/config/ and craft/storage/
craft_ensureFolderIsReadable(CRAFT_CONFIG_PATH);
craft_ensureFolderIsReadable(CRAFT_STORAGE_PATH, true);

// Create the craft/storage/runtime/ folder if it doesn't already exist
craft_createFolder(CRAFT_STORAGE_PATH.'runtime/');
craft_ensureFolderIsReadable(CRAFT_STORAGE_PATH.'runtime/', true);

/**
 * Load the config
 */

// Set the environment
defined('CRAFT_ENVIRONMENT') || define('CRAFT_ENVIRONMENT', $_SERVER['SERVER_NAME']);

// We need to special case devMode in the config because YII_DEBUG has to be set as early as possible.
$devMode = false;
$generalConfigPath = CRAFT_CONFIG_PATH.'general.php';

if (file_exists($generalConfigPath))
{
    $generalConfig = require $generalConfigPath;

    if (is_array($generalConfig))
    {
        // Normalize it to a multi-environment config
        if (!array_key_exists('*', $generalConfig))
        {
            $generalConfig = array('*' => $generalConfig);
        }

        // Loop through all of the environment configs, figuring out what the final word is on Dev Mode
        foreach ($generalConfig as $env => $envConfig)
        {
            if ($env == '*' || strpos(CRAFT_ENVIRONMENT, $env) !== false)
            {
                if (isset($envConfig['devMode']))
                {
                    $devMode = $envConfig['devMode'];
                }
            }
        }
    }
}

if ($devMode)
{
    error_reporting(E_ALL & ~E_STRICT);
    ini_set('display_errors', 1);
    defined('YII_DEBUG') || define('YII_DEBUG', true);
    defined('YII_TRACE_LEVEL') || define('YII_TRACE_LEVEL', 3);
}
else
{
    error_reporting(0);
    ini_set('display_errors', 0);
    defined('YII_DEBUG') || define('YII_DEBUG', false);
}

/**
 * Load Yii, Composer dependencies, and the app
 */

// Load Yii, if it's not already
if (!class_exists('Yii', false))
{
    require CRAFT_APP_PATH.'framework/yii.php';
}

// Guzzle makes use of these PHP constants, but they aren't actually defined in some compilations of PHP
// See http://it.blog.adclick.pt/php/fixing-php-notice-use-of-undefined-constant-curlopt_timeout_ms-assumed-curlopt_timeout_ms/
defined('CURLOPT_TIMEOUT_MS')        || define('CURLOPT_TIMEOUT_MS',        155);
defined('CURLOPT_CONNECTTIMEOUT_MS') || define('CURLOPT_CONNECTTIMEOUT_MS', 156);

// Load up Composer's files
require CRAFT_APP_PATH.'vendor/autoload.php';

// Disable the PHP include path
Yii::$enableIncludePath = false;

// Load 'em up
require CRAFT_APP_PATH.'Craft.php';
require CRAFT_APP_PATH.'etc/web/WebApp.php';
require CRAFT_APP_PATH.'Info.php';

// Set some aliases for Craft::import()
Yii::setPathOfAlias('app', CRAFT_APP_PATH);
Yii::setPathOfAlias('plugins', CRAFT_PLUGINS_PATH);

// Load the full config
$config = require CRAFT_APP_PATH.'etc/config/main.php';

// Initialize Craft\WebApp this way so it doesn't cause a syntax error on PHP < 5.3
$appClass = '\Craft\WebApp';
$app = new $appClass($config);

//$app->run();`

**Tags:** entry-type, bootstrap-craft

> **Comments:**
> **username_1**: Hi @username_0 and welcome to the Craft CMS Stack Exchange site! Could you explain what you mean by "I get the Craft loaded with another application on PHP"? You might want to start by checking `craft/storage/runtime/logs` for anything suspicious.  
> **username_0**: Hi, I mean [this](http://craftcms.stackexchange.com/questions/608/bootstrap-craft-from-another-app), I load just the core of Craft, and use the Api functions.  
> **username_2**: CraftTwigExtension shouldn’t be getting loaded if you’re just loading Craft and calling `Craft\craft()->entries->saveEntry()`. Can you please post all of your code?  
> **username_1**: @username_0 I edited your original question with the examples from your comments. Please fix anything I might have messed up!  
> **username_2**: Is any of that code (starting with `$entry = new \Craft\EntryModel();`) actually getting called? Can you post the code you’re using to actually load Craft? That “bootstrap file” is just setting some server variables; not actually loading Craft.  
> **username_0**: i can get the Entries, also I can delete them using this code: `\Craft\craft()->entries->deleteEntryById($entryId);` why doesn't the saveEntry() work?  
> **username_0**: At the end I used other option, working with a craft Http service, what makes load all the dependencies of Craft, without problems.  
> **username_1**: @username_0 Please consider adding your answer to this question if you think it might benefit others!  

---

## 1 answers

### Answer by username_0 on 2014-07-21. Score: 3 | Accepted answer

For running Craft from the console you just need to copy all the content of /directory/toCraft/app/index.php to another file, called what you want. 
Comment the last instruction 
$app->run();

and finally add this instructions in the beginning of the file:
$_SERVER['DOCUMENT_ROOT']   = '/some/path/to/craft.dev';
$_SERVER['HTTP_HOST']       = 'craft.dev';
$_SERVER['HTTPS']           = 'off';
$_SERVER['PHP_SELF']        = '/index.php';
$_SERVER['REQUEST_URI']     = '/index.php';
$_SERVER['SERVER_PORT']     = 80;
$_SERVER['SCRIPT_FILENAME'] = '/some/path/to/craft.dev/index.php';
$_SERVER['SCRIPT_NAME']     = '/index.php';

$_SERVER['HTTP_USER_AGENT']     = 'Super User Agent';
$_SERVER['REMOTE_ADDR']     = 1;

this doesn't do nothing especial, just emulate a connection


---

