PHP Tutorial – a Beginner’s Basic PHP Guide Part 2

arp14 PHP, Tutorial Tags: , , , 0

Check the first part of this PHP tutorial – PHP Tutorial – a Beginner’s Basic PHP Guide Part 1 before continue reading this part.

Working with Strings in PHP

A string is traditionally a sequence of characters or symbols. Generally there is no limit of charecters on a string in PHP.

String Functions

Very common string functions in PHP are ereg(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), and strstr(). See more on php.net

<?php
	$str = "A quick    brown fox    jumped over    the lazy dog.   ";

	// trim removes extra white spaces
	echo trim($str); // other trim functions are ltrim, rtrim, chop
	// find string length
	echo strlen($str)."<br />";

	// subtracting string
	echo substr($str, 1)."<br />"; // removing character from left to right
	echo substr($str, 1, 5)."<br />"; // removing 1 chars from left then pick 5 chars after that
	echo substr($str, -1)."<br />"; // just moves the cursor, nothing else
	echo substr($str, 0, -7)."<br />"; // remove 6 chars from right to left then pic rest
	echo substr($str, -6, 2)."<br />"; // take 6th char and continue up to 2 chars from right to left
	echo $str{4}; // use string array
	echo '<hr />';
	// note: for those negative values, 1 char is used to swap the direction

	// change case of a string
	echo strtoupper($str)."<br />"; // making a string uppercase
	echo strtolower($str)."<br />"; // making a string lowercase
	echo ucfirst($str)."<br />"; // making uppercase first char
	echo ucwords($str)."<br />"; // making uppercase first char of each words

	// find and replace within string - case-sensitive /in-sensitive version is stri_replace()
	echo str_replace("quick", "fast", $str)."<br />";

	// search string withing string
	if (strpos($str, 'fox') === true) echo 'Fox found.<br />';
	else echo 'Fox not found.<br />';

	// string to array and array to string
   $str_arr = explode(" ", $str); // exploding string to array by each white space
   print_r($str_arr);
   $str_back = implode($str_arr, " "); // imploding array string separate by white space
   echo $str_back;
	// str_split() also converts string to array, by character length.
	// join() is Alias of implode.
?>

Escaping Strings

\
the common escape indicator
\n
Newline (ASCII 10)
\r
Carriage return (ASCII 13)

\t

Tab (ASCII 9)
\\
\
\$
$
\”
\0 .. \777
Octal (base 8) number
\x0 .. \xFF
Hexadecimal (base 16) number
%%
%

htmlspecialchars converts the following characters:
(htmlentities converts all test that is possible to convert to html representation)

  • ‘&’ (ampersand) becomes ‘&amp;’
  • ‘”‘ (double quote) becomes ‘&quot;’ when ENT_NOQUOTES is not set.
  • ”’ (single quote) becomes ‘&#039;’ only when ENT_QUOTES is set.
  • ‘<‘ (less than) becomes ‘&lt;’
  • ‘>’ (greater than) becomes ‘&gt;’

Parsing a String

<?php 
// parsing string using parse_str function
	$str = "a=123&b=qqew&c=sd76";
	parse_str($str);
	echo $a."<br />".$b."<br />".$c."<br />";

	$str ="arr[]=123&arr[]=234&arr[]=abc";
	parse_str($str);
	echo $arr[0]."<br />".$arr[1]."<br />".$arr[2]."<br />";

	$str = "a=apple&b=ball&c=cat";
	parse_str($str, $op);
	echo $op['a']."<br />".$op['b']."<br />".$op['c']."<br />";
?>

sprintf() and printf()

<?php // similar to c/c++
	$num = 100; $item = "Tablet";
	$format = "There are %d %s in your cart." ;
	printf ( $format , $num , $item );

	$month = "08"; $day = "12"; $year = "1990";
	$dt = sprintf ( "%04d-%02d-%02d" , $year , $month , $day );
	echo $dt; 
?>

Chart of possibilities:

