Categories
PHP Tips & Tutorials

PHP: How to process a string one byte (character) at a time

If you want to loop through a literal string in PHP and have the opportunity to look and process each of the characters one character at a time, use the following snippet:

$string = "Hooray";
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
    echo $string[$i].', ';
}

There you go, just use $string_variable[$char_index] to access each of the characters in a string. With non-multi-byte encoding, a byte is a character.

strlen() function returns the length of a string.

Categories
PHP Tips & Tutorials

PHP: Check if a string contains another string or substring

As a web site templating language, string processing is what PHP is good at. There’s always a chance that you need to verify and make sure if a string contains another string. For example, to check if an at sign is included in the entered email address by a visitor:

if (strpos($_POST['email'], '@') !== false) {
    echo 'The email address has @ in it.';
}

Technically, strpos() function returns the index location of the first character of the specified substring if it finds it. If it fails in locating the substring in the string, it returns boolean false. As it’s possible that the substring may start in the very beginning of the father string thus strpos() returning 0 which is interpreted as false in PHP, a absolute comparison of !== is required.

Categories
PHP Tips & Tutorials

PHP: Getting the Current Date and Time

Programmably, there are several different types of date and time in PHP you can create and process. Consequently, you have several types of current date and time in PHP that can be generated and used.

Below is a list of functions that returns the current date and time:

  1. The current Unix timestamp: time()
  2. The current date and time information returned as an array: getdate()
  3. The formatted locale string of current date and time: strftime()
  4. The formatted string of current date and time: time()
  5. The current local date and time values returned as an array: localtime()
Categories
PHP Tips & Tutorials

PHP: How to access a global variable inside a function without passing it?

Ideally, global variables outside a function can not and should not be accessed from within the function to hold up the programming modularization paradigm.

However, if you really need to do this, especially in small programs, you can declare the variable again inside the function by the keyword ‘global’ so as to use inside the local scope it by reference without passing the variable as an argument.

function eat_fruit($fruit) {
   global $chew_count;

   for ($i = $chew_count; $i > 0; $i--) {
       ...
   }
}
Categories
PHP Tips & Tutorials

PHP: Detecting Different Browsers

As we all know that JavaScript is usually what involves in detecting different browsers and their varying capabilities. PHP has the very function that parses the HTTP request headers sent by client web browsers so as to determine the identify of the requesting browser as well as its capabilities.

To get client browser information and detect browsers in PHP:

$browser = get_browser(); // $browser is an array containing all information about the requesting browser
if ($browser->frames) {
    // print out a frame-based layout
} elseif ($browser->tables) {
    // print out a table-based layout
} else {
    // print out a boring layout
}

Yep, get_browser() is just the function we need. Also, there’s a lot more fields than those just shown here, the table below refers them all.

Browser capability object properties

Property

Description

platform

Operating system the browser is running on (e.g., Windows, Macintosh, Unix, Win32, Linux, MacPPC)

version

Full browser version (e.g., 5.0, 3.5, 6.0b2)

majorver

Major browser version (e.g., 5, 3, 6)

minorver

Minor browser version (e.g., 0, 5, 02)

frames

1 if the browser supports frames

tables

1 if the browser supports tables

cookies

1 if the browser supports cookies

backgroundsounds

1 if the browser supports background sounds with <embed> or <bgsound>

vbscript

1 if the browser supports VBScript

javascript

1 if the browser supports JavaScript

javaapplets

1 if the browser can run Java applets

activexcontrols

1 if the browser can run ActiveX controls

Categories
HTTP Tips & Tutorials PHP Tips & Tutorials

PHP cURL: Fetching URL and Sending Request with Cookies

One of the things the remote web server inspects is the client cookie to know about the requester. If you need cURL to simulate a user browser that sends cookie information to the web server, you need the following options:

$c = curl_init('http://www.example.com/needs-cookies.php');
curl_setopt ($c, CURLOPT_COOKIE, 'user=ellen; activity=swimming');
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec ($c);
curl_close ($c);

So, the HTTP request cURL sends out to www.example.com will take the cookie data with it, thus the remote script needs-cookies.php knows the information and determines that the request is sent from the user ellen’s web browser.

Categories
HTTP Tips & Tutorials PHP Tips & Tutorials

PHP cURL: Making POST Request to URL

By default, all HTTP requests made out by cURL is GET requests that simply fetches the URL and don’t submit any more POST variables.

However, if you need to fetch and retrieve URL by the POST method with cURL, you need the snippet below:

$url = 'http://www.example.com/submit.php';
// The submitted form data, encoded as query-string-style
// name-value pairs
$body = 'monkey=uncle&rhino=aunt';
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec ($c);
curl_close ($c);

Make sure you have set CURLOPT_POST to true and attached the POST variables in the form of a GET series of name=value couples by CURLOPT_POSTFIELDS.

