0
<?php
$rn = $_GET['rn'];

$file_exts = array("jpg", "jpeg", "png");
$upload_exts = end(explode(".", $rn));

#$images/$rn

if (in_array($upload_exts, $file_exts)) {

  #if (in_array(file_exists($haystack), $needle) {
  if (array_search($upload_exts, $file_exts/*file_exists("c:/xampp\htdocs\php/images/" .*/)) {
     $str_img = str_replace(' ', '_', $rn);
  } else {
     $str_img = 'thumb.png';
  }
}

echo $str_img;
?>

Okay so I have this code, but I can't get the result I'm looking for.
I want to see if a file exist, using array_* and other functions like file_exists.
What my problem is, when I want to add a new file type, I will just type it in the array field, and it will search for it, if an image/file was found, the file name + file type will be printed out e.g google-img.jpg, else it whould print thumb.png.

1 Answer 1

1

Use file_exists with dirname(__ FILE __):

$rn = $_GET['rn'];
$file_exts = array("jpg", "jpeg", "png");
$upload_exts = end(explode(".", $rn));

function exists( $file ) {
$file_exts = array("jpg", "jpeg", "png");
$upload_exts = end(explode(".", $file));
 if( in_array($upload_exts, $file_exts) && file_exists( dirname(__FILE__) . '/' . $file ) )
  return $file;
 foreach($file_exts as $a)
 if( file_exists( dirname(__FILE__) . '/' . $file . '.' . $a) )
  return $file.'.'.$a;
 return false;
 }
 if( exists($_GET['rn']) )
   $str_img = str_replace(" ", "_", exists($_GET['rn']));
 else
   $str_img = 'thumb.png';
echo $str_img;
Sign up to request clarification or add additional context in comments.

15 Comments

Not quite what I meant... If the file exist, the thumb.png will not be printed as it does now. I have an image named 01.jpg, and when I type in 01 in the url, it prints out "Extension is invalid". But what I mean was, if the image does not exist, then the thumb.png will be printed
file_Exists just will work if you add the extension, else you have to try with multiple the 3 extensions. I've edited the comment. Does it work now?
your function exists returns true or false or filename ??? $str_img = str_replace(" ", "_", exists($_GET['rn'])); can result in $str_img = str_replace(" ", "_", true); there is no function str_replace with argument true !
re-edited, now it returns the filename. It will return the filename if file exists, and will return false if not.
why should the code do that? Then there is an open end. Search for image01.jpg.jpg.jpg etc. What you want to achieve, you want to see whether image01.png or image01.jpeg exists that makes sense. That's why you go through all the file extensions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.