PHP if else statement- Normal and advanced

Here now I am giving you the normal code example.

$test = 100;

if ( $test == 100 ) {
echo “The if statement evaluated to true”;
} else {
echo “The if statement evaluated to false”;
}

If you want to use this in one line than use following code:

echo $testprint = ( $test == 100 ) ?  “The if statement evaluated to true” : “The if statement evaluated to false”;

This will gives you same output.

Now I am giving you the multiple IF else statment in very short way.

if ( one= true ){
if ( two=true){
echo “one”;
}else{
echo “two”;
}
}else{
echo “nothing”;
}

Short way:

$shortway = (one= true) ? (two=true ) ? “one” : ‘two’ ) : “nothing”;

Use PHP in Rails project

Many times you need to use PHP scripts in Rails project. You will got so much open source PHP scripts for various use.

Example is So many Rails site is using WordPress for blogging system.

Main reason behind using PHP files or script is SEO. PHP is a very SEO friendly.

Customer does not want to spend money or time already existing scripts or program.

If you want to use PHP files or project under Rails project. Just create any folder in Public directory and put your php files in to that folder.

lets say you created the “fourm” dir in public directory.

You need to add following lines in your apache rule file(httpd.conf)

LoadModule proxy_module modules/mod_proxy.so

LoadModule proxy_http_module modules/mod_proxy_http.so

Under <VirtualHost  *:80> tag add following lines:

ProxyRequests Off

RewriteEngine On

RewriteCond  %{HTTP_HOST}    ^example.com [NC]
RewriteCond %{REQUEST_URI}  !^/forum(.*)$ [NC]

RewriteCond  %{HTTP_HOST}    ^example.com [NC]

RewriteRule ^/forum/?(.*)$ /document_root/forum/$1 [QSA,NC,L]

Than you are able to use PHP code or scripts in Rails project

Compress the server response with Nginx

Maybe you aware with apache “mod_gzip and mod deflate”

Compress the server response with Nginx

Web page compression is not a new technology, but it has recently gained higher recognition in the minds of IT administrators and managers because of the rapid ROI it generates. Compression extensions exist for most of the major Web server platforms

For Apache Normally use following syntax:

mod_gzip_item_exclude file \.js$
mod_gzip_item_exclude mime ^text/css$

mod_gzip_item_include file \.html$
mod_gzip_item_include file \.shtml$
mod_gzip_item_include file \.php$
mod_gzip_item_include mime ^text/html$

mod_gzip_item_include file \.txt$
mod_gzip_item_include mime ^text/plain$

mod_gzip_item_include file \.css$
mod_gzip_item_include mime ^text/css$

We used gzip and compressing files technology with various browers. You need following browser support for this.

  • Accept-encoding: gzip
  • Accept-encoding: gzip, deflate

For Nginx i used following code in Nginx.conf file:

# Compression of response time
gzip on;
gzip_buffers 16 8k;
gzip_comp_level 9;
gzip_http_version 1.0;
gzip_min_length 0;
gzip_types text/plain text/html text/css image/x-icon image/png image/jpg image/jpeg text/js text/php;
gzip_vary on;

Install Apatana Studio on Fedora 9

Installation of Apatana in Detail

