...

View Full Version : PHP - Frequently Asked Questions



missing-score
04-01-2004, 06:54 PM
Ok, Im starting this FAQ thread for the PHP forum. This will work pretty much the same as all the other FAQ threads.

We seriously need some new tutorials added, if you have the time, please go here: <36142> and consider submitting a tutorial!

Please do not reply to this thread asking for help, if you are still having problems, start a new topic in the relevant forum describing your problem

General Rules

Please feel welcome to contribute to this thread, but please dont post unless you are adding a good answer to a frequently asked question.
If you do contribute, each post should contain one question and answer, no more, no less.
Please put keywords or function names that are not within PHP code blocks in blue text.
PHP code should be placed in PHP code blocks.
When you write a reply, please include links to php.net with the relevant resources.


For further information on how to add a reply, or if you would rather have your answer proof-read before you post it here (reccomended), then please visit <36142>

FAQ Index

My code isn't working, and I get no errors!
Why PHP/JavaScript?
GPC Stripping Tutorial - Magic Quotes
Outputting Data/Common Mistypes
What is the difference between using $HTTP_POST_VARS and $_POST for accessing POST variables?
How do I write to a file using PHP?
How do I read a file using PHP?
Permission denied ... why ? File permissions
How do I resolve the 'headers already sent' error?
How do I make a random password function ?
What is the difference between addslashes() and mysql_real_escape_string() when running MySQL queries?
Sending HTML email with PHP
TIP: Coding styles and $end errors
TIP: Quotes / Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in..
The IE if (isset($_POST['submit'])) bug explained.


As FAQ entries get added I will add them to the index here.

Resources

