Recent Posts

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Detecting PHP request type (GET, POST, PUT or DELETE)

To detect the PHP request type this is doing by using:

$_SERVER['REQUEST_METHOD']
For more details please see the documentation for the $_SERVER variable.

Start with and end with string function on PHP


This two functions take a string a verify if it starts with a specified character/string or ends with it

For example:

$str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
Functions code:

function startsWith($haystack, $needle)
{
    return $needle === "" || strpos($haystack, $needle) === 0;
}
function endsWith($haystack, $needle)
{
    return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}

var_dump(startsWith("hello world", "hello")); // true
var_dump(endsWith("hello world", "world"));   // true
Java and .NET implementations of String.StartsWith and String.EndsWith return true if needle is an empty string. Answer revised accordingly.

This another function is faster for large haystack:

function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}



Convert a HTML and CSS document to PDF with PHP

To convert an HTML document with CSS stylesheets you have to take a look at PrinceXML.

It's definitely the best HTML/CSS to PDF converter out there, although it's not free (But hey, your programming is not free either, so if it saves you 10 hours of work, you're home free.)

Oh yeah, did I mention that this is the first (and probably only) HTML2PDF solution that does full ACID2!?

PrinceXML Samples

Regular expression to validate email address

There is no simple regular expression for this problem: see this fully RFC‑822–compliant regex, which is anything but simple. (It was written before the days of grammatical patterns.) The grammar specified in RFC 5322 is too complicated for primitive regular expressions, although the more sophisticated grammatical patterns in Perl, PCRE, and PHP can all manage to correctly parse RFC 5322 without a hitch. Python and C# should also be able to manage it, but they use a different syntax from those first three.

However, if you are forced to use one of the many less powerful pattern-matching languages, then it’s best to use a real parser. But understand that validating it per the RFC tells you absolutely nothing about whether the person entering the address is its true owner. People sign others up to mailing lists this way all the time. Fixing that requires a fancier kind of validation that involves sending that address a message that includes a confirmation token meant to be entered in the same web page as was the address.

That's the only way to know you got the address of the person entering it, which is why most mailing lists now use that mechanism to confirm sign-ups. After all, anybody can put down president@whitehouse.gov, and that will even parse as legal, but it isn’t likely to be the person at the other end.

For PHP, you should not use the pattern given in Validate an E-Mail Address with PHP, the Right Way from which I quote:

There is some danger that common usage and widespread sloppy coding will establish a de facto standard for e-mail addresses that is more restrictive than the recorded formal standard.

That is no better than all the other non-RFC patterns. It isn’t even smart enough to handle even RFC 822, let alone RFC 5322.

If you want to get fancy and pedantic, implement a complete state engine. A regular expression can only act as a rudimentary filter. The problem with regular expressions is that telling someone that their perfectly valid e-mail address is invalid (a false positive) because your regular expression can't handle it is just rude and impolite from the user's perspective. A state engine for the purpose can both validate and even correct e-mail addresses that would otherwise be considered invalid as it disassembles the e-mail address according to each RFC. This allows for a potentially more pleasing experience, like

The specified e-mail address 'myemail@address,com' is invalid. Did you mean 'myemail@address.com'?

See also Validating Email Addresses, including the comments. Or Comparing E-mail Address Validating Regular Expressions.

How to solve: number_format() expects parameter 1 to be double, string given

This error is common when the function number_format recieves an empty string or a string with special characters. To solve this you can use floatval to make the conversion to float.

number_format( floatval ($string_variable), 2); 

How to solve Undefined variable: _SESSION PHP

If you have this error then you must to call to session_start in the begining (at the top) of each php file where you want to use sessions

How to parse string to float in PHP

If you want to parse a string to float type then you can use floatval:

float floatval  ( mixed $var  ) - Gets the float value of a string.

<?php
 $var = '122.34343The';
 $float_value_of_var = floatval($var);
 echo $float_value_of_var; // 122.34343
?>
Or you can do a cast with (float):

$rootbeer = (float) $InvoicedUnits;



PHP: Function eregi() is deprecated

eregi() is deprecated as of PHP 5.3, use preg_match() instead.

Note that preg_match() is only case insensitive when you pass the i modifier in your regular expression. Example:

include 'db_connect.php'; 
if(isset($_POST['Submit']))           
{            
    $acc_type=ucwords($_POST['acc_type']);
    $minbalance=ucwords($_POST['minbalance']);

    // Removed A-Z here, since the regular expression is case-insensitive                
    if (!preg_match("/^[a-z ]+$/i", stripslashes(trim($acc_type))))//line 20 
    {                 
        echo "Enter Valid Data for Account Type!";                
        exit(0);                 
    }           
    else 
    {                  
        // \d and 0-9 do the same thing
        if (!preg_match("/^[\d ]+$/", stripslashes(trim($minbalance))))//line 27
        {
        }
    }
} 

Sending HTML email with PHP

It turns out the key is the encoding type. Instead of:

Content-Type: text/plain; charset="iso-8859-1"
I needed to use:

Content-Type: text/plain; charset=us-ascii
It might depend on stuff as detailed as how you save the PHP file in your own text editor. I haven't looked into it, but the iconv function in PHP may have brought me some joy too. So I think this part is really sensitive.

Here is a better snippet of sample code that shows the whole thing end-to-end:

$notice_text = "This is a multi-part message in MIME format.";
$plain_text = "This is a plain text email.\r\nIt is very cool.";
$html_text = "<html><body>This is an <b style='color:purple'>HTML</b> text email.\r\nIt is very cool.</body></html>";

$semi_rand = md5(time());
$mime_boundary = "==MULTIPART_BOUNDARY_$semi_rand";
$mime_boundary_header = chr(34) . $mime_boundary . chr(34);

$to = "Me <foo@gmail.com>";
$from = "Me.com <me@me.com>";
$subject = "My Email";

$body = "$notice_text

--$mime_boundary
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

$plain_text

--$mime_boundary
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

$html_text

--$mime_boundary--";

if (@mail($to, $subject, $body,
    "From: " . $from . "\n" .
    "MIME-Version: 1.0\n" .
    "Content-Type: multipart/alternative;\n" .
    "     boundary=" . $mime_boundary_header))
    echo "Email sent successfully.";
else
    echo "Email NOT sent successfully!";

exit;



Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in PHP


ini_set('memory_limit', '-1');

With this line will take unlimited memory usage of server.

PHP: Convert SVG image to PNG


$usmap = '/path/to/blank/us-map.svg';
$im = new Imagick();
$svg = file_get_contents($usmap);

/*loop to color each state as needed, something like*/ 
$idColorArray = array(
     "AL" => "339966"
    ,"AK" => "0099FF"
    ...
    ,"WI" => "FF4B00"
    ,"WY" => "A3609B"
);

foreach($idColorArray as $state => $color){
//Where $color is a RRGGBB hex value
    $svg = preg_replace(
         '/id="'.$state.'" style="fill:#([0-9a-f]{6})/'
        , 'id="'.$state.'" style="fill:#'.$color
        , $svg
    );
}

$im->readImageBlob($svg);

/*png settings*/
$im->setImageFormat("png24");
$im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1);  /*Optional, if you need to resize*/

/*jpeg*/
$im->setImageFormat("jpeg");
$im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/

$im->writeImage('/path/to/colored/us-map.png');/*(or .jpg)*/
$im->clear();
$im->destroy();
The steps regex color replacement may vary depending on the SVG path xml and how you id & color values are stored. If you don't want to store a file on the server, you can output the image as base 64 like

<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '"  />';?>
(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg

you can see an example here I did for a former employer's sales territory map:

Start: http://upload.wikimedia.org/wikipedia/commons/3/32/Blank_US_Map.svg