clarification:PHP files

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
swetha
Forum Commoner
Posts: 88
Joined: Wed Sep 10, 2008 11:00 pm

clarification:PHP files

Post by swetha »

Code: Select all

 
$handle = fopen("http://www.google.com", "r");
if ($handle) 
{
 
}
 
in the above statement,what does if($handle) mean? can u expand it for me?does it mean
if ($handle==true)?
if fopen is not successful,$handle returns null value.


thanks
swetha
Last edited by swetha on Fri Oct 17, 2008 4:53 am, edited 1 time in total.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Re: clarification:PHP files

Post by aceconcepts »

Yes, it basically means if file is able to open then hooray, lets read it.

Whenever you use a function such as fopen(), a value is returned (TRUE, FALSE or any other value depending what function you use).

Take a look at it in more detail here http://uk3.php.net/fopen
swetha
Forum Commoner
Posts: 88
Joined: Wed Sep 10, 2008 11:00 pm

Re: clarification:PHP files

Post by swetha »

Code: Select all

 
$str="http://www.google.com"; 
$handle = fopen($str, "r");
if ($handle) 
{
 
}
 
in the above line fopen($str, "r"),how do i check if an invalid website is entered.
fopen should not be executed if an invalid site is opened.
eg for invalid $str variables.
$str="http://wwww.google.com";
$str="http:";
$str="http://www.sgdjkag.com";
etc.

thanks for any help
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Re: clarification:PHP files

Post by aceconcepts »

Validate the value of $str before you use it in fopen().

Something like:

Code: Select all

 
$str= "http://www.google.com";
 
if (preg_match("/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i", $str)) {
echo "URL is valid";
} else {
echo "URL is invalid";
}
 
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: clarification:PHP files

Post by Eran »

Actually, the $handle variable in your code is a file pointer reference if the file was successfully opened, not a boolean TRUE.
The check is the kind of lazy PHP programming to validate such things, since most values are cast to a boolean TRUE except 0 and FALSE.
A more correct way to check it would be:

Code: Select all

 
if($handle !== false) {
 
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Re: clarification:PHP files

Post by aceconcepts »

Good correction - I was being lazy and didn't even check :wink:
Post Reply