Category Archives: SynapseIndia Elance

SynapseIndia Php Development – File Write

Now that you know how to open and close a file, lets get on to the most useful part of file manipulation, writing! There is really only one main function that is used to write and it’s logically called fwrite.

php – file open: write

Before we can write information to our test file we have to use the functionfopen to open the file for writing.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');

php – file write: fwrite function

We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite’s first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you’re good to go!

Below we are writing a couple of names into our test file testFile.txt and separating them with a carriaged return.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);

The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second containedTracy Tanner. After we finished writing we closed the file using the fclose function.

If you were to open the testFile.txt file in NOTEPAD it would look like this:

Contents of the testFile.txt File:

Bobby Bopper
Tracy Tanner

php – file write: overwriting

Now that testFile.txt contains some data we can demonstrate what happens when you open an existing file for writing. All the data contained in the file is wiped clean and you start with an empty file. In this example we open our existing filetestFile.txt and write some new data into it.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);
$stringData = "Pointy Pinto\n";
fwrite($fh, $stringData);
fclose($fh);

If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present.

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto

In the next lesson we will show you how to get information out of a file by using PHP’s read data function

SynapseIndia Php Development – ile close

The next logical step after you have opened a file and finished your business with it is to close that file down. You don’t want an open file running around on your server taking up resources and causing mischief!

php – file close description

In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it’s a good programming practice and because we told you to!

php – file close function

In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.

PHP Code:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The function fclose requires the file handle that we want to close down. In our example we set our variable “$fileHandle” equal to the file handle returned by thefopen function.

After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function.

SynapseIndia Php Development – if/else conditional statment

Has someone ever told you, “if you work hard, then you will succeed”? And what happens if you do not work hard? Well, you fail! This is an example of an if/else conditional statement.

  • If you work hard then you will succeed.
  • Else, if you do not work hard, then you will fail.

How does this translate into something useful for PHP developers? Well consider this:

Someone comes to your website and you want to ask this visitor her name if it is her first time coming to your site. With an if statement this is easy. Simply have a conditional statement to check, “are you visiting for the first time”. If the condition is true, then take them to the “Insert Your Name” page, else let her view the website as normal because you have already asked her for her name in the past.

if/else an example

Using these conditional statements can add a new layers of “cool” to your website. Here’s the basic form of an if/else statement in PHP.

PHP Code:

$number_three = 3;

if ( $number_three == 3 ) {
	echo "The if statement evaluated to true";
} else {
	echo "The if statement evaluated to false";
}

Display:

The if statement evaluated to true

This is a lot to digest in one sitting, so let us step through the code, line by line.

  • We first made a PHP variable called $number_three and set it equal to 3.
  • In this example we compared a variable to an integer value. To do such a comparison we use “==“, which in English means “Is Equal To”.
  • $number_three is indeed Equal To 3 and so this statement will evaluate to true.
  • All code that is contained between the opening curly brace “{” that follows the if statement and the closing curly brace “}” will be executed when the if statement is true.
  • The code contained within the else segment will not used.

execute else code with false

On the other hand, if the if statement was false, then the code contained in the else segment would have been executed. Note that the code within the if andelse cannot both be executed, as the if statement cannot evaluate to both true and false at one time! Here is what would happen if we changed to $number_three to anything besides the number 3.

PHP Code:

$number_three = 421;

if ( $number_three == 3 ) {
	echo "The if statement evaluated to true";
} else {
	echo "The if statement evaluated to false";
}

Display:

The if statement evaluated to false

The variable was set to 421, which is not equal to 3 and the if statement was false. As you can see, the code segment contained within the else was used in this case.

SynapseIndia Php Development :- The If Statement

The PHP if statement is very similar to other programming languages use of the if statement, but for those who are not familiar with it, picture the following:

Think about the decisions you make before you go to sleep. If you have something to do the next day, say go to work, school, or an appointment, thenyou will set your alarm clock to wake you up. Otherwise, you will sleep in as long as you like!

This simple kind of if/then statement is very common in every day life and also appears in programming quite often. Whenever you want to make a decision given that something is true (you have something to do tomorrow) and be sure that you take the appropriate action, you are using an if/then relationship.

the php if statement

The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January 1st you want to print out “Happy New Year!” at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occuring every year on January 1st.

This idea of planning for future events is something you would never have had the opportunity of doing if you had just stuck with HTML.

if statement example

The “Happy New Year” example would be a little difficult for you to do right now, so let us instead start off with the basics of the if statement. The PHP if statement tests to see if a value is true, and if it is a segment of code will be executed. See the example below for the form of a PHP if statement.

PHP Code:

$my_name = "someguy";