Categories
PHP Tips & Tutorials

PHP: GD Library Drawing Functions Reference

To draw a line, use ImageLine( ):

ImageLine($image, $x1, $y1, $x2, $y2, $color);

To draw an open rectangle, use ImageRectangle( ):

ImageRectangle($image, $x1, $y1, $x2, $y2, $color);

To draw a solid rectangle, use ImageFilledRectangle( ):

ImageFilledRectangle($image, $x1, $y1, $x2, $y2, $color);

To draw an open polygon, use ImagePolygon( ):

$points = array($x1, $y1, $x2, $y2, $x3, $y3);
ImagePolygon($image, $points, count($points)/2, $color);

To draw a filled polygon, use ImageFilledPolygon( ):

$points = array($x1, $y1, $x2, $y2, $x3, $y3);
ImageFilledPolygon($image, $points, count($points)/2, $color);

To draw an arc, use ImageArc( ):

ImageArc($image, $x, $y, $width, $height, $start, $end, $color);

To draw an ellipse, use ImageArc( ) and set $start to 0 and $end to 360:

ImageArc($image, $x, $y, $width, $height, 0, 360, $color);

To draw a circle, use ImageArc( ), set $start to 0, set $end to 360, and use the same value for both $width and $height:

ImageArc($image, $x, $y, $diameter, $diameter, 0, 360, $color);

For built-in GD fonts, use ImageString( ):

ImageString($image, 1, $x, $y, 'I love PHP Cookbook', $text_color);

For TrueType fonts, use ImageTTFText( ):

ImageTTFText($image, $size, 0, $x, $y, $text_color, '/path/to/font.ttf',
             'I love PHP Cookbook');

For PostScript Type 1 fonts, use ImagePSLoadFont( ) and ImagePSText( ):

$font = ImagePSLoadFont('/path/to/font.pfb');
ImagePSText($image, 'I love PHP Cookbook', $font, $size,
            $text_color, $background_color, $x, $y);

Use ImageColorTransparent( ):

$color = ImageColorAllocate($image, $red, $green, $blue);
ImageColorTransparent($image, $color);
Categories
Hosting Tips & Deals PHP Tips & Tutorials

PHP: Change Error Reporting Level | Different PHP Error Types

Debugging a PHP script, you may want to alter the error-displaying sensitivity on a particular page and control what types of errors should be reported.

The solution is the PHP error reporting function error_reporting():

error_reporting(E_ALL);                // everything
error_reporting(E_ERROR | E_PARSE);    // only major problems
error_reporting(E_ALL & ~E_NOTICE);    // everything but notices

As the parameters of the function, &, | and ~ are all bitwise operators to determine what kind of errors are to be reported. Be advised by the following explanation:

  1. | stands for ‘OR’.
  2. & stands for ‘AND’.
  3. ~ stands for ‘NOT’.
PHP Error Types

Value

Constant

Description

Catchable

1

E_ERROR

Nonrecoverable error

No

2

E_WARNING

Recoverable error

Yes

4

E_PARSE

Parser error

No

8

E_NOTICE

Possible error

Yes

16

E_CORE_ERROR

Like E_ERROR but generated by the PHP core

No

32

E_CORE_WARNING

Like E_WARNING but generated by the PHP core

No

64

E_COMPILE_ERROR

Like E_ERROR but generated by the Zend Engine

No

128

E_COMPILE_WARNING

Like E_WARNING but generated by the Zend Engine

No

256

E_USER_ERROR

Like E_ERROR but triggered by calling trigger_error( )

Yes

512

E_USER_WARNING

Like E_WARNING but triggered by calling trigger_error( )

Yes

1024

E_USER_NOTICE

Like E_NOTICE but triggered by calling trigger_error( )

Yes

2047

E_ALL

Everything except E_STRICT

N/A

2048

E_STRICT

Runtime notices in which PHP suggests changes to improve code quality (since PHP 5)

N/A

Categories
PHP Tips & Tutorials

PHP: What is Hash? | Hashing a String | Generate Hash of Strings

A hash or digest can be thought of as the digital fingerprint of a piece of data. Hash is usually generated from any string of text in a fixed length by a one-way mathematical process. It is next to impossible to re-engineer the original text or data from the hash alone. Also, it is vast impossible that any different text strings share an identical hash.

Thus, a hash of a string is usually used to encrypt clear text yet to maintain the possibility to compare encrypted texts for identicalness or check if the original text has been modified in any way.

To hash a string or get the hash of a string in PHP, use sha1() instead of md5() which is inferior than sha1() with regards to security.

$hash = sha1('The deal is $120,000 in total.');

And $hash contains the sha1 hash of the string in the argument. Here’s a better read on how to hash your passwords.