I need to run some Magento code from PHP file in nearby directory. So I created a file, lets call it test.php:

include_once '/var/www/html/app/Mage.php';

$product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'some-sku-123');

echo $product->getProductUrl();

When I open it from browser correct product URL is printed - http://example.com/product123.html.

But when I execute this PHP file from command line via php path/to/test.php, such URL is printed: test.php/product123.html.

What's even more strange, is that previously it was working correctly, and I can't find what change did I make.

So my question is how to make sure that correct URL is printed when executed from command line?

Thank you.

edit: Mage::getBaseUrl() also returns incorrect value - test.php/.


Magento doesn't know in which context you are, therefore I would assume no base_url is set.

Try to set a context with:

Mage::app($code = '', $type = 'store')
  • Thank you for reply, but it doesn't help. The same URL is printed (test.php/). Here is the exact code that I'm using gist.github.com/anonymous/9921b161b1354f8ae858 – Marvin3 Mar 4 '15 at 12:35
  • Ok, so I just ran command service httpd restart to restart apache, and ran php test.php again and it worked correctly (even with Mage::app();). Very weird. – Marvin3 Mar 4 '15 at 12:44
  • ... and 3 minutes later it stopped working again :/ gist.github.com/anonymous/151f8d72e6f1ec737a64 – Marvin3 Mar 4 '15 at 12:49
  • this is weird. No idea. Time to use xdebug and check what is happening. Does magento find the right store, loads the right config... – Fabian Blechschmidt Mar 4 '15 at 12:55
  • I gave up and just decided to use wget instead of CLI php to execute php file. – Marvin3 Mar 4 '15 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.