PHP Expert Programmer

Just another WordPress.com weblog

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 »

Php extract method

Posted by sarapeter on March 1, 2009

“extract()” Method


Experimentally I found that calling extract() also shows the number of keys if the key is set and is not numeric ! Maybe there was a better definition than mine  . Please have a look to this scripts :
<?PHP
$var
["i"] = “a”
;
$var["j"] = “b”
;
$var["k"] = 1
;
echo
extract($var);
// returns 3
?>

<?PHP
$var2
["i"] = “a”
;
$var2[2] = “b”
;
$var2[] = 1
;
echo
extract($var2);
// returns 1
?>

 

(Arash Moslehi)

Posted in 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 »

X-Cart – ecommerce shopping cart software

Posted by sarapeter on August 18, 2008

X-Cart – ecommerce shopping cart software:

  • X-Cart shopping cart software is based on PHP Smarty templates, this makes it very flexible and easy to modify. The data is stored in MySQL database.
  • W3C XHTML 1.0 compliance of X-Cart storefront out of the box.
  • You receive a complete source code and SQL tables for MySQL database to make them extended or customized easily.
  • X-Cart is a turnkey package. Installation is handled by web-based step-by-step wizard to make the system running immediately after receiving it.
  • X-Cart is search engine friendly. It has integrated HTML catalog functionality to gain benefits of dynamic content and static HTML preferred by search engines.
  • We bundle our software with 24×7 free technical support for beginners. Our experts are always ready to answer questions, even handle installation & configuration tasks.
  • We also offer custom programming services. Every client can get a storefront with a unique look. We can customize the software to completely fit the structure of your business.
  • Additional software licenses come at discounted rates.

More advantages:

Robust feature rich ecommerce shopping cart software is a key in online business success. Its potential can be multiplied many times if accompanied by coherent resources & services to give a hand on the way to online success not leaving you alone when operating live ecommerce website:

  • Moneyback guarantee

    We offer unconditional 30-day money back guarantee as a sign of our products quality to ensure best customers’ experience in any case. Simply request a refund within 30 days since purchase to have all the money back.

  • Community forums

    The value of help provided by community forums should not be underestimated. Share experience with thousands of real business owners to find answers & hints to be successful. The forums are intentionally made available for clients only to ensure community forums are the meeting point of people who actually are in the business.

  • Responsive support

    Free technical support offered with each license guarantees successful project launching. We designed our software to minimize the need of this, so free technical support is a warranty card to keep you confident.

  • Partnership

    Regardless of whether you are a web hosting provider, developer, payment gateway or ISP, we can setup a partner relationship profitable for both parties. Read about our Affiliate program and see Reseller prices.

Website: http://www.x-cart.com/

Posted in Php CMS, Php Shopping Carts | 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 »

PHP MySQL Database Class

Posted by sarapeter on July 29, 2008

A class for very basic MySQL database connectivity. Written to reduce redundant code in my own projects aswell as aid in debugging and error reporting during the developement phase. Currently connects to a database, execute external files containing SQL commands, insert and update from an array of key => value pairs, insert and update with sql command, query (one result), query (multiple rows), and dump a select query to a table. The zip file contains the class aswell as a demonstration script.

Download Version 1.0.4: db-1.0.4.zip

Posted in Php Database, Php MySql | 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 »

Turnkey PHP shopping cart software

