Check on Image filename

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
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Check on Image filename

Post by tito85 »

Hi,

I have the below code in my script and I would like to add a check to this code so that when a user tries to upload an image, the system will check that the image name is unique from all other image names in the database. If there is an image with the same filename in the database an error msg will show up telling the user to change the image name or something.

Code: Select all

<?
session_start();
require('config/connection.php');
if (isset($_POST['btnCancel']))
{
header('Location: index.php');
}
else if (isset($_POST['btnRegister']))
{
$username = $_POST['txtUsername'];
$password = ($_POST['txtPassword']);
if (strlen(trim($username)) > 0 && strlen(trim($password)) > 0)
{
$confirmpassword = ($_POST['txtConfirmPassword']);
$firstname = $_POST['txtFirstName'];
$lastname = $_POST['txtLastName'];
$email = $_POST['txtEmail'];
if (strlen($_POST['txtDOB']) > 0)
{
$dob = explode("/", $_POST['txtDOB']);
$day = $dob[0];
$month = $dob[1];
$year = $dob[2];
$dob = date("Y-m-d", mktime(0,0,0,$month,$day,$year));
}
else
{
$dob = "";
}
$location = $_POST['txtLocation'];
$image = $_FILES['txtImage'];
$filename = "";
//checking if an image was uploaded
if ($image)
{
//checking if image is JPG
if ($image['type'] == "image/jpeg" || $image['type'] == "image/pjpeg")
{
$filename = $image['name'];
//uploading the file
move_uploaded_file($image['tmp_name'], "images/users/" . $image['name']);
}
else
{
$message = "Only .jpg images are allowed to be uploaded";
}
}
if (isset($_POST['rbnGender']))
{
$gender = $_POST['rbnGender'];
}
else
{
$gender = "";
}
if ($password == $confirmpassword)
{
$insert = "INSERT INTO users (username, password, firstname, lastname, email, dob, location, gender, filename, userlevel) VALUES ('" . addslashes($username) . "', '" .
addslashes($password) . "', '" . addslashes($firstname) . "', '" . addslashes($lastname) . "', '" . addslashes($email) . "', '" . addslashes($dob) . "', '" . addslashes($location) . "', '" . addslashes($gender) . "', '" . addslashes($filename) . "', '0')";
mysql_query($insert) or die(mysql_error());
header('Location: index.php');
}
else
{
$message = "Error: <b>Passwords</b> do not match";
}
}
else
{
$message = "Error: <b>Username</b> and <b>Password</b> are mandatory";
}
}
?> 
lunarnet76
Forum Commoner
Posts: 67
Joined: Sun Apr 04, 2010 2:07 pm
Location: Edinburgh

Re: Check on Image filename

Post by lunarnet76 »

Hi,

the solution is just to check after the upload,
you also forgot to do the insert ONLY if there is no error!

here should be the solution

Code: Select all

