khan
khan

Reputation: 373

php file exists or not

I have the following code, what is the easiest way to check if $data has something in it?

$handle = fopen($_FILES['uploaded_file']['tmp_name'], "rb");

$data = fread($handle, filesize($_FILES['uploaded_file']['size']));

when I do

file_exists($_FILES['uploaded_file']['tmp_name']

it prints out 1? does 1 mean exists?

Upvotes: 4

Views: 1177

Answers (5)

The Mask
The Mask

Reputation: 17427

in some languages 1 and 0 represent boolean values

1 as true 0 as false

if(1) {
 //do something
} 

equal to

if(true) {
 //do something
}

Upvotes: 0

Mingle
Mingle

Reputation: 836

if(file_exists($_FILES['uploaded_file']['tmp_name'])) {
    // file does exist... 
    // we can move it now.. or do some more "checking" on it.
} else {
    // file doesn't exist...
}

This here (file_exists()) will return a boolean value on whether or not the file DOES exist.

If it's true, and you output this.. it will be equal to one. If it's false, it's "nothing" or 0.

Here is how booleans work... just for reference..

These are considered false

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered true

Upvotes: 0

Paul
Paul

Reputation: 141839

"file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance."

https://www.php.net/manual/en/function.file-get-contents.php

if(file_exists($_FILES['uploaded_file']['tmp_name']))
   $data = file_get_contents($_FILES['uploaded_file']['tmp_name']);

Upvotes: 0

zerkms
zerkms

Reputation: 254906

It means that file_exists() function returned true which has been casted to 1. And yes - that means that file exists.

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270607

file_exists() will return a boolean value, where 1 == TRUE and 0 == FALSE.

Typically you would use something like:

if (file_exists($_FILES['uploaded_file']['tmp_name'])) {
  // success
}
else {
  // failure
}

Easier than fopen(), fread() is file_get_contents():

if (file_exists($_FILES['uploaded_file']['tmp_name'])) {
  $data = file_get_contents($_FILES['uploaded_file']['tmp_name']);
  echo $data;
}

Upvotes: 2

Related Questions