%
a literal percent character.
b
an integer presented as a binary number.
c
an integer presented as a character with that ASCII value.
d
an integer presented as a (signed) decimal number.
e
a number presented as scientific notation (e.g. 2.4e+5).
u
an integer presented as an unsigned decimal number.
f
a float presented as a floating-point number (locale aware).
F
a float presented as a floating-point number (non-locale aware).
(PHP 4.3.1+ and PHP 5.0.3+)
o
an integer presented as an octal number.
s
a string presented as a string.
x
an integer presented as a hexadecimal number.
(output as lowercase letters).
X
an integer presented as a hexadecimal number.
(output as uppercase letters).

Example outputs:

$n = 1234567890;
$u = -1234567890;
$c = 65; // ASCII 65 is 'F'

%b = '1001001100101100000001011010010'
%s = '1234567890'
%c = 'F'

%d = '1234567890'
%u = '1234567890'
%u = '3060399406'

%e = '1.234568e+9'
%f = '1234567890.000000'

%o = '11145401322'
%x = '499602d2'
%X = '499602D2'

%+d = '+1234567890'
%+d = '-1234567890'

Working with Web Forms in PHP

Web forms are very important to receive user inputs. You can catch those users inputs and process the input values with PHP. There are two methods to pass user inputs, get method and post method. In GET method characters are restricted only to 256 characters. But in the case of POST method characters has no limit. Get method will be visible to the user as it sent appended to the URL, but data sent by Post method will not be visible as it is sent encapsulated within the HTTP request body.

Processing Web Forms with PHP using get method

By using get method, we can exchange, carry values from one page to another.

<!-- The action attribute receives the file name, where the data to be submitted. 
$_SERVER['PHP_SELF'] dynamically referring the document itself. -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="get">
	Name: <input name="name" type="text" /><br />
	Phone: <input name="phone" type="text" /><br />
	Email: <input name="email" type="text" /><br />
	<input name="submit" type="submit" /><br />
</form>

<?php // please notice the URL/Address bar of browser
if (isset($_GET['submit'])) {
	$name = $_GET['name'];
	$phone = $_GET['phone'];
	$email = $_GET['email'];

	echo "Name: {$name}<br />";
	echo "Phone: {$phone}<br />";
	echo "Email: {$email}<br />";
}
?>

Processing Web Form with PHP using post method

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
	Name: <input name="name" type="text" /><br />
	Phone: <input name="phone" type="text" /><br />
	Email: <input name="email" type="text" /><br />
	<input name="submit" type="submit" /><br />
</form>

<?php // please notice the URL/Address bar of browser
if (isset($_POST['submit'])) {
	$name = $_POST['name'];
	$phone = $_POST['phone'];
	$email = $_POST['email'];

	echo "Name: {$name}<br />";
	echo "Phone: {$phone}<br />";
	echo "Email: {$email}<br />";
}
?>

Get server variables

<?php	foreach($_SERVER as $key => $val) echo $key ." => ". $val."<br />"; ?>

Processing CheckBox, Radio Buttons, Selection Lists and Hidden inputs

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
	Married: <input name="married" type="checkbox" value="true"><br />
	No of Legs:<br />
		one <input name="legs" type="radio" value="1">
		two <input name="legs" type="radio" value="2" checked><br />
		<select name="os" size="5">
       	<option value="-1" selected>Please select one or more...</option>
       	<option>Windows</option>
       	<option>Mac OS X</option>
       	<option>Older Mac</option>
       	<option>Linux</option>
       	<option>Other</option>
       </select>
	Hidden status: <input type="hidden" name="status" value="ok" />
	<input name="submit" type="submit" /><br />
</form>

<?php // please notice the URL/Address bar of browser
if (isset($_POST['submit'])) {
	$married = isset($_POST['married']) ? $_POST['married'] : false;
	$legs = $_POST['legs'];
	$os = $_POST['os'];
	$status = $_POST['status'];

	echo "Married: {$married}<br />"; // if checked, returns the value, if no value 
	// is set then - returns on, otherwise it's not even set or/and empty
	echo "No of Legs: {$legs}<br />";
	echo "Operating System: {$os}<br />";
	echo "Hidden status: {$status}<br />";
	// note: hidden input only works on different submitted location than it's own.
	// means, you must submit the form to different location than where the form is.
}
?>