if ( $my_name == "someguy" ) {
	echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";

Display:

Your name is someguy!
Welcome to my homepage!

Did you get that we were comparing the variable $my_name with “someguy” to see if they were equal? In PHP you use the double equal sign (==) to compare values. Additionally, notice that because the if statement turned out to be true, the code segment was executed, printing out “Your name is someguy!”. Let’s go a bit more in-depth into this example to iron out the details.

  • We first set the variable $my_name equal to “someguy”.
  • We next used a PHP if statement to check if the value contained in the variable $my_name was equal to “someguy”
  • The comparison between $my_name and “someguy” was done with a double equal sign “==”, not a single equals”=”! A single equals is for assigning a value to a variable, while a double equals is for checking if things are equal.
  • Translated into english the PHP statement ( $my_name == “someguy” ) is ( $my_name is equal to “someguy” ).
  • $my_name is indeed equal to “someguy” so the echo statement is executed.

a false if statement

Let us now see what happens when a PHP if statement is not true, in other words, false. Say that we changed the above example to:

PHP Code:

$my_name = "anotherguy";

if ( $my_name == "someguy" ) {
	echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";

Display:

Welcome to my homepage!

Here the variable contained the value “anotherguy”, which is not equal to “someguy”. The if statement evaluated to false, so the code segment of the if statement was not executed. When used properly, the if statement is a powerful tool to have in your programming arsenal!

SynapseIndia Php Development Require

Just like the previous lesson, the require command is used to include a file into your PHP code. However there is one huge difference between the two commands, though it might not seem that big of a deal.

require vs include

When you include a file with the include command and PHP cannot find it you will see an error message like the following:

PHP Code:

<?php
include("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in/home/websiteName/FolderName/tizagScript.php on line 2Warning: main(): Failed opening ‘noFileExistsHere.php’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in/home/websiteName/FolderName/tizagScript.php on line 2

Hello World!

Notice that our echo statement is still executed, this is because a Warning does not prevent our PHP script from running. On the other hand, if we did the same example but used the require statement we would get something like the following example.

PHP Code:

<?php
require("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in/home/websiteName/FolderName/tizagScript.php on line 2
Fatal error: main(): Failed opening required ‘noFileExistsHere.php’ (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in/home/websiteName/FolderName/tizagScript.php on line 2

The echo statement was not executed because our script execution died after the require command returned a fatal error! We recommend that you use require instead of include because your scripts should not be executing if necessary files are missing or misnamed.

SynapseIndia Pass Values Across Multiple Forms Using PHP Development

HTML forms — what would the web be without them? After you complete and submit a form, the input is usually sent to some script that processes it. The script may send the input via e-mail or insert it into a database.

Creating this type of functionality is usually a snap. First, you create an HTML form with whatever fields you want the user to fill out. Then you create a script that does something with the user input it receives from the form. The final step is to make the form’s ACTION attribute point to the script, like this:

<form action="process_form.php3">

That’s it. User input is collected via the form and processed by the script. Piece of cake, right?

But what if the user has to complete more than one form?

The tricky part is transferring the user’s input from one form to the next until it reaches the script. We must somehow store the user’s input from previous forms as fields in the current form the user is on. That way all the answers will be carried over when the user submits the form. To help accomplish this task, we’ll use hidden input fields. If you’ve played around with forms before you’re probably already familiar with them. They look like this:

<input type="hidden" value="somevalue" name="somename">

The hidden input fields will store the names and values of form elements from previous forms in the current form the user is on.

We’ll also use a little PHP, which will generate the hidden input fields for us on-the-fly.

Using the POST Method, hidden input fields, and PHP, we can easily carry user input across multiple forms. It just takes a few lines of code. Here’s the actual script:

<?php

while (list($name, $value) = each($HTTP_POST_VARS))
  {
   echo "<input type=\"hidden\" value=\"$value\" name=\"$name\">\n"; 
  }

?>

Here’s what we find when we break it down:


while (list($name, $value) = each($HTTP_POST_VARS))

The code above is a loop that accesses the elements stored in $HTTP_POST_VARS.

  {
   echo "<input type=\"hidden\" value=\"$value\" name=\"$name\">\n"; 
  }

All we’re doing here is getting the name and value of an element and using them to construct a hidden input field. This segment of code serves as a template for generating the hidden input fields.

To sum it up, the script will loop through each element stored in $HTTP_POST_VARS and generate a hidden input field for it.

Just make sure you do the following:

1. Copy and paste the script somewhere between the

<form></form>

tags in whatever form(s) you want.

2. Use POST in the form’s METHOD attribute. If you don’t specify anything, it will use GET and the script won’t work.

The following is the uncut version of the script, with comments and all. Feel free to modify the script to suit your needs.

<?php

/* ---------------------
    Declare Variable(s) 
   --------------------- */

$name; 	// Represents the name of the elements in $HTTP_POST_VARS
$value;	// Represents the value of the elements in $HTTP_POST_VARS


// ---------------------

// Do while there is an element in $HTTP_POST_VARS... 

while (list($name, $value) = each($HTTP_POST_VARS))

  /* ...get the name and value of the element and use it to construct a hidden input field.  
      Then go back to the beginning of the loop and do the same thing with the next element. */

  {
   echo "<input type=\"hidden\" value=\"$value\" name=\"$name\">\n"; 
  }

?>

Until next time, happy coding!

SynapseIndia Persistent Session (Server-Side Cookie) with PHP Development

Hello !!

If somoene wonder what is a persistent session or server-side cookie, then I will give you an introduction :

“Persistent Session is a session that is stored on your server, but the data will persist even when user disconect from your web server until the expired date comes”

This persistent session, some people called with “Server-Side Cookie” because how it works is really like cookie but it is stored in server side.

To simulate persistent session, we still need cookie (just like original Session technology does). This cookie is not to store the data itself, but to store the SESSION ID which will be different among every users.

We also need a temporary directory in server to store the Session data with read/write permission (in UNIX/Linux, you can use chmod 777 to change the permission).

Ok, first you have to define the temp directory, for example : /temp/

Then, we can make persistent session management module :


file    : mod_PSession.php
purpose : module of Persistent Session
**************************************
<?
// your temp directory :
$SESSION_DIR = "/temp/";

// The expired date.
$expired_date = 30*3;  // 30 days times 3 (3 months)

srand((double)microtime()*1000000);
$SES_VAR = array();

function generate_SID()
 {
 return md5(rand(0,32000) . $REMOTE_ADDR . rand(0,32000));
 }

function sess_start()
 {
 global $MYSID, $CKDOMAIN, $SES_VAR, $SESSION_DIR;
 if (!$MYSID) 
    $MYSID = generate_SID();

 setcookie("MYSID",$MYSID,time()+365*24*3600,"/");

 if (file_exists($SESSION_DIR.$MYSID))
    {
    $arr = file($SESSION_DIR.$MYSID);

    // if session is expired, then skip ...
    if ( time() > $arr[0] )
         {
         unlink($SESSION_DIR.$MYSID); 
         return;
         }

    // read content of session from file system ... 
    for ($i=1;$i<count($arr);$i++)
        {
        $arr2=explode(":",$arr[$i]);
        $arr2[1]=base64_decode($arr2[1]);
        $SES_VAR[$arr2[0]]=1;
        GLOBAL ${$arr2[0]};
        ${$arr2[0]} = $arr2[1];
        }
    }
 }

function sess_register($name)
 {
 global $SES_VAR;
 $SES_VAR[$name]=1;
 }

function sess_close()
 {
 global $MYSID, $CKDOMAIN, $SES_VAR, 
        $SESSION_DIR, $expired_date;

 reset($SES_VAR);
 $fp = fopen($SESSION_DIR.$MYSID,"w");
 fputs($fp,(time() + $expired_date * 24 * 3600)."\n");
 while (list($key,$val)=each($SES_VAR))
       {
       GLOBAL ${$key}; 
       $val = ${$key};
       fputs($fp,$key.":".base64_encode($val)."\n");
       }
 fclose($fp);
 }
?>

Now, let’s try how to implement the module :


file : index.php
****************
<?
include("mod_PSession.php");

// sess_start must be called on the beginning of your code !!
sess_start();

// register variables you want to store in persistent session :
sess_register("myname");
sess_register("myage");
sess_register("mygender");

// now, put the values ...
$myname   = "Alexander";
$myage    = "22";
$mygender = "Male of course !!";

print "
<HTML>
<BODY>
Session is saved ! 
<A HREF='next.php'>Go to next page</A>
</BODY>
</HTML>
";

// sess_close must be called after all is done
sess_close();
?>

In sequence :
1. You must include file mod_PSession.php.
2. You must call sess_start() to start the session support.
3. You must call sess_register() to register any variables that you want the session to remember.
4. You must call sess_close() if you want to save the session to file system. Usually, this is called in the last part of your code.

To see if the persistent session works, create the “next page” :


file : next.php
***************
<?
include("mod_PSession.php");
// must be started !!
sess_start();

print "<HTML><BODY>";
print "Hello !! My name is $myname, 
\n";
print "I am $myage years old, and I am $mygender 
\n";

print "<A HREF='next.php'>Go to last page</A>"
print "</BODY></HTML>";

// I increase my age ... :P
// Each time you refresh the page, my age will be added
$myage++;
sess_close();
?>