0

I have an input like this:

<input name='postImg' type='text'><?php if(isset($error)){ echo $_POST['postImg'];}?></input>

I would like PHP to check if the input text contains: .png or .jpeg or .gif etc. To make sure its a image. But it has to be input name (so no upload).

How can I do this best?

1
  • 1
    note that matching filenames isn't a reliable way of checking "is this an image"? ren nastyvirus.exe cutekittens.jpg, for one... Commented Oct 20, 2014 at 15:56

2 Answers 2

2

You could use a regular expression. This will check that the extension is correct; matching (.png, .jpeg, .jpg, .gif) the end of the string

if( preg_match("/\.(png|jpeg|jpg|gif)$/", $_POST['postImg']) ) {
   //Yep.
}

Example: https://eval.in/208018

Edit

if( strlen($postImg) > 0 AND preg_match("/\.(png|jpeg|jpg|gif)$/", $postImg) == FALSE) {
   $error[] = 'Wrong image format.';
}
Sign up to request clarification or add additional context in comments.

6 Comments

For some reason it isnt working. My other statements aren't working anymore. Here is the full code: pastebin.com/hF6p9fVA
Try something like: pastebin.com/SiEeGU3U (You are also trying to insert into the database even if there were errors. I've switched the logic on that for you, too)
Ok, that's working. Thanks. But could you add something that it is also possible to leave postImg empty?
Sure, add an OR clause within the if logic. if( empty($_POST['postImg']) OR ...
if( empty($postImg) OR preg_match("/\.(png|jpeg|jpg|gif)$/", $postImg) == FALSE) {} If the string is blank OR the regular expression brings no matches.
|
0

Try:

if(strpos($_POST['postImg'], '.png') || strpos($_POST['postImg'], '.jpeg') || strpos($_POST['postImg'], '.gif')) {
    echo 'It exists';
}

1 Comment

This will allow input.png.exe, which isn't an image. You'd need to match the extension, not the contents of the string.

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.