Form Validation

Any kind of user input is not safe to do stuffs with those inputs until it get validated from client side first then server side. A user can put a invalid email or phone number or a 1000 charters long string name. A bad user may inject some harmful code and then even can delete all we’ve. So we need to validate HTML forms with PHP, as below.

 
<h3>Register:</h3>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
  Username: <input type="text" name="username" value="" /><br />
  Password: <input type="password" name="password" value="" /><br />
  Confirm Password: <input type="password" name="confirm_password" value="" /><br />
  Name: <input type="text" name="name" value="" /><br />
  Age: <input type="text" name="age" value="" /><br />
  Married:
  	yes <input name="married" type="radio" value="yes">
  	no <input name="married" type="radio" value="no" checked><br />
  Phone: <input name="phone" type="text" value=""><br />
  Are you agree with our TOS?: <input name="tos" type="checkbox" checked><br />
  <input type="submit" name="submit" value="register" />
</form>

<?php
  $username = mysql_real_escape_string($_POST["username"]);
  $password = mysql_real_escape_string($_POST["password"]);
  $confirm_password = mysql_real_escape_string($_POST["confirm_password"]);
  $name = mysql_real_escape_string($_POST["name"]);
  $age = mysql_real_escape_string($_POST["age"]);
  $married = mysql_real_escape_string($_POST["married"]);
  $phone = mysql_real_escape_string($_POST["phone"]);
  if (isset($_POST["tos"])) $tos = mysql_real_escape_string($_POST["tos"]);

  $error = "";
  if (isset($_POST["submit"])) { // if the form been submitted, start validate it
  if (strlen($username)==0 || strlen($username)>=20 || is_numeric($username)==true) 
  $error .= "Invalid username: It must be less that 20 alpha chars long.<br />";

  if (strlen($password)==0 || strlen($password)>=20)
  $error .= "Invalid password: It must be less that 20 chars long.<br />";
  if ($password != $confirm_password)
  $error .= "Invalid confirm password: It did not matched.<br />";
  if (strlen($name)==0 || strlen($name)>=20 || is_numeric($name)==true) 
  $error .= "Invalid name: It must be less that 20 alpha chars long.<br />";

  if (!is_numeric($age) || $age<=18 || $age>=99)
  $error .= "Invalid age: It must be numeric and between 18 to 99.<br />";  

  if (!is_numeric($phone) || strlen($phone)>10 || strlen($phone)<8)
  $error .= "Invalid phone: It must be numeric and between 7 to 10 digits.<br />";
  if (!isset($tos)) $error .= "You must be agree with out TOS.<br />";
  }  

  if (isset($_POST["submit"]) && $error=="") {
  echo "Registered successfully!";
  // do stuffs with safe data
  }

  echo $error;
?>

In the code above, we are initializing $error with blank value. Then if the form been submitted, we do start validate the unsafe data. For each inputs we are checking each inputs wit certain conditions and if matched or unmatched, add the particular error to $error. After all if $error stays blank then do stuffs with safe data. At last we are printing $error. To prevent SQL injection, we’re passing inputs through PHP built-in function “mysql_real_escape_string()”.

Working with Functions in PHP

Using and Defining Functions

While defining a function, it has three parts – function name, arguments/parameters, and definition body.

<?php
// a function that can add two number
	function add($x, $y){
		return ($x + $y);
	}

// a function without any argument/parameter
	function filename(){
		return basename($_SERVER['PHP_SELF']);
	}

// reference parameter
	function test_ref($var1, &$var2){ // add ampersand before a parameter to use it as reference
		$var1 = 500;
		$var2 = 1000;
		echo $var1 .', '. $var2;
	}

// calling those functions we defined above
	echo add(10, 12); // output: 15
	echo filename(); // output: *the current working directory name*

// calling test_ref() function
	$a = "this is a string";
	$b = "this is another";

	// showing the actual variables before we touch them
	echo $a . "<br />";
	echo $b . "<br />";

	// showing them via the test_ref() function
	test_ref($a, $b); // output: 500, 1000
	echo "<br />";

	// again showing them
	echo $a . "<br />"; // output: this is a string
	echo $b . "<br />"; // output: 1000 // note: this has been changed forever