<?php
session_start();
require('config/connection.php');
if (isset($_POST['btnCancel'])) {
    header('Location: index.php');
}else if (isset($_POST['btnRegister'])) {
    $username = $_POST['txtUsername'];
    $password = ($_POST['txtPassword']);
    if (strlen(trim($username)) > 0 && strlen(trim($password)) > 0) {
        $confirmpassword = ($_POST['txtConfirmPassword']);
        $firstname = $_POST['txtFirstName'];
        $lastname = $_POST['txtLastName'];
        $email = $_POST['txtEmail'];
        if (strlen($_POST['txtDOB']) > 0) {
            $dob = explode("/", $_POST['txtDOB']);
            $day = $dob[0];
            $month = $dob[1];
            $year = $dob[2];
            $dob = date("Y-m-d", mktime(0,0,0,$month,$day,$year));
        }else {
            $dob = "";
        }
        $location = $_POST['txtLocation'];
        $image = $_FILES['txtImage'];
        $filename = "";
        //checking if an image was uploaded
        if ($image) {
            //checking if image is JPG
            if ($image['type'] == "image/jpeg" || $image['type'] == "image/pjpeg") {
                $filename = $image['name'];
                //uploading the file
                move_uploaded_file($image['tmp_name'], "images/users/" . $image['name']);
                // do the query to check if this image exists
                $query=mysql_query('SELECT filename FROM users WHERE filename="'.mysql_real_escape_string($filename).'"') or die(mysql_error());
                if(mysql_num_rows($query))
                    $message='This image already exists in the database';
           }else {
                $message = "Only .jpg images are allowed to be uploaded";
            }
        }
        if (isset($_POST['rbnGender'])) {
            $gender = $_POST['rbnGender'];
        }else {
            $gender = "";
        }
        
        if ($password == $confirmpassword && !isset($message)) {
            $insert = "INSERT INTO users (username, password, firstname, lastname, email, dob, location, gender, filename, userlevel) VALUES ('" . addslashes($username) . "', '" .
                    addslashes($password) . "', '" . addslashes($firstname) . "', '" . addslashes($lastname) . "', '" . addslashes($email) . "', '" . addslashes($dob) . "', '" . addslashes($location) . "', '" . addslashes($gender) . "', '" . addslashes($filename) . "', '0')";
            mysql_query($insert) or die(mysql_error());
            header('Location: index.php');
        }else {
            $message = "Error: <b>Passwords</b> do not match";
        }
    }else {
        $message = "Error: <b>Username</b> and <b>Password</b> are mandatory";
    }
}
?>
just a few tips for you : you should always use <?php instead of <?, use mysql_real_escape_string instead of addslashes, and use meaningful variable name like using $error instead of $message and indent your if, else using tabulation!
hope it helps :drunk:
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: Check on Image filename

Post by tito85 »

Hi, Thanks for your help.

It Is working now but it is not giving me the right message if i upload an image with a file name that is already in the database. it is giving me the "passwords do not match" although the passwords are correct...

Any idea why?
lunarnet76
Forum Commoner
Posts: 67
Joined: Sun Apr 04, 2010 2:07 pm
Location: Edinburgh

Re: Check on Image filename

Post by lunarnet76 »

yeah, use this instead!

Code: Select all

if(!isset($message)){
            if ($password == $confirmpassword ) {
                $insert = "INSERT INTO users (username, password, firstname, lastname, email, dob, location, gender, filename, userlevel) VALUES ('" . addslashes($username) . "', '" .
                        addslashes($password) . "', '" . addslashes($firstname) . "', '" . addslashes($lastname) . "', '" . addslashes($email) . "', '" . addslashes($dob) . "', '" . addslashes($location) . "', '" . addslashes($gender) . "', '" . addslashes($filename) . "', '0')";
                mysql_query($insert) or die(mysql_error());
                header('Location: index.php');
            }else {
                $message = "Error: <b>Passwords</b> do not match";
            }
        }
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: Check on Image filename

Post by tito85 »

Hi, Thanks for your great it is working fine now!

regarding the tips you gave me, if I change the addslashes with the mysql_real_escape_string should I do something else or everything will work as it is?

about the use of <?php, I use only the <? because i am using wampserver localy using "short open tag". To be honest I do this because at school we used to do like that and i don't know if i change or add something what will happen...

thanks....
lunarnet76
Forum Commoner
Posts: 67
Joined: Sun Apr 04, 2010 2:07 pm
Location: Edinburgh

Re: Check on Image filename

Post by lunarnet76 »

you just need to use mysql_real_escape_string, nothing more
For the <? issue just know that the open tags won't work in every server as <?php does!
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: Check on Image filename

Post by tito85 »

ok but if i change <? with <?php will it still work? because if i'm not mistaken when i tried it it didn't work.... :/
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

Re: Check on Image filename

Post by omniuni »

<?php

is the correct way to open PHP code, and will work on all servers where PHP is installed correctly. <? is a short-open tag, and will not work all the time.
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: Check on Image filename

Post by tito85 »

So the only different thing of short open tags is <? to <?php

Hence if I replace <? with <?php and untick the short open tags in the wamp server it should work or maybe there are other things that might are not ok?

For example this part of code is not working...

Code: Select all

<?php = $_SESSION['userinfo']['username'] ?>
or

Code: Select all

<?php = stripslashes($user['firstname']); ?>


Sorry about these questions but I am confused...
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

