$zip = new ZipArchive;
$zip->open(‘innovapain.zip’);
$zip->extractTo(‘./’);
$zip->close();
Category Archives: PHP
How to download a file on server in PHP
What are some good WordPress plugins
- Business Directory
- Calendar
- Contact Form
- Custom Post Order
- My Post Order
- My Page Order
- Fancy Transition Header Slider
- Google Analytics
- Sharethis
- Simple Pagination
- Spider FAQs
- White Label CMS
- .html on Pages
- Page Meta
- Another WordPress Meta Plugin
- Captcha
- Mail List By Danilo Andreini
How do I detect mobile browser in PHP?
// Create the function, so you can use it
function isMobile() {
return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}
// If the user is on a mobile device, redirect them
if(isMobile()) header("Location: http://m.yoursite.com/");
Can you recommend some post upload checks?
- Delete unwanted files, like ‘test’, ‘copy of’, etc.
- Give write permission (777) to the required folders.
- If .htaccess file has been uploaded, make sure it runs according the the server settings. Sometimes .htaccess files run on local but not on server.
- Make configuration settings according to server where required, like database connections, file paths, etc.
- Do not upload folders required for local copy of the web site like ‘backup’,'db’, etc – if you maintain them.
- In folders where there are no index/default files, place a blank index/default file to avoid directory listing. If this is not done, a site visitor can type in the folder path in browser URL and see all files in that folder which is not a good idea. This can also be done using .htaccess file with the following code.
Options -Indexes
How to take backup dump of MySQL database with PHP script
Here is a simple script to take backup of MySQL database, using a PHP script.
<?php
backup_tables(‘localhost’,'username’,'password’,'dbname’);
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$dbname,$tables = ‘*’)
{
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);
//get all of the tables
if($tables == ‘*’)
{
$tables = array();
$result = mysql_query(‘SHOW TABLES’);
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(‘,’,$tables);
}
//cycle through
foreach($tables as $table)
{
$result = mysql_query(‘SELECT * FROM ‘.$table);
$num_fields = mysql_num_fields($result);
$return.= ‘DROP TABLE IF EXISTS ‘.$table.’;';
$row2 = mysql_fetch_row(mysql_query(‘SHOW CREATE TABLE ‘.$table));
$return.= “\n\n”.$row2[1].”;\n\n”;
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$return.= ‘INSERT INTO ‘.$table.’ VALUES(‘;
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace(“\n”,”\\n”,$row[$j]);
if (isset($row[$j])) { $return.= ‘”‘.$row[$j].’”‘ ; } else { $return.= ‘”"‘; }
if ($j<($num_fields-1)) { $return.= ‘,’; }
}
$return.= “);\n”;
}
}
$return.=”\n\n\n”;
}
//save file
$handle = fopen(‘./db/db-backup-’.time().’-’.(md5(implode(‘,’,$tables))).’.sql’,'w+’);
fwrite($handle,$return);
fclose($handle);
}
?>
How to uploading large(big) files in PHP using .htaccess
Usually, default upload size from a web browser is 2 MB and if this is required to be changed, you can do it using .htaccess file.
- Create a .htaccess file in the root folder of web server.
- Put the following code in side the .htaccess file and save it.
- If the .htaccess file already exists, add the above code to the already existing file.
- Make sure there are no blank spaces at the end of the file.
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200
Note: Some servers do not allow to change file upload size using .htaccess so Internal Server Error may appear in this case.
How to stream a file as attachment in PHP
Sometimes we need to download files as attachment in PHP. This code can ideally be called on a hyperlink.
$filename = “myImage.jpg”;
if(file_exists($filename)) {
header(“Content-disposition: attachment; filename={$filename}”);
//Tell the filename to the browser
header(‘Content-type: application/octet-stream’);
//Stream as a binary file! So it would force browser to download
readfile($filename);
//Read and stream the file
}else{
echo “Sorry, the file does not exist!”;
}
What are some common PHP coding standards
- Set all warnings and errors to ‘on’ in php.ini file.
- Set register_ globals to ‘off’ in php.ini file.
- Set magic_quotes_gpc to ‘off’ in php.ini file.
- Set magic_quotes_runtime to ‘off’ in php.ini file.
- Test in browser with javascript errors on.
- Make an include file for all settings and variables.
- Check data entry with single quotes and double quotes.
- Use stripslashes() when fetching data.
- Use nl2br() when printing data (entered from a textarea) in html pages.
- Use encrypted query strings where required.
- One user must not be able to see the records of another user by tampering with the query string variables.
- Use image resizing wherever required.
- Do not resize images that are smaller than the specified size.
- When uploading file, display allowable file types and maximum upload size like: JPG, PNG and GIF Only. Max file size 2 MB.
- All forms should come filled in, in case of any errors in filling the form, so that user does not have to type all info again.
- All deletes must be confirmed before deletion.
- Use lipsum for dummy text. Get it from www.lipsum.com.
- When a search or view record is not found, please show a message, “No record found.”.
- Check for cascade deletions where required or warn for child record entry.
- On all submitted forms, especially contact us pages, please check referrer.
- Make messages like this:
- Username is a required field.
- Your passwords do not match.
- This category cannot be deleted as it is being referred to in a subcategory. Please delete the subcategory first.
- Delete corresponding images when deleting records from database.
- All forms must be validated.
- Use date picker or date combos whenever date is required to be entered.
- Paginate when required.
- When writing insert and/or update SQL queries, always write field names and then values. Do not insert or update all values.
- When writing database queries, always use quotes, even for numeric fields. This is for MySQL database.
- Table names and field names should be like this:
- Table name: databasename_tablename
- Field name: tablename_fieldname
- Some commonly used field sizes should be as below:
- username: varachar(20)
- password: varchar(20)
- firstname: varchar(15)
- lastname: varchar(15)
- fullname: varchar(30)
- phone: varchar(15)
- fax: varchar(15)
- email: varchar(50)
- address: text
- city: varchar(20)
- state: varchar(20)
- zip: varchar(12)
- country: int (to come from from country’s table).
- url: varchar(255)
- amount/price: double
- date: date
- timestamp: bigint
- Please set textbox’s max attribute to what it is in the database.
- Add server timeout when required.
- Test all your applications on multiple browsers.
- Give alt tag to all images
- Give title tags to images and hyperlinks.
- There is always space after a comma, a colon, a semi-colon and a full stop and not before them.
- Place an index page (with page title and text as “Access Denied” in all folders without index page to stop directory browsing. Or stop directory browsing using htaccess file.
- Show dates in full date format (January 10, 2012)
- Make admin login window database driven.
- All forms submitted, leading to select statements most have GET method.
- All views must be ordered by their respective fields.
- In user manager, the application must not be able to delete self and must not be able to delete the admin level user.
- Password protect admin folder with database driven module. Do not depend on password protecting admin folder.
- Use meta tag to redirect to log out page for auto log out when required.
- Always use die() with queries.
- Set auto complete off for login forms.
- Stripslashes() in email messages.
- Use substr where required to show long messages like “Lorem ipsum dorit…”.
- Format numbers as 24.00 where required.
- Spell check
- Write recommended size for pictures
- Contact and similar pages should go to thank you page.
- Required field must be marked with *.
- Use inner joins where required.
- Use enum data type where required.
- Close connections at page end or before redirection.
- Clean up test files before uploading.
- Use frame busters where required.
- Centre pop up windows.
- Delete images before updating them. Either check if exists before deleting or use @unlink.
- Mark all required fields with * in all forms.
- To get file path, use the following as it works on Apache and IIS.
- $url_to=”http://”.$ HTTP_HOST.$SCRIPT_NAME;
- Set different session names for admin and public users.
- Remove all test email addresses that send forms to you.
- Some sample messages at below.
Signup: Thank you very much for registering. Your account is now active and ready to use.
Contact Us: Thank you for contacting us. Your message has been sent to the concerned department and you will be contacted back shortly.
Profile Update: Your profile has been updated successfully.
Bug report submission message: Thank you very much for your time. Your reported bug/error has been routed to the concerned department for further action.
Lost Password: Your login information has been mailed to your email@domain.com.
Wrong Login info for Lost Password: Invalid login information; please provide the email address you used when you registered with us.
Lost Password Email:
Subject: Your SITE_NAME Login Information
Dear Member Name,
Your SITE_NAME login information is as below.
User Name: username
Password: password
The SITE_NAME Team
Registration Email to the member:
Subject: Welcome to SITE_NAME
Dear Member Name,
We welcome you to SITE_NAME. Your login information is as below and you can change your password anytime after logging in to the web site.
User Name: username
Password: password
The SITE_NAME Team
How to watermark an image in PHP
Watermarking an image in PHP is very easy. If you follow the code below, you can do it in 2 minutes.
<?php
function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
//$SourceFile is source of the image file to be watermarked
//$WaterMarkText is the text of the watermark
//$DestinationFile is the destination location where the watermarked images will be placed
//Delete if destinaton file already exists
@unlink($DestinationFile);
//This is the vertical center of the image
$top = getimagesize($SourceFile);
$top = $top[1]/2;
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
//Path to the font file on the server. Do not miss to upload the font file
$font = ‘arial.ttf’;
//Font sie
$font_size = 16;
//Give a white shadow
$white = imagecolorallocate($image_p, 255, 255, 255);
imagettftext($image_p, $font_size, 0, 10, $top, $white, $font, $WaterMarkText);
//Print in black color
$black = imagecolorallocate($image_p, 0, 0, 0);
imagettftext($image_p, $font_size, 0, 8, $top-1, $black, $font, $WaterMarkText);
if ($DestinationFile<>”) {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header(‘Content-Type: image/jpeg’);
imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
};
?>
<?php
$SourceFile = ‘image.jpg’;//Source image
$DestinationFile = ‘watermarked/image.jpg’;//Destination path
$WaterMarkText = ‘www.phpHelp.co’;//Watermark text
//Call the function to watermark the image
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);
//Display watermarked image if desired
if(file_exists($DestinationFile)){
echo “<img src=\”watermarked/image.jpg\”>”;
echo “<p>The image has been watermarked at ‘”.$DestinationFile.”‘</p>”;
}
?>
Note:
- This code is being provided to you as a help by http://www.phpHelp.co without any warranty and liability
- Place all the files in a folder on web server.
- Do not forget to upload the font file – arial.ttf.
- Once the image is watermarked, it will be placed in the folder named ‘watermarked’.
- You might need to give ‘write permission’ or ’777 permission’ to the folder named ‘watermarked’ as the new watermarked image will be written in this folder.