1. Download zip file from this location(http://www.aptana.com/studio/download)
File name:Aptana_Studio_Setup_Linux_1.2.7.zip
2. Then uncompress the .zip file. and copy the resulting ‘aptana’ folder under ‘/home/siwan’.(siwan is my username for fedora, you have replace your username)
3. Install xulrunner (for install xulrunner user following command, Became root first)
yum install xulrunner
or follow this step
Down load xulrunner from this url
http://releases.mozilla.org/pub/mozilla.org/xulrunner/releases/1.8.1.3/contrib/linux-i686/xulrunner-1.8.1.3.en-US.linux-i686-20080128.tar.gz
Unarchive using file roller to get a ‘xulrunner’ folder.
Open a terminal, and type the following commands, changing the path in the last line ie nigel to your username.
(for install xulrunner user following command, Became root first)

    mkdir /usr/lib/xulrunner
    cp -r /home/nigel/Download/xulrunner/* /usr/lib/xulrunner

4. Create a new file called say ‘aptana.sh’ and make it executable
use this command for make file executable.
Became root user first.
cd /home/siwan/aptana/
chmod +x aptana.sh
5. Copy the following into that text file

#!/bin/sh
MOZILLA_FIVE_HOME=/usr/lib/xulrunner
if [ $LD_LIBRARY_PATH ]; then
LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME:$LD_LIBRARY_PATH
else
LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME
fi
export MOZILLA_FIVE_HOME LD_LIBRARY_PATH
/home/siwan/aptana/AptanaStudio

Then run the aptana.sh file.
Enjoy with Aptana Studio

Easy Steps for setting up nginx with php on Linux

I am using Fedora 10 so for that linux version i used these commands for setting up my server.

Installing Nginx:
yum install nginx

Then we create the system startup links for nginx:
/sbin/chkconfig –level 35 nginx on

We can make PHP5 work in nginx through FastCGI.For that install all this packages:
yum install lighttpd-fastcgi php-cli php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-eaccelerator php-magickwand php-magpierss php-mapserver php-mbstring php-mcrypt php-mhash php-mssql php-shout php-snmp php-soap php-tidy

Then open /etc/php.ini and add the line cgi.fix_pathinfo = 1 right at the end of the file:
vi /etc/php.ini
paste this line :- cgi.fix_pathinfo = 1

To start a PHP FastCGI daemon listening on port 9000 on localhost and running as the user and group nginx, we run the following command:
/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u nginx -g nginx -f /usr/bin/php-cgi -P /var/run/fastcgi-php.pid

To restart PHP FastCGI daemon, Use this command:
ps -ef|grep php-cgi
kill PROCESS_ID

you don’t want to type in that command manually whenever you boot the system, so to have the system execute the command automatically at boot time, open /etc/rc.local…
vi /etc/rc.local
and add the command at the end of the file:
/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u nginx  -g nginx -f /usr/bin/php-cgi -P /var/run/fastcgi-php.pid

THEN STOP THE APACHE WEB SERVER:
/sbin/init.d/httpd stop
To stop apache on every startup:
/sbin/chkconfig –level 35 httpd off

First take backup of your nginx configuration file:
cp /etc/nginx/nginx.conf nginx.conf_cp
use nginx.conf file from life180 “config/nginx” folder

Php Mysql Question and Answers for Interview

What is the difference between PHP4 and PHP5?
PHP4 cannot support oops concepts and Zend engine 1 is used.
PHP5 supports oops concepts and Zend engine 2 is used.
Error supporting is increased in PHP5.
XML and SQLLite will is increased in PHP5.Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?
Yes we can include that many times we want, but here are some things to make sure of:
(including abc.PHP, the file names are case-sensitive)
there shouldn’t be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php

How i can get ip address – REMOTE_ADDR – the IP address of the client
REMOTE_HOST – the host address of the client, if available

What is the difference between echo and print statement? – echo() can take multiple expressions,Print cannot take multiple expressions.
echo has the slight performance advantage because it doesn’t have a return value.
True, echo is a little bit faster.

How we know browser properties -echo $_SERVER[‘HTTP_USER_AGENT’] . “<hr /> “;
$browser = get_browser();
foreach ($browser as $name => $value) {
echo “<b>$name</b> $value <br /> “;
}

How i will check that user is, logged in or not. i want to make it a function and i want to use in each page and after login i want to go in current page(same page. where i was working)

What is difference between require_once(), require(), include(). Becouse above three function usely use to call a file in another file.
Difference between require() and require_once(): require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).
So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don’t include the file more times and you will not get the “function re-declared” error.
Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING.
There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

How do I generate a random number from-php?
srand((double)microtime()*1000000);
echo rand(0,100);

How do I set the browser timeout?
set_time_limit(900);
this sets the timeout too 900 seconds / 15 minutes.

How can I do error handling in php?

Is it possible to connect to a ftp server with php?
Yes it is possible, you can use the ftp_connect function. (PHP 3>= 3.0.13, PHP 4 >= 4.0b4)

How do I find out how a user came to my page?
You have the variable $HTTP_REFERER which holds the page that refered to you page, if there are any referer, ie if the user enters your url directly the referer variable will be empty.

How can I add text to an image?
array imagettftext ( resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text )
how to rotate an image using php code?
$move90 = imagerotate($myimage,90);
//$myimage is the reference to the loaded image, eg through imagecreatefromjpeg

How do I find the size of an array? –use Count function
$values = range(“A”,”Z”);
echo count($values);

How do I remove escape characters from data?
$data = “I\’m the king of the castle”;
echo stripslashes($data); //I’m the king of the castle

What are magic quotes?
Magic quotes is a configuration setting within PHP that means that all data containing a single or double quote, or NUL, will automatically be escaped with a backslash before being entered into a database.

How can we encrypt the username and password using PHP?

What is the difference between $message and $$message?
$message is a simple variable whereas $$message is a reference variable.

What are the differences between DROP a table and TRUNCATE a table?

What’s the difference between md5(), crc32() and sha1() crypto on PHP?
The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.

How to set cookies?
setcookie(’variable’,’value’,’time’)
;

My Suggestions for Google Top ranking

My Suggestions for Google Top ranking

 

Create City wise Sub domains

like pune.yourdomain.com, Mumbai.yourdomain.com

 

in pune.yourdomain.com upload whole website or redirect to our yourdomain.com site

Another way upload whole website but disable only selected means pune city in search criteria.

 

Google collect all website data every week on Sunday. He catches many types of data like meta description, meta keywords, page information, page name, page content. But Google give First preference to website name than WebPages name (page title).

 

That’s why suggested to create simple city wise and favorite category wise sub domains. This is very powerful system which we have implement and improve.

 

Google can catch our sub domains and there different types of data means specialize (city wise and favorite category wise) information of rental activity in that city or that category.

 

This is technically possible anytime. Not so much hard work. No database mismatch or No additional database required. no additional mail required ( but if we create mail like pune@yourdomain.com, Mumbai@yourdomain.com ) this is very better for Google top ranking. Pune rental requirement come on only pune@yourdomain.com

 

Now we hosted our website in Godaddy.com. We can create 10 sub domain in our hosting plan.

 

This is very simple and achieving idea for Google top ranking.

 

Pl read my Search engine Report because we use Php and Mysql Technology in our Web portal. What Google did for data collection and what criteria they use for ranking or listing of website? I read many articles and used many soft wares and programs for Google ranking.

 

I am pretty glad to tell you. I suggested techniques are very helpful for our achievement.

 

This techniques used by many website like

 

(pune.magicbricks.com, pune.indiaproperty.com, realestate.virtualpune.com, apartment. magicbricks.com, pune.click.in, Bharatmatrimonial.com and many more)

 

Search Engine Optimizing PHP Report

 

PHP pages have a reputation of being more difficult (or at least different) to SEO than static HTML pages. Here?s an overview of the major issues encountered when trying to optimize PHP script for search engines. While this focuses on PHP much of it is still relevant to SEO’ing dynamic pages in general.

PHP Speed

While page size does affect load time, spiders run on servers connected to high bandwidth networks, so download time is less important than the latency of the PHP script?s execution time. If a search engine spider follows a link on a site and is forced to wait too long for the server to process the PHP code behind that page, it may label your page as unresponsive.

The biggest delays in a PHP script typically are the database and loop code. Avoid making SELECT * calls, instead explicitly name all the columns you want to retrieve, and if you are using MySQL, test your queries using the EXPLAIN statement. To optimize loops consider using duplicated code instead of loops that don’t repeat very many times, also use as many static values, such as count($array) values inside the loop as you can, generating their values before the loop once.

URL Cleanliness

A major goal in SEO’ing your PHP pages, is to make them look and act like static pages. If you have a large site you can use Apache to fake static looking URLs, or, with a smaller site, you can simply keep your GET variables to a useful minimum. In either case, however, never allow a spider to see links with different URL?s to the same content. If the URL is different, the page should be too.

One of the major problems most webmasters have with getting their dynamic pages to index is URL cleanliness. Since many dynamic pages are created with GET variables, lots of pages have URLs that look like:

Page.php?var=lkdjdfhv&var2=345&var3=kfjdks

Most of the search engines will be able to follow this link, because it has 3 or under get variables (a good rule of thumb is to keep the number of GET variables passed in the URL to under 3), but any more than 3 variables and you will run into problems. Try using less GET variables, and make them more relevant, rather that useless id numbers use titles, and other keyword rich bits of text. This is an example of a better URL:

Page.php?var=category&var2=topic

If the page requires more variables you may want to consider combining the variables by delimiting them with a hyphen or another unused character, and then splitting the variable in the target page.

Disabling Trans_sid

Possibly the biggest cause of webmaster frustration when SEO?ing php pages is PHP?s tendency to add session id numbers to links if cookies are rejected by the browser (Search engine spiders reject cookies). This will happen by default if your PHP installation was compiled with the ?enable-trans-sid option (and this is the default from version 4.2 onward), and it creates links with an additional, long nonsense looking GET variable. In addition to making the links clunky this gives spiders different URLs with the same content, which makes them less likely to treat the pages individually, and possibly not even index them at all. A quick way to fix this is to disable the trans-id feature, if you have access, in php.ini by setting ?session.use_trans_sid? to false. If you don?t have access to change php.ini you can add this line to the .htaccess file in your root directory:

<IfModule mod_php4.c> php_flag session.use_trans_sid off </IfModule>

Masking dymamic URLs

However the mere presence of a question mark in the URL will introduce a delay in google?s indexing of the page. This from Mike Grehan?s Interview with Daniel Dulitz of Google:

?So the mere presence of a question mark in the URL doesn’t throw us for a loop at all. We will crawl those pages more slowly than we do with pages without question marks in the URL. Purely because they’ve identified themselves as being dynamic and we certainly don’t want to bring anyone’s site down because we’re hitting the database too hard.?

Small sites will not need to worry much about this delay as it means your server is hit every few minutes, not a few times a second, but for larger sites this can slow down your site?s inclusion into the index.

Making dynamic pages look static without mod_rewrite

A way to mask bulky dynamic page URLs (and avoid the question mark delay) is Apache?s ForceType in combination with a PHP command to interpret URLs like: www.example.com/books/computers.html as referring to a page called ?books? which is executed as a PHP script (I usually make a link on the linux server from ?books.php? to ?book? to make editing the script easier). The function will return an array of the additional values, including the category ?computers?. This can be accomplished by inserting a line like this into the .htaccess file in the root of your web documents directory:

<Files *Directory Handle Name Here*> ForceType application/x-httpd-php </Files>

*Directory Handle Name Here* should be replaced with the alias name you are giving to the fake directory you are creating. In this example:

www.example.com/books/computers.html

your .htaccess line would look like this:

<Files books>ForceType application/x-httpd-php</Files>

You can then log into your server and create a link to the file ?books? or whatever directory alias you have choosen. This is done with the linux command “ln”, or link, like this:

$ Ln books.php books

This creates a link between the existing PHP script books.php and the non-existant ?books?. This way all requests for the directory “books” will be given to books.php, ie www.example.com/books/computers.html would be handled by books.php

Inside books.php you can use this function (available here) to extract values from the static-looking request URI?s:


<?php
function processURI() {
    $request = explode(“/”,$_SERVER[“REQUEST_URI”]);
    $count = count($request);     
    for ($i = 1 ; $i < $count ; $i++) {              
        $values[“arg”.$i] = $request[$i];   
    }
    return $values;   
}
?>
1

So the above example of: www.example.com/books/computer.html would be processed like this:


<?php
$vals = processURI();
$_GET[$vals[1]] = str_replace(“.html”, “”, $vals[2]);
?>
1

With this, $_GET[‘books’] would equal “computer” similar to www.example.com/index.php?books=computer

PHP?s SEO Advantages

A great advantage to using dynamic pages as opposed to static pages is the ability to create content that is constantly changing and updated in real time. RSS headlines, randomly circulating content and other automatically ?fresh? content can boost your ranks in Google, and many other engines.

Another advantage to using PHP is that you can make simple modifications to many scripts to create relevant and fresh page titles. Since this is the most important on page factor in SEO special attention should be given to creating title tags that accurately reflect the page?s current content. Any html templates or used in PHP pages can be altered to contain this line:

<title><?=$page_title?></title>

With this, $page_title can be set to a keyword rich test describing the page. Title text is also important in improving the click-through from SERP?s, so be sure that the title tags doesn?t read like spam, but more like a human created title.

 

Create breadcrumb in php – PHP Breadcrumb

breadcrumb is useful for every site. here I explained code about Create breadcrumb in php – PHP Breadcrumb. This code will be helpful for website developers.

Create breadcrumb in php – PHP Breadcrumb

What are breadcrumbs?

How to create the breadcrumbs in wordpress
How to create the breadcrumbs in wordpress

Well quite simply, in web page terms this refers to a list of links (usually at the top) that appear on a web page to tell the user where they are in the structure of the website they are viewing. This makes navigating backward and forward so much easier as they have the ability to skip directly back through whole categories, rather than just using the browser’s back button.

Example

The breadcrumbs.php include file:

Copy the code below, save it in a file called breadcrumbs.php and upload it to your site. This will print out a simple unordered list (<ul>) of the parent directories by directory name. The only edits you may wish to make to this file is to change the $ul_id='crumbs'; line if you wish to change the id of the <ul>. If you wish to add a background image or border etc to the <li> simply select it as #crumbs li{} and style. Script for Create breadcrumb in php:

<?
$ul_id='crumbs';
$bc=explode("/",$_SERVER["PHP_SELF"]);
echo '<ul id="'.$ul_id.'"><li><a href="/">Home</a></li>';
while(list($key,$val)=each($bc)){
$dir='';
if($key > 1){
$n=1;
while($n < $key){
$dir.='/'.$bc[$n];
$val=$bc[$n];
$n++;
}
if($key < count($bc)-1) echo '<li><a href="'.$dir.'">'.$val.'</a></li>';
}
}
echo '<li>'.$pagetitle.'</li>';
echo '</ul>';</pre>
?> This is some more usefull code
<pre><?
$url = $_SERVER['REQUEST_URI'];
echo $url;
echo "<br>";
$array = explode("/",$url);
echo $array[2]; ///which folder would you want to access ?
echo "size of array = ".sizeof($array)."<br>";
?>

Use above script for Create breadcrumb in php.

A script to insert in the HTML where you want the breadcrumbs to appear:

Edit the URI to point to where you saved the include file (once this is done it never needs to be changed again). Edit, ‘Insert Page Title’ to add the page title to the end of the breadcrumbs.

<?
$pagetitle="Insert Page Title";
include("http://www.yourdomain.com/breadcrumbs.php");
?>

Note: It would be useful to automatically print the page <title> as the last crumb but PHP cannot interrogate the DOM. Javascript would be required which we didn’t think appropriate as nothing would be returned if Javascript was turned off.

If you are looking for wordpress breadcrumbs then visit this link

wordpress breadcrumbs without any wp plugin

get page name from current url using php

Many people facing this problem for many kind of situations like, get page name from current url using php, Here we given php code for retrieve page name  … create dynamic javascript or css menu..,  navigation,  hit counter… for page..

get page name from current url using php

you can use set variable names for page.  second good way is use this function for print page name $_SERVER[“PHP_SELF”]

or if you want only page name than use this script


<?php

$pagename=pathinfo($_SERVER["PHP_SELF"]);
$pagename=$pagename["basename"];

echo $pagename;

?>

This is some more helpfull code…


$url = $_SERVER['REQUEST_URI'];
echo $url;
echo "<br>";
$array = explode("/",$url);
echo $array[2]; ///which folder would you want to access ?
echo "size of array = ".sizeof($array)."
";

URL unicode is another method for Creating Pretty or Clean Url and creating breadcrumbs