PHP Expert Programmer

Just another WordPress.com weblog

Archive for the ‘Php Codes’ Category

Php Codes

Short open tags not work in php5.2.0 and not in php5.2.3

Posted by sarapeter on April 20, 2009

Short open tags not work in php5.2.0 and not in php5.2.3

My advice was to put short_open_tag = On in the php.ini file.

The server status is short_open_tag = Off

I set this to short_open_tag = On in the php.ini file in the root of the site.

This did not work but when I renamed the php.ini file to php5.ini this corrected this issue.

However I did not immediately notice but this blocked out the server php.ini file – this start a major component working as it also blocked out zend optimizer.

I have read more about the issue of the short tag.

I have in my limited experience of php coding always used <!–p and not <?
There appears to be a number opinions that setting short_open_tag = On can cause problems where there are xml files as attempts will be made to parse these.

I have been through every php file in the component – I can’t find a short code anywhere in the files.

Posted in Php Codes, Php Errors, Php Security | Tagged: , , , | Leave a Comment »

Fatal error: Allowed memory size of 8388608 bytes exhausted

Posted by sarapeter on March 26, 2009

Php Fatal error: Allowed memory size of 8388608 bytes exhausted

This error message can spring up in a previously functional PHP script when the memory requirements exceed the default 8MB limit. Don’t fret, though, because this is an easy problem to overcome.

To change the memory limit for one specific script by including a line such as this at the top of the script:

ini_set("memory_limit","12M");

The 12M sets the limit to 12 megabytes (12582912 bytes). If this doesn’t work, keep increasing the memory limit until your script fits or your server squeals for mercy.

You can also make this change permanently for all PHP scripts running on the server by adding a line like this to the server’s php.ini file:

memory_limit = 12M

Keep in mind that a huge memory limit is a poor substitute for good coding. A poorly written script may inefficiently squander memory which can cause severe problems for frequently executed scripts. However, some applications are run infrequently and require lots of memory like importing and processing a big data file.

Posted in Php Codes, Php Errors, Php Functions, Php Methods, Php Security | Tagged: , , , , | Leave a Comment »

Resize an image on the fly & keep its aspect ratio

Posted by sarapeter on March 25, 2009

Resize an image on the fly & keep its aspect ratio

bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

In other words, imagecopyresampled() will take an rectangular area from src_image of width src_w and height src_h at position (src_x ,src_y ) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x ,dst_y ).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image ) but if the regions overlap the results will be unpredictable.

<?php
// The file
$filename 'test.jpg'
;
$percent 0.5
;

// Content type
header('Content-type: image/jpeg'
);

// Get new dimensions
list($width$height) = getimagesize($filename
);
$new_width $width $percent
;
$new_height $height $percent
;

// Resample
$image_p imagecreatetruecolor($new_width$new_height
);
$image imagecreatefromjpeg($filename
);
imagecopyresampled($image_p$image0000$new_width$new_height$width$height
);

// Output
imagejpeg($image_pnull100
);
?>

Posted in Php Codes, Php Functions, Php Methods | Tagged: , , , , | Leave a Comment »

Sending Email with Attachment

Posted by sarapeter on February 8, 2009

The last variation that we will consider is email with attachments. To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have a look at the example:

<?php
//define the receiver of the email
$to = ‘youraddress@example.com’;
//define the subject of the email
$subject = ‘Test email with attachment’;
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash

$random_hash = md5(date(‘r’, time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = “From: webmaster@example.com\r\nReply-To: webmaster@example.com”;
//add boundary string and mime type specification
$headers .= “\r\nContent-Type: multipart/mixed; boundary=\”PHP-mixed-”.$random_hash.”\”";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks

$attachment = chunk_split(base64_encode(file_get_contents(‘attachment.zip’)));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
–PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary=”PHP-alt-<?php echo $random_hash; ?>”

–PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset=”iso-8859-1″
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

–PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset=”iso-8859-1″
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

–PHP-alt-<?php echo $random_hash; ?>–

–PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/zip; name=”attachment.zip” 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?>
–PHP-mixed-<?php echo $random_hash; ?>–

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print “Mail sent”. Otherwise print “Mail failed”
echo $mail_sent ? “Mail sent” : “Mail failed”;
?>

As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64,  split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.

Posted in Php Codes | Tagged: , | Leave a Comment »

Sending a Simple Text Email

Posted by sarapeter on February 8, 2009

At first let’s consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters. These parameters are, in order, the email address to send to, the subject of the email, the message to be sent, additional headers you want to include and finally an additional parameter to the Sendmail program. The mail() function returns True if the message is sent successfully and False otherwise. Have a look at the example:

<?php
//define the receiver of the email
$to = ‘youraddress@example.com’;
//define the subject of the email
$subject = ‘Test email’;
//define the message to be sent. Each line should be separated with \n
$message = “Hello World!\n\nThis is my first mail.”;
//define the headers we want passed. Note that they are separated with \r\n
$headers = “From: webmaster@example.com\r\nReply-To: webmaster@example.com”;
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print “Mail sent”. Otherwise print “Mail failed” 
echo $mail_sent ? “Mail sent” : “Mail failed”;
?>

As you can see, it very easy to send an email. You can add more receivers by either adding their addresses, comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don’t receive the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.

Posted in Php Codes | Tagged: , , | Leave a Comment »

how to remove html tags from text in php

Posted by sarapeter on February 6, 2009

if you are reading my post, its probably because you want to remove html tags from your posts or forums or whatever.

when i first started to do this, i wanted to remove all the html tags from a strin i had in my posts. this is an example:

<?
$string = “<h1>BIG HTML TAGS</h1>”;
?>

ok as you can see, this will output:

BIG HTML TAGS

but i dont want that, i want to stop and prevent html from being posted on my forums. i tried using htmlspecialchars() and htmlentities() but none did what i wanted.

but finally i found it, the function is called strip_tags()

so if i wanted to remove the <h1> tags from my string i would just simply do this:

<?
$string = “<h1>BIG HTML TAGS</h1>”;
$string = strip_tags($string);
?>

and this would be the ouput:

BIG HTML TAGS

Posted in Php Codes | Tagged: | Leave a Comment »

PHP Email Address Validation

Posted by sarapeter on July 29, 2008

<?Php
function check_email_address($email) {
// First, we check that there’s one @ symbol, and that the lengths are right
if (!ereg(“^[^@]{1,64}@[^@]{1,255}$”, $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode(“@”, $email);
$local_array = explode(“.”, $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg(“^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\”[^(\\|\")]{0,62}\”))$”, $local_array[$i])) {
return false;
}
}
if (!ereg(“^\[?[0-9\.]+\]?$”, $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(“.”, $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg(“^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$”, $domain_array[$i])) {
return false;
}
}
}
return true;
}
?>

Using the function above is relatively simple, as you can see:

<?Php
if (check_email_address($email)) {
    echo $email . ‘ is a valid email address.’;
} else {
    echo $email . ‘ is not a valid email address.’;
}
?>

Posted in Php Codes, Php Validators | Tagged: , , | Leave a Comment »

Returning an array of variables from PHP function

Posted by sarapeter on July 29, 2008

From a function we can get back a set of variables by using an array. A function returns any variable to the main script by using return statement. Here we will try to return a set of variables by using an array. Our main script will receive the array and we will use while each statement to display all elements of an array.

We will change a script a bit and try to pass ( as input ) a string to the function. This string we will break by using split command and create an array. This array we will return to main script for displaying.

<?Php

function test($my_string){
// creating an array by split command
$my_array=split(” “,$my_string);
return $my_array; // returning the array
}

// sending a string to function as input //
$collect_array=test(“Hello welcome to plus2net”);

// displaying the elements of the collected array
while (list ($key, $val) = each ($collect_array)) {
echo “$key -> $val <br>”;
}

?>

Posted in Php Codes | Tagged: , , , , | Leave a Comment »