php.net (http://www.php.net) - The official PHP site, where you can download the latest versions of PHP or lookup functions and syntax.
mysql.com (http://www.mysql.com) - MySQL is the database technology that is most often used with PHP, to make dynamic data driven websites and scripts

missing-score
04-02-2004, 09:56 PM
Q. How do I write to a file using PHP?


A. This question is often asked in many ways, it could be how to add something to the end of a file, empty a file, or create a file. All of these operations come under writing to a file.

Firstly, there is a basic pattern to writing to a file, it goes something like this:


Open the file using fopen
Lock the file using flock
Write to the file using fputs or fwrite
Unlock the file using flock
Close the file using fclose


This is the order that the operations (usually) need to be carried out in. The following example shows you how to create a file, then write a string to the file.

Jargon
Handle - The name often given to the variable defined when using the fopen function.
Mode - A letter that represents how the file should be opened when using fopen.




<?php

$fp = fopen('filename.txt', 'w'); // set the handle to the variable $fp
// and open the file in "w" mode.

$string = 'Test String'; // set the $string variable

flock($fp, LOCK_EX); // lock the file "exclusivley" for writing

fputs($fp, $string); // write the data to the file

flock($fp, LOCK_UN); // unlock the file

fclose($fp); // always call fclose to close the file.
// forgetting to close or lock files is the main cause of
// files getting corrupted.

?>


1. Now, to go over the example, the first line, where the fopen function is used, opens the file in writeable mode... If the file does not exist it will attempt to create it. The important thing to remember about using the "w" mode in fopen is that any data in the file will be truncated (emptied). There are other file handling modes, which can be looked up on the php website: <http://www.php.net/fopen>. Some of these other modes will also be covered later in this post.

On the next line, we just simply set the variable $string to the value 'Test String'. This is the data that will get written into the file later on.

2. Next we lock the file using flock. Using an exclusive lock, which is set by putting LOCK_EX, the file is locked from other scripts writing to the file or reading from it while we put the new information into the file. If the file isn't locked and two scripts try to write to it at the same time, it can get corrupted.

3. The next part is the part that actually writes the information to the file. Using the fputs function it use the file path and data supplied ($fp and $string in this case), and writes $string to $fp.

4. From here, the file needs to be unlocked using flock again, otherwise no other scripts would be able to write or read it. To unlock the file, we use LOCK_UN.

5. Finally, we have finished with the file so we can close it. Using the fclose function we pass it the file handle ($fp) and it closes it. You should always do this as this is another thing that can lead to files getting corrupted.


Problems?
If you try this and are still having problems, there are some possible reasons that it is failing, the most likley is that the file or directory you are trying to write to doesn't have the right permissions set. If you are on Linix machines (mosts PHP hosts will be running Linux), then you can CHMOD the file or directory to a value that will allow the scripts to be executed. For testing, I usually set it to 777. You can CHMOD from some FTP programs and online control panels. If you are not sure how to CHMOD on your hosting acount, you should contact your webspace provider.


This is the basics of writing to a file. Often, however, when you write to a file, you want to be able to add something on to the end of the file, and not delete everything that is in there first. This is very easy to alter, simply change the code:




fopen('filename.txt', 'w');

// to

fopen('filename.txt', 'a');


This changes the file from opening to write mode (w) to ammend mode (a). When you write to the file now, anything you write to the file gets added onto the end after any existing data.

Finally, to bring this to a close, just a couple more points...


This only handles with writing to files, you can also read from filed but that is not discussed here
There are many more modes for file handling, look at <http://www.php.net/fopen>
There are also other types of file lock, and you can find these at <http://www.php.net/flock>



How to write to the beginning of a file?
A common question is ,'how do you write to the beginning of a file' , the answer is not a new magic mode but a different approach , it should be noted that you can write to the beginning of a file by opening 'r+' and using fseek() to rewind to the start of a file then fputs() etc , however this will overwrite byte for byte the files existing contents.

To add a line to the beginning of a text file the most straightforward method is to read the file into memory , manipulate and then rewrite the file.
Newer PHP versions have handy functions such as file_get_contents (http://www.php.net/file_get_contents)() to get the files data into a variable , you can also use the above noted functions to read a file into memory or the old sausage <?$str = implode( '', file( $filename ) ) ;?>

e.g. (no filelocking for clarity)


read the file contents into a variable
<?php
$filename = 'cars.txt' ;
$str = implode( '' , file( $filename ) ) ;
?>
append your data
<?php
$str = "porche 911sc\n" . $str ;
?>
open (overwrite) your existing file
<?
$fp = fopen( $filename ,'w' ) ;
fputs( $fp , $str ) ;
fclose( $fp ) ;
?>


Note that the above method becomes resource intensive with larger files.

Resources
http://www.php.net/fopen
http://www.php.net/flock
http://www.php.net/fputs
http://www.php.net/fwrite
http://www.php.net/fclose

firepages
01-17-2005, 11:08 AM
<help>I would really appreciate those of you who understand all of this to please check the below is in order since it is a sticky , I am not a unix user , not a trained administrator so any pointers errata are welcomed !!!</help>

OK so many questions regarding this subject so...here we go.

Files on any *NIX system have a, at first glance ,complex ownership/permission system , its actually not that complex but can be intimidating at first.
Now you may think you don't need to understand them (and for most web-related work you probably don't ), however knowledge is power & once you do understand them , you will never again worry about the dreaded `permission denied` , dont skip though , read from the beginning , it makes more sense if you do.

The 3 common (there are more) *NIX permissions 'r' , 'w' , 'x' ( often 'e' or 'o' ) are applicable to 3 entities , the files 'owner' the files 'group' and 'others' (AKA 'everyone else' 'the world' )

Ownage
All files have an owner , who that owner is depends on who created them , when you upload a file via FTP the file is owned by the user that you logged in as.
So if your FTP login is 'joe' then the file is most likely owned by user 'joe'.

When however you create a file via script (fopen() etc) the file is still owned by whoever created it , however that user is no longer 'joe' , its the user that your webserver runs as , which is normally NOT your *UNIX username (except in chrooted or suexec environments) , it is normally 'apache' or 'nobody' .

Groups[b/]
Groups are a bit of a sticky subject because how groups are assigned varies from system to system , often at the whim of the server administrator or hosting control panel interface , plesk for example assigns all file uploaded via FTP to the 'psacln' group , redhat however by default creates a new group for each user and assigns group ownership to that group (e.g. user 'joe' gets his own group 'joe').

[b]Others AKA everyone else , the world
As far as *NIX is concerned , if someone is not the owner of the file or does not belong to the same group as a file , then you are classed as 'others' , contrary to popular belief external applications can not modify files which allow write access to 'others' , only other users of the same system or local network can actually do that (on shared hosting this is a real issue)

Permissions
All *NIX files have permissions assigned , there are 3 permissions a file can be given , 'r' for read , 'w' for write & 'x' for executable , a file can have 0 or more permissions . e.g. a file can have both 'r' and 'w' permissions , so they are both readable and writable , 'rwx' means you can do pretty much anything with the file.

Now the permissions above r,w & x are applied individually to the files owner , the files group and others ! so

owner group others user group
myfile rwx r r joe joe

With the above, the owner of the file (joe) can read write & execute (if applicable , e.g. the file is a script) the file , any members of the 'joe' group (usually just the user joe) can read and write to the file , 'others' can only read the file. when your webserver requests myfile , it does so as 'apache' or nobody' and as such is given read access.

However , when your script which is probably running as 'apache' comes along and tries to write to the file , it finds it can not .. why? , well 'apache' is not the owner of the file , nor does it belong to the group 'joe' , therefore as far as this file is concerned it belongs to the 'world' group which is only allowed to read, not write to the file.

to allow apache to write to the file you would need to change the file permissions to ...

owner group others user group
myfile rwx rw rw joe joe

e.g. give 'others' write 'w' access , so an outsider , such as apache , could write to the file.

vice-versa
Now lets say you created a file via a PHP script , the file created by PHP (actually by apache with mod_php) will be owned by 'apache' , if you then chmod the file (again via script) to say 0700 (rwx------) then you would not have permission to delete that file via FTP , since you would then be considered as 'others' !
Luckily if you created a file by script you can chmod it to something more accessible via script <?php chmod( 'myfile' , 0766 );?> , this will then allow you to read and write to the file via FTP.

so with the following
owner group others user group
myfile rwx r r joe joe

You can not chmod the script via PHP/apache since it only has read access , however if via FTP you (as 'joe') chmod to 0766 or 0777 , then your PHP script can read and write to the file.

Directories
Its often assumed that if a directory is not writable then nor are is contents , that however is <B>not</B> the case , a writable file in a read-only directory can still be altered by anyone with the right credentials , however you will not be able to write to that directory unless the directory is writable to the user or application that attempts the write.
Also to be able to list the directories contents , the directory must be executable to the application attempting to do so , 'read' is not enough (in fact you don't even need the directory to be readable , 'x' is enough.

scripts
Need to be executable , HTML & text files etc can simply be read-only , but if a file is a script , then make it executable !

.................................................................................................... .............................

modes
file permissions can be represented as octal modes , but that's easier than it sounds , if ...
r (read) = 4
w (write) = 2
x (execute) = 1

if the owner of a file has read & write permissions that's 4+2 = 6
if the group just has read permission that's 4
if others also only have read permissions , again that's 4

so myfile below has the mode 0644
owner group others user group
myfile rw r r joe joe

.................................................................................................... .............................

chmod
As noted above chmod() can change the permissions of a given file , for a user or an application to change these permissions however the user or application needs to have write access to the file in the first place !!

for PHP its important when chmod()'ding to use octal values
chmod( 'myfile' , '0644' ) ; will cause issues , since we are passing the mode as a string
chmod( 'myfile' , 644 ) ; here 644 , is , as far as PHP is concerned, decimal ! again be prepared for problems
chmod( 'myfile' , 0644 ) ; is correct !

.................................................................................................... .............................

chown & ghgrp
PHP has the chown & chgrp commands, however only a superuser can use them , so unless your webserver runs as 'root' or similar , you can't use them.

.................................................................................................... .............................

CGI disclaimer
If your server runs PHP as a CGI then much of the above may change , its is not common for CGI scripts to be run as a different user than the webserver via Apaches mod_suexec or phpsuexec etc

.................................................................................................... .............................

chrooted environments
If you webserver runs in a chrooted environment then its possible (probable) that the webserver (above stated as 'apache' or 'nobody') may well run as another user , often as the user account e.g the same as your FTP login , if this is the case then you will have less issues with file ownership & generally be in a much safer playground.

umask
Not really important here , but you may wonder why when you create a file via FTP or script that it is given e.g. 0755 for FTP or 0644 for scripts , this is decided by the umask , the responsibility of the server administrator

.................................................................................................... .............................
.................................................................................................... .............................

So , if you read the above , and if it made any sense at all :D , you will understand why you can't ,immediately alter your files uploaded by FTP via a PHP script, if you don't then read again , if I am making no sense then please post and say so & I will try and clarify , if anyone wants to add to this document , post & I will add/amend

tomahack
03-05-2005, 10:44 AM
Q: How can i do a random password function ?

There it is,
First of all, you need a character bank as well abcdefghijklm...etc..,
It looks that you want a password generated by the server, so you need to specify all your chars and yes, Upper cases too..


STEP 1 , Create a file called functions.php and add this content..

// File functions.php
<?
function randompassword() { // Declaring the function
//Config Start
$salt = "abchefghjkmnpqrstuvwxyz0123456789"; // Your characters bank
$n = "8"; // Number of character to return
//end config
$v = strlen($salt);
srand((double)microtime()*1000000);
$i = 1;
while ($i <= $n) {
$num = rand() % $v;
$tmp = substr($salt, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}


Please note, that functions with those structures doesnt called by itself, so you must call it to get results..Let's do it..

STEP 2, in any files who needs a random password, add this to require the file who contain functions at page load, and declare the variable to get the password..


// File index.php
<? require("functions.php"); ?>
<html>
<head>
Some meta-head infos
Some javascript scripts..etc..
</head>
<body>
Some contents
<?
$password = randompassword(); // $password gonna call the function randompassword and return it into the variable..
echo "There's my password: ".$password." ";
?>
Some contents


</body>
</html>






Functions used in this scripts are:

substr (http://www.php.net/substr) Return parts of a $string
$i++ (http://ca.php.net/manual/en/language.operators.increment.php) Increment / Decrement variables
srand (http://www.php.net/srand) Seed the random number generator < PHP 4.2
microtime (http://www.php.net/microtime) Return current Unix timestamp with microseconds
rand (http://www.php.net/rand) Generate a random integer
strlen (http://www.php.net/strlen) Return lenght of a string

thewickedjester
03-18-2005, 10:00 PM
Very begginner question:

Why PHP/JavaScript?

PHP is server side, while JavaScript is client side, meaning that JavaScript can make popups and other things happen on someones PC, while PHP is server-side, so it does stuff with the server.

marek_mar
04-23-2005, 01:57 PM
Q: How to resolve the 'headers already sent' error?
A: This is one of the most common errors. You often get it when your using session_start() (http://www.php.net/session_start) or header() (http://www.php.net/header).
Headers are sent automatically when any output is sent to the user. You send output with print (http://www.php.net/print)/echo (http://www.php.net/echo) (and some other functions) as well as having anything outside php tags. This includes blank lines spaces, tabs and all other characters. You must send the header BEFORE the output. You must watch out not to have any blank lines before the <?php tag and after the ?> tag


<?php // There should be no spaces before tag.
session_start();
?>
// A new line which shouldn't be here. This is important especially the file is included to another file.
Coding in such a way might be difficult, so you might ask if there is a way to wait with sending the output until the end of script execution. This is where output buffering (ob for short) comes in to play. If you start ob it will save all output and headers into memory instead of sending it. You can send all output at once with the headers.


<?php
ob_start(); // Send the output.
?>
<html>
<head>
<title>OB test</title>
</head>
<body>
<?php
session_start();
print SID;
?>
</body>
</html>
<?php
header('Content-type: text/plain'); // An example header.
ob_end_flush(); // Send the output.
?>

You can try commenting out the ob_start();

Functions used:
ob_start() (http://www.php.net/ob_start)
ob_end_flush() (http://www.php.net/ob_end_flush)
-mentioned but not OB functions
session_start() (http://www.php.net/session_start)
header() (http://www.php.net/header)
Good to read:
output buffering (http://www.php.net/outcontrol)

If you spot an error (or have a suggestion) PM me. I'll fix it as fast as I can.

PoweredPC
06-28-2005, 09:51 PM
Very begginner question:

Why PHP/JavaScript?

PHP is server side, while JavaScript is client side, meaning that JavaScript can make popups and other things happen on someones PC, while PHP is server-side, so it does stuff with the server.
PHP and JavaScript can be used together also (you can put <?php echo whatnot ?> in <SCRIPT> tags, just as you can put <script>some js here</script> in <?php ?> tags (with the echo before each js command, of course)
PHP is used to load a page and can be put into certain js variables etc (for instance taking items from a database and putting them into js variables, you would use php in script tags OR if you want to make a certain part of your page scale to the length of your database but have JS inside of it, you would use php to make the length of whatever it is (say <TD>s) and put JavaScript inside each TD.
Just because JS and PHP are client-side and server-side respectively does not mean they cannot be used together. JS makes pages dynamic (on the client side) while PHP makes pages dynamic (on the server side, when the page actually loads (the user does not see how the php affects the page)).

Velox Letum
12-21-2005, 01:59 AM
Q: What is the difference between addslashes() and mysql_real_escape_string() when running MySQL queries?

A: The difference between addslashes() and mysql_real_escape_string() is that mysql_real_escape_string() escapes all characters harmful to a mysql query (such as line feeds, carriage returns, quotes, and a number of other assorted special characters), while addslashes() only escapes quotes (both single and double), backslashes, and the NULL byte.

Related to this topic is magic quotes. If magic_quotes_gpc is enabled in the PHP config, it automatically runs the equivalent of addslashes() on $_POST, $_GET, and $_COOKIE data (and by proxy, $_REQUEST data). If magic_quotes_runtime is enabled, it runs it on almost all external data (file reads, database results, and so on). Thus, we would want to remove this from our data before entering, as when used with mysql_real_escape_string() it would double-escape values, and would cause errors.

Snippit:


$username = $_POST['username']; // Value is ' OR ''=', which would be executed as part of the query without escaping.

if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) { // Check if either magic_quotes_gpc or magic_quotes_runtime are enabled.
$username = stripslashes($username); // Strip the slashes added by magic quotes.
}

$username = mysql_real_escape_string($username); // String is now safe to use in a query.


One more warning is to not use mysql_real_escape_string() on integers. You can, but all it will do is convert them to strings, and there are ways to do so with far less overhead. You may want to write a function which acts as a wrapper for mysql_real_escape_string() and checks if it is an integer first.

Resources:

addslashes() (http://www.php.net/function.addslashes)
stripslashes() (http://www.php.net/function.stripslashes)
mysql_real_escape_string() (http://www.php.net/function.mysql-real-escape-string)
get_magic_quotes_gpc() (http://www.php.net/function.get-magic-quotes-gpc)
get_magic_quotes_runtime() (http://www.php.net/function.get-magic-quotes-runtime)
Magic Quotes (http://www.php.net/security.magicquotes)

Velox Letum
12-21-2005, 02:11 AM
Q: What is the difference between using $HTTP_POST_VARS and $_POST for accessing POST variables?

A: The difference between $HTTP_POST_VARS and $_POST is that one is depricated, and one is not. $HTTP_POST_VARS (and others such as GET, SERVER, ENV, COOKIE, etc.) were all renamed in PHP 4.1.0 to variables such as $_POST, $_GET, $_SERVER, $_ENV, $_COOKIE, and so on. In later versions of PHP (possibly PHP6) they will be eventually removed.

It is noteworthy to say that the $HTTP_POST_VARS array and the $_POST superglobal array are not references...that is to say, they are separate variables. Changing the value of $_POST['foo'] will not modify the value of $HTTP_POST_VARS['foo'].

References:

Predefined Variables (http://www.php.net/manual/en/language.variables.predefined.php)

jeyalakshmi
08-17-2006, 11:46 AM
How do I read a file using PHP?
The following are basic steps followed in reading a file using PHP
Open a file using fopen
lock the file using flock
read the contents of the file using fread
unlock the file using flock
close the file using fclose


<?php
$filename = "../example/file.txt"; //name of file
$handle = fopen($filename, "r"); //open the file using fopen
flock($handle,LOCK_SH);//lock the file using shared lock for reading
$contents = fread($handle, filesize($filename));//read the file using fread
echo $contents; //display the contents of file
flock($handle,LOCK_UN);
fclose($handle);//close the file using fclose
?>


1. The first line of the code specifies name of the file.
2. Then open the file using fopen in "r" read mode. If the file doesn't exists, it will show you an error.
3.Lock the file using flock.using an shared lock,which is set by putting LOCK_SH.When a statement reads data without making any modifications, its transaction obtains a shared lock on the data.
4.Read the data from the file using fread. Read the file until end of the file will be reached.
5.unlock the file using flockby putting LOCK_UN
6.close the file using fclose

apachehtaccess
01-05-2007, 10:21 PM
I read a really good article (http://www.askapache.com/2006/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html) about the PHP emailing program PHPmailer and decided to check it out.

Heres how I use it to send HTML emails on my sites:



<?php
require("class.phpmailer.php");
require("class.smtp.php");

class MyMailer extends PHPMailer {
public $From = "form-results@google";
public $FromName = "Google.com";
public $Host = "mail.google";
public $Hostname = "google";
public $Mailer = "smtp";
public $Sender = "form-results@google";
public $SMTPAuth = true;
public $Username = "form-results@google";
public $Password = "youwish";
}


$emailresults = '<html><head><title></title></head><body>
<div style="position:relative; margin:40px 0; padding:1px;">'.$myformss.$debugger.$mess.'</div></body></html>';

session_start();

if(!isset($_SESSION['mailsent'])) $_SESSION['mailsent']=0;
else $_SESSION['mailsent']++;


if ($_SESSION["mailsent"] < 10) {
$_SESSION["mailsent"]++;
$mail = new MyMailer();
$mail->IsHTML(true);
$mail->AddAddress("post-to-blog@google");
$mail->AddBCC("webmaster@google");
$mail->Subject = $mysubject;
$mail->Body = $emailresults;
$mail->AltBody = "You are viewing this message because your email client is not configured for html emails.$mess";
$mail->SetLanguage('en');
if(!$mail->Send())
{
$mail->ClearAllRecipients();
echo "Message was not sent<br>";
echo "Mailer Error: " . $mail->ErrorInfo;
} else $mail->ClearAllRecipients();

} else die('MAILSENT OVER LIMIT!');

?>

schferdi
10-03-2007, 11:21 PM
Outputting Data

echo "Hello<br/>$name"; // Works!
echo "Hello\n$name"; // Works!
echo 'Hello\n$name'; // outputs "Hello\n$name"

Why is this?
functions used with single quotes is used as direct/literal input, and text within single quotes does not get parsed.

Common Mistypes

if ($variable = $condition) // will always return as true
if ($variable == $condition) // correct usage


if ($variable !== $condition) // enforces type comparison: http://php.net/language.operators.comparison
if ($variable != $condition) // correct usage


fputs($fp, 'This is text\n'); // does not make a new line
fputs($fp, "This is text\n"); // this does make a new line

Note from Inigoesdr: While you can use any of these and/or examples, you probably want the one marked "correct". See this (http://php.net/language.operators.logical) manual page for more info; specifically precedence.

if ($variable == $condition AND $other != $condition) // incorrect usage
if ($variable == $condition && $other != $condition) // correct usage

if ($variable == $condition OR $other != $condition) // incorrect usage
if ($variable == $condition || $other != $condition) // correct usage



// Incorrect
if ($variable == $condition)
execute();
exit;
else do_not_execute();
// Correct
if ($variable == $condition) {
execute();
exit;
}
else do_not_execute();
More info on control structure syntax is available here (http://php.net/control-structures.if).

There's also the alternative syntax (http://php.net/control-structures.alternative-syntax) for control structures available to you.

Inigoesdr
10-04-2007, 03:59 AM
My code isn't working, and I get no errors!

First and foremost: Turn on error reporting at the very beginning of your script.

<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting (E_ALL);
?>
If you have MySQL queries that aren't working add some error logic to find out why. See the manual (http://php.net/mysql_query) for some examples.

Also, be sure output buffering is off: ob_end_flush() (http://php.net/ob_end_flush)

And if you can't figure it out after that, post a new thread in this forum with as much relevant information as possible, and any code that we might need so we can help you as quickly as possible.

Fou-Lu
12-25-2008, 11:11 PM
How do I determine alternating rows?
Common question when using loops and css divs or tables. There are two ways to determine whether you're current iteration is odd or even. One way is through modulus (remainder) division, and the other way is through bitwise comparison. Bitwise comparison is faster than modulus since only the least significant bit needs to be checked. This equates to approximately 2 - 3 times faster than modulus division.



$aItems = array('Cat', 'Dog', 'Mouse', 'Rabbit');
$cItems = sizeof($aItems);
for ($i = 0; $i < $cItems; ++$i)
{
printf("<div>%s</div>\n", $aItems[$i]);
}

In the above example, $i represents even if one of the following is true:


$bIsEven = ($i % 2 == 0); // Most common way
$bIsEven = !($i & 1); // Faster though less used.

Conversely, $i is odd if the above are false:


$bIsOdd = ($i % 2 != 0);
$bIsOdd = ($i & 1);


Using this with the previous loop, the alternating rows would correspond with the classes 'evenRow' and 'oddRow':


$aItems = array('Cat', 'Dog', 'Mouse', 'Rabbit');
$cItems = sizeof($aItems);
for ($i = 0; $i < $cItems; ++$i)
{
$sClass = 'evenRow';
if ($i & 1)
{
$sClass = 'oddRow';
}

printf("<div class=\"%s\">%s</div>\n", $sClass, $aItems[$i]);
}

Results in:


<div class="evenRow">Cat</div>
<div class="oddRow">Dog</div>
<div class="evenRow">Mouse</div>
<div class="oddRow">Rabbit</div>

JAY6390
01-14-2010, 01:02 PM
go here
http://www.phpvideotutorials.com/free and check out the free lessons (the first teaches you how to install WAMP)

jaymista
03-17-2010, 05:47 AM
Does it cost anything to install the above program, WAMP?

abduraooft
03-17-2010, 08:18 AM
Does it cost anything to install the above program, WAMP?
http://www.google.co.in/search?q=wamp

hinch
10-20-2011, 02:02 PM
some basic qusetion in php:
1.What is staic and dynamic webpage?
2.what is css?
3.How do you connect database with php code?
4.What is session ?


1) static is a page made up purely of html and/or css it does not automatically update its self or allow any form of interaction with a data storage or retrieval system eg: a database
Dynamic is basically everything you see on the internet :)
2) css = cascading style sheets used for defining a layout and design etc of your website you can read more here http://www.w3schools.com/css/
3) like this



define("DB_NAME","mydatabase");
define("SERVER_NAME","serveraddress");
define("USER_NAME","myusername");
define("PASSWORD","mypassword");
$conn = mysql_connect(SERVER_NAME, USER_NAME, PASSWORD) or die("Could not connect: " . mysql_error());
mysql_select_db(DB_NAME, $conn);

4) a session is something you create in in your web page that can store data for you to use. so if you want to store something and use it later you can store it in a session. most commonly used in login systems where people will store a "logged in" variable to identify users who are logged in or not.

liveperson
08-21-2013, 09:54 AM
How to use LDAP to authenticate user.


function ldap_auth($server, $domain, $username, $password) {
if (strlen($username) == 0 || strlen($password) == 0) {
return false;
}

$ds = ldap_connect($server)
or die('Connection to the LDAP server failed.');

if (!$ds) {
return false;
}
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);


$r = @ldap_bind($ds, "$domain\\$username", $password);

if (!$r) {
return false;
}
$dn = "dc=ad,dc=domain,dc=com";
$filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=$username))";
$search_results = ldap_search($ds, $dn, $filter) or die ("ldap search failed");
$entries = ldap_get_entries($ds, $search_results);

if( $entries["count"] > 0)
{

}
else {
error_log("No such user $username found", 0);

}
ldap_close($ds);

return true;


}

tintin77
07-01-2014, 11:33 AM
Hi Im new to php. Can anyone help me for php random script that i can define priority. Example I have number 1 to 10 in array. I want to select 1 to 4 in first 4 picks. Then only it should pick 5-10.

How can i do this. I hope this is clear. If not please ask.

Thanks

sayam
09-19-2014, 09:23 PM
There are many to learn code of php,like w3scool,ytube e.t.c

jan127
12-04-2014, 11:07 AM
Create Image Thumbnails Using PHP and gd


function make_thumb($src, $dest, $desired_width) {

/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);

/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));

/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);

/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest);
}

collenwesling
12-15-2014, 06:13 AM
I was reading the whole thread and I got some informations that I needed. Thankss

imobdevtech
01-06-2015, 06:13 AM
go here
http://www.phpvideotutorials.com/free and check out the free lessons (the first teaches you how to install WAMP)

I totally appreciate with you that anyone can get almost all topics regarding PHP. One more source for video learning is Linda.com.

Mehak50
02-22-2015, 11:22 AM
very nice. I have read about Cookies and Sessions here. Cookie and Session (http://forum-discussion.com/Thread-What-is-the-Difference-Between-Cookie-and-Session)

WardBradley
08-20-2015, 09:24 AM
thanks. it's really useful theme.
I'd like to ask you some questions

1. What is the benefits of using PHP Framework?

2. Which PHP Framework I'd better use?

I've found one interesting article related to this topic - How to Choose a PHP Application Framework - WebiNerds (http://webinerds.com/choose-php-application-framework/) (PHP Frameworks comparison) but can't choose between Laravel and Zend.

3. How to install OpenSSL PHP Extension?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum