First and last day of the month in PHP
I've been working with dates today and i've found a pretty neat snippet to show the first and the last day of the month using php
$firstDoM = date("Y-m-01"); //01 -> first day of month
$lastDoM = date("Y-m-t"); //t -> last day of month
Force IE to use the latest engine
If by some unknown reason IE8/9/10 are rendering your site in compatibility mode, ie IE7 mode or something lame like that, just force it to use the latest engine available:
<?php if (using_ie()) {header("X-UA-Compatible: IE=Edge"); ?><meta http-equiv="X-UA-Compatible" content="IE=Edge"/><?php } ?><!DOCTYPE html>
note that the code added right before the doctype declaration. the using_ie() boolean function below (credits to Simeon for this solution: http://www.php.net/manual/en/function.get-browser.php#101314)
function using_ie()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$ub = False;
if(preg_match('/MSIE/i',$u_agent))
{
$ub = True;
}
return $ub;
}
Magento get all products
Here is an easy way to return all the products from a magento store.
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
foreach ($collection as $product) {
echo $product->getName() . "<br />";
}
HTTP response headers in Zend Framework
I needed to display a Zend Framework generated PDF using the browser plugins and after a bit of looking around it turns out that some headers need to be set in order to achieve that.
$this->getResponse()
->setHeader('Content-Disposition', 'inline; filename=invoice.pdf')
->setHeader('Content-type', 'application/x-pdf');
If you'd want to automatically download the PDF instead of displaying it using the browser plugins, you need to change the 'Content-Disposition' as follows:
$this->getResponse()
->setHeader('Content-Disposition', 'attachment; filename=invoice.pdf')
->setHeader('Content-type', 'application/x-pdf');
Switch layouts in Zend Framework
If you have a larger Zend Framework application, you probably want to you use a layout for more of your pages. For instance you'd need at least two layouts: one for a backend and another one for frontend. In order to tell ZF to use layouts, you'll need to set the layout paths in your application.ini
In order to store the layouts in /application/layouts/scripts, add the following to /application/configs/application.ini
resources.layout.layoutpath = APPLICATION_PATH "/layouts/scripts"
You can now create several layouts, something around this model:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php echo $this->headTitle() ?>
<?php echo $this->headScript() ?>
<?php echo $this->headStyle() ?>
</head>
<body>
<?php echo $this->render('header.phtml') ?>
<div id="content"><?php echo $this->layout()->content ?></div>
<?php echo $this->render('footer.phtml') ?>
</body>
</html>
By default, your application will use the layout in /application/layouts/scripts/layout.phtml, but if you want some pages to be rendered using another layout you can tell ZF to do so like this:
// Within controller
// note that the file that's going to be rendered is /application/layouts/scripts/backend.phtml
$this->_helper->_layout->setLayout('backend')
//Within view script
$this->layout()->setLayout('other-layout'); ?>
More info on using Zend_Layout: http://framework.zend.com/manual/en/zend.layout.quickstart.html
Password protect a folder in Apache using .htaccess
mkdir -p /home/secure/ htpasswd -c /home/secure/apasswords developer chown apache:apache /home/secure/apasswords chmod 0660 /home/secure/apasswords
then in your htaccess add these:
AuthType Basic AuthName "Restricted Access" AuthUserFile /home/secure/apasswords Require user developer
FIX: Sites not working in IE7, IE8 CO
Recently I had to fix a site that was not being displayed correctly in IE8. Turned out that some of the DOM was written by Javascript, and IE8 on client's machine was not displaying parts of the page. At first i was not able to replicate the issue on a clean XP SP3, with IE8, but then after i disabled javascript i got the same effect as the client. Thought the solution was easy, assumed the client has JS disabled, but it turns out JS was enabled.
After closer investigation, the only difference between my IE8 and client's IE8 was a CO, installed using IEAK8 (corporate shit) and it had by default native XMLHTTP disabled. Translated: jQuery was assuming the browser is IE6.
To fix this issue, enable XMLHTTP in IE7, or IE8
1. Open IE8 2. Go to Tools -> Internet Options -> Advanced 3. make sure "Enable native XMLHTTP support" is checked 4. Save
Heroku on Ubuntu
As everything that comes from ruby world, getting heroku running on Ubuntu is not as easy as we're used to (ie: apt-get install heroku) so there are a few steps that need to be followed. I've written this down so i can come back to it later and so that others don't lose hours trying to figure this out. The data on this article has been scraped from http://www.web2linux.com/05/installing-rails-3-on-ubuntu-10-04-lucid-lynx/ and http://devcenter.heroku.com/articles/quickstart
Installing dependencies
sudo apt-get install curl git-core build-essential zlib1g-dev libssl-dev libreadline5-dev
Install rvm
#for latest, check https://rvm.beginrescueend.com/ bash <
Install ruby-1.9.2
rvm install 1.9.2 && rvm use 1.9.2 --default
Then add this line as the last line in your .bashrc:
if [[ -s "$HOME/.rvm/scripts/rvm" ]];
then source "$HOME/.rvm/scripts/rvm";
fi
Install Heroku
Sign-up for a Heroku account if you haven’t already and then install the herokugem.
gem install heroku
You will be asked to enter your Heroku credentials the first time you run a command; after the first time, your email address and an API token will be saved to ~/.heroku/credentials for future use.
It’s generally a good idea to add your public key immediately after installing the heroku gem so that you can use git to push or clone Heroku app repositories:
heroku keys:add Enter your Heroku credentials. Email: joe@example.com Password: Uploading ssh public key /Users/joe/.ssh/id_rsa.pub
Track your application with Git
If you’re already using Git with your application, skip to the next step. If you’re not yet using Git to track your application, run this:
cd PATH/TO/MY_APP git init # Initialized empty Git repository in .git/ git add . git commit -m "new app" Created initial commit 5df2d09: new app 44 files changed, 8393 insertions(+), 0 deletions(-)
Create your Heroku application
At the command line, run heroku create. The first time you do this, you’ll be asked to enter your Heroku credentials. Once you do, your email address and an API token will be saved to ~/.heroku/credentials, so you won’t have to provide them again.
This first use will also upload your public SSH key so you’ll be able to push and pull code.
heroku create Enter your Heroku credentials. Email: joe@example.com Password: Uploading ssh public key /Users/joe/.ssh/id_rsa.pub Created http://high-sunrise-58.heroku.com/ | git@heroku.com:high-sunrise-58.git Git remote heroku added
The last line shows the name of your new Heroku app; in this case, it’s “high-sunrise-58”, and is available at http://high-sunrise-58.heroku.com. If you were to visit that URL before pushing your application code (either by typing it in or running heroku open), you’d see a standard Heroku welcome page.
On the next to last line, there’s another important piece of information: git@heroku.com:high-sunrise-58.git. This is the Git repository address for your new Heroku app, and if you check the output of git remote show heroku you can see that the heroku gem added it as a remote for you automatically.
Push your application to Heroku
git push heroku master
Counting objects: 65, done.
Compressing objects: 100% (58/58), done.
Writing objects: 100% (65/65), 80.54 KiB, done.
Total 65 (delta 14), reused 0 (delta 0)
-----> Heroku receiving push
-----> Rails app detected
Compiled slug size is 0.1MB
-----> Launching....... done
App deployed to Heroku
To git@heroku.com:high-sunrise-58.git
* [new branch] master -> master
Bootstrap your database
Your app is now running on Heroku with an empty database. Depending on your framework, run the appropriate command to set up your DB. For Ruby on Rails, run:
heroku rake db:migrate (in /mnt/home/slugs/41913_b81cc1e5813c58c443e4120aff984d006f36ef20/mnt) == 20081118092504 CreateWidgets: migrating ==================================== -- create_table(:widgets) -> 0.0519s == 20081118092504 CreateWidgets: migrated (0.0520s) ===========================
That’s it, your app is now running on Heroku! You can take a look at it in your default web browser by running heroku open.
Next Steps
Now that your application is running, it’s easy to push updates:
Develop and test changes locally.
Commit code to git.
Push your changes to Heroku with git push heroku.
Remove MS Word formatting using PHP regular expressions
Recently i've had a client which would only paste into the CMS text from MS Word. Normally a JS should have been in place to automatically strip the crazy tags Word adds, but on this project this was not the case. Here's hos to remove MS Word formatting using PHP regular expressions:
// it will remove all <!--[if ...]>....<![endif]--> comments
preg_replace('/<!--\[if[^\]]*]>.*?<!\[endif\]-->/i', '', $string);
or
// it will remove all <!--[if ...]>.... --> comments
preg_replace('/<!--\[if[^\]]*]>.*?-->/i', '', $string);
Redirect entire site to another domain, excluding folder
A site i've built for a campaign needed to be redirected to another site as the campaign expired, but one folder in the domain needed still to be accessible. htaccess to the rescue:
RewriteEngine on
RewriteRule !^uploads($|/) http://example.com%{REQUEST_URI} [L,R=301]
This rule does match any URL path that does not begin with either /uploads or /uploads/ (leading / is missing in the pattern due to the path prefix removal when used in .htaccess files) and redirects the request to the corresponding path at example.com.