Wednesday, December 4, 2013

Multipart Mime Headers in PHP

Here is a snippet of code that shows how multi-part mime headers can be assembled without the help of a mailer class.

<?php
$mime_boundary=md5(time());
$headers .= 'From: My Email <me@company.com>' . "\n";
$headers .= 'MIME-Version: 1.0'. "\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"". "\n"; 
 
$msg .= "--".$mime_boundary. "\n";
$msg .= "Content-Type: text/plain; charset=iso-8859-1". "\n";
$msg .= "Content-Transfer-Encoding: 7bit". "\n\n";
$msg .= $textmessage . "\n\n";
 
$msg .= "--".$mime_boundary. "\n";
$msg .= "Content-Type: application/pdf; name=\"".$filename."\"". "\n";
$msg .= "Content-Transfer-Encoding: base64". "\n";
$msg .= "Content-Disposition: attachment; filename=\"".$filename."\"". "\n\n";
$msg .= chunk_split(base64_encode($doc)) . "\n\n";
$msg .= "--".$mime_boundary."--". "\n\n";
?>

Tuesday, November 26, 2013

PHP ini Configuration

Case Study

  • Your php scripts contains many inputs fields and also so many logics. When you execute your scripts its gives a fatal error: PHP Fatal error: Maximum execution time of 120 seconds exceeded in C:\wamp\www\phptest\test.php on line 101
  • You want to upload your database to server using phpmyadmin. You select your sql files and when click upload it gives a fatal error : PHP Fatal error: Files exceeds it Maximum upload size.

The solution is

Configure your php.ini file

PHP ini file location

If you have wamp installed in c drive then go C:\wamp\bin\php\php5.2.6 as shown in below and open php.ini file

Or

You can go directly by clicking wamp tray icon as shown in below. In this case, you have to run wamp server
Now we have our php.ini file ready. So lets do the following

 PHP short open tag

You must off the php short tag for the following reasons
  • Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server.
  • For portable, redistributable code, be sure not to use short tags.
  • If you are sharing your code (open source etc.), some users might use them on a host which does not support PHP short code. So do not use short tag.
  • Generates confusion with XML declarations. Your code will break, and you will have very very hard time figuring out why.
  • <% %>, the ASP opening tag! Probably one of the most idiotic 'features' in PHP – the ability to write PHP code with ASP opening tags. Avoid anything idiotic.
  • Even the creators of PHP are suggesting not using short tags. Infact, short tags will be gone in PHP 6. Make your code future-proof.
So keep
short_open_tag = Off

Maximum execution time

Suppose you are running a script that takes more time (more than 30 seconds and your assigned time is 30 seconds) to execute. It gives you a php fatal error : "maximum execution time exceeds" and your script stopped running. So increase execution time
max_execution_time = 60 or max_execution_time = 120

Maximum Input time

Maximum amount of time each script may spend parsing request data. If you think your are running a big script then increase input time.
max_input_time = 60

Memory limit

Maximum amount of memory a script may consume
memory_limit =512M

Display errors

In order to see errors that your scripts generates then keep it on
display_errors = On

Log errors

Keep it on if you want to save any php errors in a file for future use.
log_errors = On

Error log

Location of error log file. Default error log file location is c:/wamp/logs. If you want to some where else than default location change it.
error_log = c:/wamp/logs/php_error.log

Post Maximum Size

Maximum size of POST data that PHP will accept. If your scripts contains audio or video data then increase it
post_max_size = 8M

Upload Maximum Size

Maximum allowed size for uploaded files. If Your scripts contains audio or video data then increase it
upload_max_filesize = 20M

Error Reporting

Suppose you are new in PHP programming and you want to see all sorts of error that your scripts generates then keep it E_ALL. Remember that, keep it on only for development environment , not in production environment.
error_reporting = E_ALL

Restart Wamp

After successfully changing above php configuration, save the file.

Now Don't Forget To Restart Your Wamp Server

Checking Changes value

To see the changes value, go to http://localhost/?phpinfo=1 and see your recently changes php value.




Thursday, November 21, 2013

Ajax Select and Upload Multiple Images with Jquery

Very few days back I had posted an article about Multiple ajax image upload without refreshing the page using jquery and PHP. In this post I have updated few lines of code that allows to user can select and upload multiple images in single shot.

Sample database design for Users.

Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`user_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)

User Uploads
Contains user upload details upload_id, image_name, user_id_fk(foreign key) and timestamp etc.
CREATE TABLE  `user_uploads` (
`upload_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`image_name` text,
`user_id_fk` int(11),
`created` int(11)
)