Posted by sarapeter on July 28, 2008

  • Complete ready-to-run PHP shopping cart software
  • No programming required
  • Cost-effective
  • All major ecommerce features
  • Easy design integration in any HTML editor
  • A set of ready-to-use skin templates included
  • Search Engine friendly
  • Online credit card processing
  • Integrated with Google Checkout and PayPal Pro
  • Real-time shipping quotes
  • Order notifications by email and SMS
  • Easy localization
  • Free installation service
  • Free 24/7 customer support
  • WEBSITE: http://www.shop-script.com/

    Posted in Php Shopping Carts | Tagged: , , , , , , , , , , , | Leave a Comment »

    Joomla – Cutting Edge Content Management

    Posted by sarapeter on July 24, 2008

    Joomla

    Joomla

    Joomla! is one of the most powerful Open Source Content Management Systems on the planet. It is used all over the world for everything from simple websites to complex corporate applications. Joomla! is easy to install, simple to manage, and reliable.

    Joomla! is different from the normal models for content management software. For a start, it’s not complicated. Joomla! has been developed for everybody, and anybody can develop it further. It is designed to work (primarily) with other Open Source, free, software such as PHP, MySQL, and Apache.

    It is easy to install and administer, and is reliable.

    Joomla! doesn’t even require the user or administrator of the system to know HTML to operate it once it’s up and running.

    To get the perfect Web site with all the functionality that you require for your particular application may take additional time and effort, but with the Joomla! Community support that is available and the many Third Party Developers actively creating and releasing new Extensions for the 1.5 platform on an almost daily basis, there is likely to be something out there to meet your needs. Or you could develop your own Extensions and make these available to the rest of the community.

    Posted in Php CMS | Tagged: , , , | 1 Comment »

    Easy PHP Calendar

    Posted by sarapeter on July 23, 2008

    The Easy PHP Calendar is a powerful PHP calendar script that is easily integrated into web sites and is simple to customize. This attractive, full-featured calendar is suitable for display on a calendar of events page, home page, or any other page that needs a calendar.

    * The Easy PHP Calendar was formerly known as the Easily Simple Calendar.

    Key Features:

    • mySQL database support
    • Flat-file database support – No mySQL server required!
    • Single events, recurring events and floating events plus multiple categories
    • Complete and easy event and setup administration
    • Mouse-over and pop-up event details
    • Customizable categories and multiple event administrators
    • Rich event descriptions including font sizes/colors and images
    • and much more…

    With the Easy PHP Calendar, you can easily customize colors, font sizes, table sizes and more by adjusting a single CSS file. It’s simple to take complete control over the PHP calendar’s looks and how it interacts with users! With support for multiple date, time and language formats, the Easy PHP Calendar can be used for anywhere in the world!

    The Easy PHP Calendar is well-supported through the user forums. Take your time to view the online demonstration, download a free trial version, and you’ll see that the Easy PHP Calendar is the PHP calendar script for you!
     
    DOWNLOAD

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

    Selecting random record from MySQL database table

    Posted by sarapeter on July 7, 2008

    The simplest way of selecting random rows from the MySQL database is to use “ORDER BY RAND()” clause in the query.

    Solution 1 [SQL]
    SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;

    The problem with this method is that it is very slow. The reason for it being so slow is that MySQL creates a temporary table with all the result rows and assigns each one of them a random sorting index. The results are then sorted and returned.

    There are several workarounds to speed things up.

    The basic idea is to get a random number and then select a specific row using this number.

    In the case that all the rows have unique ids we will just have to pick a random number between the smallest and the biggest id and then select the row with id that equals that number. To make this method work when ids are not evenly distributed we will have to use “>=” operator instead of “=” in the last query.

    To get the minimum and maximum id values in the entire table we will use MAX() and MIN() aggregate functions. These functions will return minimum and maximum value in the specified group. The group in our case is all the values of `id` column in our table.

    Solution 2 [PHP]
    $range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` ");
    $range_row = mysql_fetch_object( $range_result );
    $random = mt_rand( $range_row->min_id , $range_row->max_id );
    $result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");

    As we mentioned this method is limited to tables with unique id for each row. What to do if it’s not the case?

    The solution is to use the MySQL LIMIT clause. LIMIT accepts two arguments. The first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1).

    To calculate the offset to the first row we will generate a random number between 0 and 1 using MySQL’s RAND() function. Then we will multiply this number by number of records in the table, which we will get using COUNT() function. Since LIMIT arguments must be integers and not float values we will round the resulting number using FLOOR() function. FLOOR() is an arithmetic function that calculates the largest integer value that is smaller than or equal to the expression. The resulting code will look like this:

    Solution 3 [PHP]
    $offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
    $offset_row = mysql_fetch_object( $offset_result );
    $offset = $offset_row->offset;
    $result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );

    In MySQL 4.1 and later we can combine two previous methods using subquery like so:

    Solution 4 [SQL]
    SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;

    This solution has the same weakness as the solution 2 e.g. it only works for tables with unique ids.

    Remember the reason we started looked for alternative ways of selecting random rows? Speed! So how do these methods compare in terms of execution times. I am not going to go into specifics of hardware and software configuration or give precise numbers. The approximate results are:

    • The slowest method is solution 1. Let’s say that it took 100% of time to execute.
    • Solution 2 took 79%.
    • Solution 3 – 13%.
    • Solution 4 – 16%.

    The winner is solution 3.

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

    Drag N Drop File Upload With Progress Bar

    Posted by sarapeter on July 4, 2008

    Make your site more user friendly. With Rad Upload’s drag and drop functionality, your visitors can transfer files to your server just as easily as copying from one folder to another.

    The lite edition is available for free download. It does not expire and contains most of the features of the standard edition. Rad Upload Plus has many advanced features such as client side filtering and on the fly GZip compression.

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

    PHP Captcha Security Images for Anti Spamming

    Posted by sarapeter on July 4, 2008

    <?php
    session_start();
    
    /*
    * File: CaptchaSecurityImages.php
    * Author: Simon Jarvis
    * Copyright: 2006 Simon Jarvis
    * Date: 03/08/06
    * Updated: 07/02/07
    * Requirements: PHP 4/5 with GD and FreeType libraries
    * Link: http://www.white-hat-web-design.co.uk/articles/php-captcha.php
    *
    * This program is free software; you can redistribute it and/or
    * modify it under the terms of the GNU General Public License
    * as published by the Free Software Foundation; either version 2
    * of the License, or (at your option) any later version.
    *
    * This program is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    * GNU General Public License for more details:
    * http://www.gnu.org/licenses/gpl.html
    *
    */
    
    class CaptchaSecurityImages {
    
       var $font = 'monofont.ttf';
    
       function generateCode($characters) {
          /* list all possible characters, similar looking characters and vowels have been removed */
          $possible = '23456789bcdfghjkmnpqrstvwxyz';
          $code = '';
          $i = 0;
          while ($i < $characters) {
             $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
             $i++;
          }
          return $code;
       }
    
       function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
          $code = $this->generateCode($characters);
          /* font size will be 75% of the image height */
          $font_size = $height * 0.75;
          $image = imagecreate($width, $height) or die('Cannot initialize new GD image stream');
          /* set the colours */
          $background_color = imagecolorallocate($image, 255, 255, 255);
          $text_color = imagecolorallocate($image, 20, 40, 100);
          $noise_color = imagecolorallocate($image, 100, 120, 180);
          /* generate random dots in background */
          for( $i=0; $i<($width*$height)/3; $i++ ) {
             imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
          }
          /* generate random lines in background */
          for( $i=0; $i<($width*$height)/150; $i++ ) {
             imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
          }
          /* create textbox and add text */
          $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
          $x = ($width - $textbox[4])/2;
          $y = ($height - $textbox[5])/2;
          imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
          /* output captcha image to browser */
          header('Content-Type: image/jpeg');
          imagejpeg($image);
          imagedestroy($image);
          $_SESSION['security_code'] = $code;
       }
    
    }
    
    $width = isset($_GET['width']) && $_GET['height'] < 600 ? $_GET['width'] : '120';
    $height = isset($_GET['height']) && $_GET['height'] < 200 ? $_GET['height'] : '40';
    $characters = isset($_GET['characters']) && $_GET['characters'] > 2 ? $_GET['characters'] : '6';
    
    $captcha = new CaptchaSecurityImages($width,$height,$characters);
    
    ?>
    Download Link

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