Following is the code for permanent (301) redirect using php.
Better approach is to use .htaccess but there are situations where .htaccess could not be used so using following code might help
@header("HTTP/1.1 301 Moved Permanently");
@header("location: http://www.mywebsite.com");
Additionally if you want to redirect your home page to always open using www. which might be usefull when using cookies or for SEO. Add an if condition to code
if (!preg_match('/www\..*?/', $_SERVER['HTTP_HOST']))
{
@header("HTTP/1.1 301 Moved Permanently");
@header("location: http://www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
}
This website is dedicated to common, day to day programming and database related Frequently Asked Questions. Popular Programming and Database Articles under one blog
Showing posts with label php. Show all posts
Showing posts with label php. Show all posts
Tuesday, July 17, 2012
Wednesday, May 30, 2012
PHP Q&A
1. How many are PHP super global variables?
(a) $_REQUEST
(b) $_POST
(c) $_GET
(d) $_COOKIES
(e) $_SERVER
(f) $_FILES
(g) $_ENV
2. How can we get images properties like type, size, width, height?
For image type we can use exif_imagetype()
Image size use getimagesize()
Image width imagesx()
Image Height imagesy()
3. Get browser properties using PHP?
echo $_SERVER['HTTP_USER_AGENT'];
4. How many ways we can pass data between two pages using php?
(a) Register data in sessions
(b) Use cookies
(c) Pass value as GET or POST
5. How to make a script support multiple languages?
Set charset = UTF-8
6. What is the difference between Echo and Print in PHP?
Echo and print are more or less the same both outputs to the browser.
Difference is print() only takes one argument and returns true on successful printing
Echo is slightly faster than print
7. How to prevent hacking in PHP?
(a) Set Register_globals to OFF to prevent form injection with malicious data
(b) Set Error Reporting to E_ALL to show all error messages
(c) Validate input using htmlentities(), strip_tags(), utf8_decode() & addslashes()
8. What is the difference between Notify URL and Return URL using Paypal?
Notify URL
Notify URL is used by PayPal IPN for sending transaction information
Return URL
The url to which user is returned after successful payment
9. What is ob_start()?
ob_start() turns on the output buffering. When buffering is ON any output sent from server will be stored in a buffer until ob_end() is called or script ends.
It eliminate Headers already sent problem
(a) $_REQUEST
(b) $_POST
(c) $_GET
(d) $_COOKIES
(e) $_SERVER
(f) $_FILES
(g) $_ENV
2. How can we get images properties like type, size, width, height?
For image type we can use exif_imagetype()
Image size use getimagesize()
Image width imagesx()
Image Height imagesy()
3. Get browser properties using PHP?
echo $_SERVER['HTTP_USER_AGENT'];
4. How many ways we can pass data between two pages using php?
(a) Register data in sessions
(b) Use cookies
(c) Pass value as GET or POST
5. How to make a script support multiple languages?
Set charset = UTF-8
6. What is the difference between Echo and Print in PHP?
Echo and print are more or less the same both outputs to the browser.
Difference is print() only takes one argument and returns true on successful printing
Echo is slightly faster than print
7. How to prevent hacking in PHP?
(a) Set Register_globals to OFF to prevent form injection with malicious data
(b) Set Error Reporting to E_ALL to show all error messages
(c) Validate input using htmlentities(), strip_tags(), utf8_decode() & addslashes()
8. What is the difference between Notify URL and Return URL using Paypal?
Notify URL
Notify URL is used by PayPal IPN for sending transaction information
Return URL
The url to which user is returned after successful payment
9. What is ob_start()?
ob_start() turns on the output buffering. When buffering is ON any output sent from server will be stored in a buffer until ob_end() is called or script ends.
It eliminate Headers already sent problem
Friday, December 30, 2011
HTML Printing & Page Breaks
<html> <head> <style> @page { size 8.5in 11in; margin: 2cm } div.page { page-break-after: always } </style> </head> <body> <div class="page">Page 1 Here</div> <div class="page">Page 2 Here</div> </body> </html>
Thursday, December 22, 2011
Optimize Your Site With GZIP Compression
In Apache, enabling output compression is fairly straightforward. Add the following to your .htaccess file:
If you can't change your .htaccess file, you can use PHP to return compressed content. Give your HTML file a .php extension and add this code to the top:
In PHP:
<?php if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start(); ?>
We check the "Accept-encoding" header and return a gzipped version of the file (otherwise the regular version). This is almost like building your own webserver (what fun!). But really, try to use Apache to compress your output if you can help it. You don't want to monkey with your files.
Reference: http://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>
Apache actually has two compression options:- mod_deflate is easier to set up and is standard.
- mod_gzip seems more powerful: you can pre-compress content.
If you can't change your .htaccess file, you can use PHP to return compressed content. Give your HTML file a .php extension and add this code to the top:
In PHP:
<?php if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start(); ?>
We check the "Accept-encoding" header and return a gzipped version of the file (otherwise the regular version). This is almost like building your own webserver (what fun!). But really, try to use Apache to compress your output if you can help it. You don't want to monkey with your files.
Verify Your Compression
Once you've configured your server, check to make sure you're actually serving up compressed content.- Online: Use the online gzip test to check whether your page is compressed.
- In your browser: Use Web Developer Toolbar > Information > View Document Size (like I did for Yahoo, above) to see whether the page is compressed.
- View the headers: Use Live HTTP Headers to examine the response. Look for a line that says "Content-encoding: gzip".
Reference: http://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/
Creating image thumbnails using PHP
Sometimes restricting images size is required. Following function is very useful to create images of certain sizes on the fly
function createThumbs($source, $dest, $requiredWidth, $requiredHeight, $fileType='')
{
$size = getimagesize($source);
$givenWidth = $size[0];
$givenHeight = $size[1];
if ($givenWidth > 800)
{
$requiredRatio = $requiredWidth / $requiredHeight;
$middleWidth = ceil($givenHeight * $requiredRatio);
if($middleWidth>$givenWidth){
$requiredRatio = $requiredHeight / $requiredWidth;
$middleHeight = ceil($givenWidth * $requiredRatio);
$middleWidth = $givenWidth;
$y = ceil(($givenHeight - $middleHeight)/2);
}
else{
$middleHeight = $givenHeight;
$middleWidth = ceil($givenHeight * $requiredRatio);
$x = ceil(($givenWidth - $middleWidth)/2);
}
$new_im = imagecreatetruecolor($requiredWidth,$requiredHeight);
$extention = strtolower(substr($source, strlen($source)-3, strlen($source)));
if ($extention == "jpg" || $extention == "jpeg") { $im = imagecreatefromjpeg($source); }
elseif ($extention == "gif") { $im = imagecreatefromgif($source); }
elseif ($extention == "png") { $im = imagecreatefrompng($source); }
else
{
//echo("ERROR: Unknown image source file format");
return;
}
imagecopyresampled($new_im,$im,0,0,$x,$y,$requiredWidth,$requiredHeight,$middleWidth,$middleHeight);
imagejpeg($new_im,$dest,85);
}
}
function createThumbs($source, $dest, $requiredWidth, $requiredHeight, $fileType='')
{
$size = getimagesize($source);
$givenWidth = $size[0];
$givenHeight = $size[1];
if ($givenWidth > 800)
{
$requiredRatio = $requiredWidth / $requiredHeight;
$middleWidth = ceil($givenHeight * $requiredRatio);
if($middleWidth>$givenWidth){
$requiredRatio = $requiredHeight / $requiredWidth;
$middleHeight = ceil($givenWidth * $requiredRatio);
$middleWidth = $givenWidth;
$y = ceil(($givenHeight - $middleHeight)/2);
}
else{
$middleHeight = $givenHeight;
$middleWidth = ceil($givenHeight * $requiredRatio);
$x = ceil(($givenWidth - $middleWidth)/2);
}
$new_im = imagecreatetruecolor($requiredWidth,$requiredHeight);
$extention = strtolower(substr($source, strlen($source)-3, strlen($source)));
if ($extention == "jpg" || $extention == "jpeg") { $im = imagecreatefromjpeg($source); }
elseif ($extention == "gif") { $im = imagecreatefromgif($source); }
elseif ($extention == "png") { $im = imagecreatefrompng($source); }
else
{
//echo("ERROR: Unknown image source file format");
return;
}
imagecopyresampled($new_im,$im,0,0,$x,$y,$requiredWidth,$requiredHeight,$middleWidth,$middleHeight);
imagejpeg($new_im,$dest,85);
}
}
Thursday, November 3, 2011
Redirect to www .htaccess
Create a .htaccess file with the below code, it will ensure that all requests coming in to domain.com will get redirected to www.domain.com
The .htaccess file needs to be placed in the root directory of your old website (i.e the same directory where your index file is placed)
The .htaccess file needs to be placed in the root directory of your old website (i.e the same directory where your index file is placed)
Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]
RewriteEngine on
rewritecond %{http_host} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]
Please REPLACE domain.com and www.newdomain.com with your actual domain name.
Note* This .htaccess method of redirection works ONLY on Linux servers having the Apache Mod-Rewrite moduled enabled.
Thursday, July 21, 2011
Zip Files or Folder On The Fly Using PHP
Zip Files<?phpinclude_once 'CreateZipFile.inc.php';$createZip = new CreateZipFile;$createZip->addDirectory('/');$filecontent1 = file_get_contents('fileone.txt');$filecontent2 = file_get_contents('filetwo.txt');$createZip->addFile($filecontent1, '/fileone.txt');$createZip->addFile($filecontent2, '/filetwo.txt');$zipFileName = 'myzip.zip';$handle = fopen($zipFileName, 'wb');$out = fwrite($handle, $createZip->getZippedFile());fclose($handle);$createZip->forceDownload($zipFileName);@unlink($zipFileName);?>Zip Folder<?phpinclude_once 'CreateZipFile.inc.php';$createZip = new CreateZipFile;$createZip->zipDirectory('/testdir', '');$zipFileName = 'myzip.zip';$handle = fopen($zipFileName, 'wb');$out = fwrite($handle, $createZip->getZippedFile());fclose($handle);$createZip->forceDownload($zipFileName);@unlink($zipFileName);?>Wednesday, September 9, 2009
Top 7 PHP Security Blunders
PHP is a terrific language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn't require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.
Tuesday, September 1, 2009
Improving Performance by Profiling PHP Applications
One of the best things about programming in PHP is how easy it is to learn the language and its libraries. Everything seems to fit together and you can almost guess how to do a specific task, even not knowing much about the function that you need to use. A lot of times you will just try doing something and be surprised that the language has that specific feature.
PHP performance tips
Profile your code to pinpoint bottlenecks
Before changing your code, you'll need to determine what is causing it to be slow. You may go through this guide, and many others on optimizing PHP, when the issue might instead be database-related or network-related. By profiling your PHP code, you can try to pinpoint bottlenecks.Friday, August 28, 2009
PHP global arrays
The Global Array List
| Old Form | New Form | Description |
|---|---|---|
-- | $GLOBALS[] | The complete list of all global variables, including user defined variables at the global level. |
$HTTP_GET_VARS[] | $_GET[] | All variables received as part of a query string in the requesting URL, or HTML form data transmitted using the GET method. |
$HTTP_POST_VARS[] | $_POST[] | All variables recieved as an inline posted data set, normally through using the POST method in an HTML form. |
$HTTP_POST_FILES[] | $_FILES[] | References to all files received, most commonly from HTML forms, using the POST method. |
$HTTP_COOKIE_VARS[] | $_COOKIE[] | Any cookies returned from the client. The index key name matches the cookie name. |
-- | $_REQUEST[] | A more recent addition that stores all user variables, including elements from the $_GET[], $_POST[], and $_COOKIE[] arrays. Prior to PHP4.3, this also includes the $_FILES[] array. |
$HTTP_SERVER_VARS[] | $_SERVER[] | Information about the server session and the HTTP connection with the client. |
$HTTP_ENV_VARS[] | $_ENV[] | Information about the server environment and system defined values. |
$HTTP_SESSION_VARS[] | $_SESSION[] | IF PHP is being used for session management, this array is to store any session variables that need to be stored on the server between calls from the client. |
Wednesday, October 1, 2008
Generating pdf with php
There exists very little open source options for generating pdf with php but http://fpdf.org
is one easy to use and both IE and firefox compatible open source solution available which generates pdf files with pure php so its very easy to setup on your server.
The author claims that although the generation speed of the document is less than with PDFlib
but there is very small difference for small and medium sized pdf documents.
The site has good tutorials for beginners and manual for all the functions.
is one easy to use and both IE and firefox compatible open source solution available which generates pdf files with pure php so its very easy to setup on your server.
The author claims that although the generation speed of the document is less than with PDFlib
but there is very small difference for small and medium sized pdf documents.
The site has good tutorials for beginners and manual for all the functions.
Subscribe to:
Posts (Atom)