Re: Check on Image filename

Post by omniuni »

It is not recommended to echo values like that. Instead, call echo explicitly:

Code: Select all

<?php echo $_SESSION['username']; ?>
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: Check on Image filename

Post by tito85 »

It Seems to work fine now! Thanks for your help!

however i encontered another problem...

I have the below code, before I posted that I needed to do a check on the image name so if the image already exist in the database it will tell the user to change the image name. However if the user does not upload any image the error of "only .jpeg images are allowed" is showing up. It's like the user is required to upload the image... However I want that the image is not required and if the user does not upload any image the registration will be done too.

Any help please?

Code: Select all

<?php
  session_start();
  require('config/connection.php');
  if (isset($_POST['btnCancel'])) {
      header('Location: index.php');
  } elseif (isset($_POST['btnRegister'])) {
      $username = $_POST['txtUsername'];
      $password = ($_POST['txtPassword']);
      if (strlen(trim($username)) > 0 && strlen(trim($password)) > 0) {
          $confirmpassword = ($_POST['txtConfirmPassword']);
          $firstname = $_POST['txtFirstName'];
          $lastname = $_POST['txtLastName'];
          $email = $_POST['txtEmail'];
          if (strlen($_POST['txtDOB']) > 0) {
              $dob = explode("/", $_POST['txtDOB']);
              $day = $dob[0];
              $month = $dob[1];
              $year = $dob[2];
              $dob = date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));
          } else {
              $dob = "";
          }
          $location = $_POST['txtLocation'];
          $image = $_FILES['txtImage'];
          $filename = "";
          //checking if an image was uploaded
          if ($image) {
              //checking if image is JPG
              if ($image['type'] == "image/jpeg" || $image['type'] == "image/pjpeg") {
                  $filename = $image['name'];
                  //uploading the file
                  move_uploaded_file($image['tmp_name'], "images/users/" . $image['name']);
                  // do the query to check if this image exists
                  $query = mysql_query('SELECT filename FROM users WHERE filename="' . mysql_real_escape_string($filename) . '"') or die(mysql_error());
                  if (mysql_num_rows($query))
                      $message = 'The Image name already exists in the database. Please change Image name and try again.';
              } else {
                  $message = "Only .jpg format images are allowed to be uploaded";
              }
			}
				// do the query to check if the username exists
			   	$query2 = mysql_query('SELECT username FROM users WHERE username="' . mysql_real_escape_string($username) . '"') or die(mysql_error());
                  if (mysql_num_rows($query2))
                      $message = 'The Username is already in use. Please select a different Username and try again.';
          if (isset($_POST['rbnGender'])) {
              $gender = $_POST['rbnGender'];
          } else {
              $gender = "";
          }
          if (!isset($message)) {
              if ($password == $confirmpassword) {
                  $insert = "INSERT INTO users (username, password, firstname, lastname, email, dob, location, gender, filename, userlevel) VALUES ('" . mysql_real_escape_string($username) . "', '" . mysql_real_escape_string($password) . "', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($lastname) . "', '" . mysql_real_escape_string($email) . "', '" . mysql_real_escape_string($dob) . "', '" . mysql_real_escape_string($location) . "', '" . mysql_real_escape_string($gender) . "', '" . mysql_real_escape_string($filename) . "', '0')";
                  mysql_query($insert) or die(mysql_error());
                  header('Location: index.php');
              } else {
                  $message = "Error: Passwords do not match";
              }
          }
      } else {
          $message = "Error: Username and Password are mandatory";
      }
  }
?>
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: Check on Image filename

Post by Weiry »

Well assuming the user does not upload an image, i would imagine that $_FILES['txtImage'] should be empty. To test this though, you should try doing a (following code) after you submit no image to see if $_FILES is empty or not.

Code: Select all

print_r($_FILES['txtImage']);
Currently your just checking to see if it exists at all, empty or not.
Line 27:

Code: Select all

if(!empty($image)){
Or try an }elseif(){ statement on line 37:

Code: Select all

}elseif(!empty($image['type'])){
	$message = "Only .jpg format images are allowed to be uploaded";
}
Post Reply