Javascript Code
$("#photoimg").live('change',function(){})photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag. 
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function() 


$('#photoimg').live('change', function() 
 {
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");

$("#imageform").ajaxForm({target: '#preview', 
beforeSubmit:function(){
A.show();
B.hide();
}, 
success:function(){
A.hide();
B.show();
}, 
error:function(){
A.hide();
B.show();
} }).submit();
});

}); 
</script>
Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.


index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value. 

<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
Upload image: 
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimgmultiple="true" />
</div>
</form>

ajaxImageUpload.php
Contains PHP code. This script helps you to upload images into uploads folder and it will  rename image file into timestamp+session_id.extention format to avoid duplicates. This system will store image files into user_uploads with user session id tables
<?php
error_reporting(0);
session_start();
include('db.php');
$session_id='1'; //$session id
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Valid image formats 
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") 
{
$uploaddir = "uploads/"; //Image upload directory
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))

$image_name=time().$filename; 
echo "<img src='".$uploaddir.$image_name."' class='imgList'>"; 
$newname=$uploaddir.$image_name; 
//Moving file to uploads folder
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) 

$time=time(); 
//Insert upload image files names into user_uploads table
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else 

echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; } 
}

else 

echo '<span class="imgList">You have exceeded the size limit!</span>'; 




else 

echo '<span class="imgList">Unknown extension!</span>'; 


//foreach end


?>


db.php
Database configuration file, just modify database credentials.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>

CSS
Style for image blocks. 
#preview
{
color:#cc0000;
font-size:12px
}
.imgList 
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px; 
float:left; 
}

Understanding Regular Expression

Regular expression is the most important part in form validations and it is widely used for search, replace and web crawling systems. If you want to write a selector engine (used to find elements in a DOM), it should be possible with Regular Expressions. In this post we explained few tips that how to understand and write the Regular Expression in simple way.

Will discuss about basic regular expression in three stages.

Stage 1
Symbol             Explanation

^                       Start of string
                      End of string
.                        Any single character
+                       One or more character
\                        Escape Special characters
?                       Zero or more characters

Input exactly match with “abc” 
var A = /^abc$/;

Input start with “abc”
var B = /^abc/;

Input end with “abc”
var C = /abc$/;

Input “abc” and one character allowed Eg. abcx
var D = /^abc.$/;

Input  “abc” and more than one character allowed Eg. abcxy
var E = /^abc.+$/;

Input exactly match with “abc.def”, cause (.) escaped
var F = /^abc\.def$/;

Passes any characters followed or not by “abc” Eg. abcxyz12....
var G = /^abc.+?$/

Stage 2

Char                Group Explanation

[abc]                 Should match any single of character
[^abc]               Should not match any single character
[a-zA-Z0-9]      Characters range lowercase a-z, uppercase A-Z and numbers
[a-z-._]              Match against character range lowercase a-z and ._- special chats 
(.*?)                  Capture everything enclosed with brackets 
(com|info)         Input should be “com” or “info”
{2}                   Exactly two characters
{2,3}                Minimum 2 characters and Maximum 3 characters
{2,}                  More than 2 characters


Put together all in one URL validation.
var URL = /^(http|https|ftp):\/\/(www+\.)?[a-zA-Z0-9]+\.([a-zA-Z]{2,4})\/?/;

URL.test(“http://9lessons.info”);                      // pass
URL.test(“http://www.9lessons.info”);            // pass
URL.test(“https://9lessons.info/”);                   // pass
URL.test(“http://9lessons.info/index.html”);    // pass

Stage 3

Short Form     Equivalent              Explanation 

\d                      [0-9]                         Any numbers
\D                     [^0-9]                       Any non-digits
\w                     [a-zA-Z0-9_]            Characters,numbers and underscore
\W                    [^a-zA-Z0-9_]          Except any characters, numbers and underscore
\s                       -                                White space character
\S                      -                                Non white space character


var number = /^(\+\d{2,4})?\s?(\d{10})$/;  // validating phone number

number.test(1111111111);           //pass
number.test(+111111111111);     //pass
number.test(+11 1111111111);    //pass
number.test(11111111);               //Fail

How to change the PHP version for subfolders or subdomains

  How to change the PHP version for subfolders or subdomains Setting a specific PHP version for a specific websites, subfolders or subdomain...