?>

Use func_num_args() to get the number of arguments in a function. Use func_get_arg() to get arguments’ array. Global variables won’t be visible inside a function. Global is to be used within a function to see variables at the page level.

Require and Includes

The require() and include() functions are identically same but if a fatal error occurred, the require will stop executing the script where include will try to continue. There are also include_once() and require_once(). If a file already been included, it will not include it again. To keep user defined functions and classes apart from presentation, it is good to make the functions and classed stay outside and include then when needed. See example codes below:

<?php
	include("functions.php");
	// or,
	include_once("functions.php");
	// or,
	require("functions.php");
	// or,
	require_once("functions.php");

// you can write all user defined on function.php (or any file name)
?>

Working with Databases (PHP-MySQL)

There are basically five steps to do work with databases. Before all of those, make a file where all Database Constants will be defined and keep that file placed one or two upper level directories from your root level where no one can get it. So, here is the db_cons.php as below.

<?php
	define("DB_SERVER", "your_server_name");
	define("DB_NAME", "your_db_name");
	define("DB_USER", "username");
	define("DB_PASS", "password");
?>

1. Create a database connection

<?php
	require_once("../../path/to/db_cons.php");

	$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
	if (!$connection) die("Database connection failed: ", mysql_error() );

2. Select a database to use

	$db_select = mysql_select_db(DB_NAME, $connection);
	if (!$db_select) die("Database selection failed: ", mysql_error() );

3. Perform database query

	$sql = "SELECT * FROM table_name";
	$results = mysql_query($sql, $connection); /* specifying connection is not necessary,
		but it is must when there are more than one connection */
	if (!$results) die("Database query failed: ", mysql_error() );

4. Use returned data

	while ($row = mysql_fetch_array($results)) {
		// do stuffs with returned data
	}

5 .Close database connection

	if (isset($connection)) {
		mysql_close($connection);
		unset();
	}
?>

Other mysql important functions

mysql_num_rows() – this will return the number of rows.
mysql_insert_id() – this will return the last id inserted over last connection.
mysql_affected_rows() – this will return number of last affected rows.

Working with Sessions and Cookies

To work with sessions, we must start it first by calling function session_start() at the top of the page before a single character even a white space appears.

Register session variables and assign their values

<?php
// starting session
	session_start();

	$_SESSION['STATUS'] = "Online";
	$_SESSION['USERID'] = "1234";
	$_SESSION['USERNAME'] = "Arpan";

// unregister and unset session
	unset($_SESSION['USERNAME']);

// check current registered session variables (debug purpose only)
	foreach ($_SESSION as $k => $v)	echo $k." => ".$v."<br />";
?>

Cookies – setcookie

Cookies are part of the HTTP headers. Setting cookies (setcookie()) must be called before and single character sent to the browser. After setting a cookie, you must refresh the page the get the value of that cookie. Try the codes below.

<?php
	$str = "hello world!";
	setcookie("testcookie1", $str);
	setcookie("testcookie2", "This is a test cookie!");

	setcookie("testcookie3", "Arpan", time()+3600); // expire in 1 hour

// note: in setcookie function, there are other additional parameters
// syntax: setcookie(name,value,expire,path,domain,secure)

// get those cookies you made
	echo $_COOKIE["testcookie1"]."<br />";
	echo $_COOKIE["testcookie2"]."<br />";
	echo $_COOKIE["testcookie3"]."<br />";

// check all registred cookies (debug purpose only)
	foreach ($_COOKIE as $k => $v) echo $k." => ".$v."<br />";

// delete/unset/expire cookies
	setcookie("testcookie1", "", time()-1); // setting value to blank, make it expired
// or,
	setcookie("testcookie1"); // setting value to nothing
// or,
	unset($_COOKIE["testcookie1"]); // unset it
// or you can do all of three above for extra security
?>

If you have any problem with learning PHP, please comment below, I’ll be back to you.
Thank you.

Leave a Reply

Note: Your email address will not be published. Required fields are marked *