Upload a default image

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

Upload a default image

Post by tito85 »

Hi,

I am using this code for user registration. I would like that if the user does not select any image for his profile a default image will be uploaded.

Any help please?

Code: Select all

<?php
  session_start();
  require('dbconnect.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 = "";
          }
          $country = $_POST['txtcountry'];
          $image = $_FILES['txtImage'];
          $filename = "";
          //checking if an image was uploaded
		  if(!empty($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.';
             }elseif(!empty($image['type'])){
        $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['rbnsex'])) {
              $sex = $_POST['rbnsex'];
          } else {
              $sex = "";
          }
          if (!isset($message)) {
              if ($password == $confirmpassword) {
                  $insert = "INSERT INTO users (username, password, firstname, lastname, email, dob, country, sex, filename, usertype) 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($country) . "', '" . mysql_real_escape_string($sex) . "', '" . 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";
      }
  }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<link rel="stylesheet" href="CSSWebStyles/style.css" /> 
<title>Online Movie Database - Register</title> 
</head> 
<body> 
<div id="website"> 
<?php
  include('banner.php');
?> 
<div id="content">
<center>
<br><h2>Register at Online Movie Database</h2><br>
</center>
<div id="contentgeneral2"> 
<?php
  if (isset($message)) {
      echo "<center>$message</center>";
      unset($message);
  }
?> 
<form method="post" enctype="multipart/form-data"> 
<table> 
<tr> 
<td> 
First Name: 
</td> 
<td> 
<input type="text" style="width: 200px;" name="txtFirstName" /> 
</td> 
</tr> 
<tr> 
<td> 
Last Name: 
</td> 
<td> 
<input type="text" style="width: 200px;" name="txtLastName" /> 
</td> 
</tr>
<tr> 
<td> 
Username: 
</td> 
<td> 
<input type="text" style="width: 200px;" name="txtUsername" />* 
</td> 
</tr> 
<tr> 
<td> 
Select a Password: 
</td> 
<td> 
<input type="password" style="width: 200px;" name="txtPassword" />* 
</td> 
</tr> 
<tr> 
<td> 
Confirm Password: 
</td> 
<td> 
<input type="password" style="width: 200px;" name="txtConfirmPassword" />* 
</td> 
</tr>  
<tr> 
<td> 
Email: 
</td> 
<td> 
<input type="text" style="width: 250px;" name="txtEmail" /> 
</td> 
</tr> 
<tr> 
<td> 
D.O.B.: 
</td> 
<td> 
<input type="text" style="width: 150px;" name="txtDOB" /><small>format: (dd/mm/yyyy)</small>
</td> 
</tr> 
<tr>
<td>
Country:
</td>
<td>
<select name="txtcountry" class="fields" id="country">
<option value="" selected>Please choose from list</option>
                            <option>Afghanistan </option>
                            <option>Albania </option>
                            <option>Other</option>
      </select>
</td>
</tr>
<tr> 
<td> 
Sex: 
</td> 
<td> 
<input type="radio" value="Male" name="rbnsex" /> Male 
<input type="radio" value="Female" name="rbnsex" /> Female 
</td> 
</tr> 
<tr> 
<td> 
Profile Image: 
</td> 
<td> 
<input type="file" name="txtImage" /> <br><br>
</td> 
</tr> 
<tr> 
<td colspan="2" align="center"> 
<input type="submit" name="btnRegister" value="Register" />&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="btnCancel" value="Cancel" /> 
</td> 
</tr> 
</table> 
</form> 
</div> 
<div id="contentright"> 
<div class="blog2" style="float: right; margin-right: 160px; margin-top:40px; width: 250px;"> 
<h2><center>Why should you Register?</center></h2> 
<ul> <br>
<li>Rate Movies from 1 to 10</li> <br>
<li>Give your Comments on Movies</li> <br>
<li>Select Your Favorite Movies</li>  
</ul> 
</div> 
</div> 
</div> 
<?php
  //will include the code from footer.php file 
  include('footer.php');
?> 
</div> 
</body> 
</html>
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: Upload a default image

Post by cpetercarter »

You can't upload a default image. Only the user can upload an image from his/her computer. But you can have a default image in your images folder which is selected if the user has not chosen to upload an image of their own. The simple way to achieve this is to replace the line

Code: Select all

$filename = "";
at the beginning of the section which handles the uploaded image with

Code: Select all

$filename="[name of default image]";
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: Upload a default image

Post by tito85 »

Thanks for your help it is working however if a user with the default image updates his profile and add his own image, the old image ie the default image is deleted. Is there any way that if the user has the default image the image will not be deleted?

This is the code where the user updates his profile.

Code: Select all

<?php
  session_start();
  require('dbconnect.php');
  include('securitycheck.php');
  if (isset($_POST['btnUpdate'])) {
      $firstname = $_POST['txtFirstName'];
      $lastname = $_POST['txtLastName'];
      $email = $_POST['txtEmail'];
      $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));
      $Country = $_POST['txtCountry'];
      $image = $_FILES['txtImage'];
      $currentimage = $_POST['txtCurrentImage'];
      $filename = $currentimage;
      //checking if an image was uploaded
      if (strlen($image['name']) > 0) {
          //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']);
              //remove old image
              if (strlen($currentimage) > 0) 
                  unlink("images/users/" . $currentimage);
          } else {
              $message = "Only .jpg images are allowed to be uploaded";
          }
      }
      if (isset($_POST['rbnSex']))
          $Sex = $_POST['rbnSex'];
      else
          $Sex = "";
      $SHFirstName = 0;
      $SHLastName = 0;
      $SHEmail = 0;
      $SHDOB = 0;
      $SHCountry = 0;
      $SHImage = 0;
      $SHSex = 0;
      if (isset($_POST['chkSHFirstName']))
          $SHFirstName = 1;
      if (isset($_POST['chkSHLastName']))
          $SHLastName = 1;
      if (isset($_POST['chkSHEmail']))
          $SHEmail = 1;
      if (isset($_POST['chkSHDOB']))
          $SHDOB = 1;
      if (isset($_POST['chkSHCountry']))
          $SHCountry = 1;
      if (isset($_POST['chkSHSex']))
          $SHSex = 1;
      if (isset($_POST['chkSHImage']))
          $SHImage = 1;
      $insert = "UPDATE users SET FirstName = '" . mysql_real_escape_string($firstname) . "', LastName = '" . mysql_real_escape_string($lastname) . "', EMail = '" . mysql_real_escape_string($email) . "', DOB = '" . mysql_real_escape_string($dob) . "', Country = '" . mysql_real_escape_string($Country) . "', Sex = '" . mysql_real_escape_string($Sex) . "', Filename = '" . $filename . "', SHFirstName = '" . $SHFirstName . "', SHLastName = '" . $SHLastName . "', SHEmail = '" . $SHEmail . "', SHDOB = '" . $SHDOB . "', SHCountry = '" . $SHCountry . "', SHSex = '" . $SHSex . "', SHImage = '" . $SHImage . "' WHERE UserID = '" . $_SESSION['userinfo']['id'] . "'";
      mysql_query($insert) or die(mysql_error());
  } elseif (isset($_POST['btnUpdatePassword'])) {
      $oldpassword = $_POST['txtoldpassword'];
      $newpassword = $_POST['txtnewpassword'];
      $query = "UPDATE users SET Password = '" . ($newpassword) . "' WHERE UserID = '" . $_SESSION['userinfo']['id'] . "' AND Password = '" . ($oldpassword) . "'";
      mysql_query($query);
  }
  $query = "SELECT * FROM users WHERE UserID = '" . $_SESSION['userinfo']['id'] . "'";
  $result = mysql_query($query);
  $firstname = mysql_result($result, 0, 'FirstName');
  $lastname = mysql_result($result, 0, 'LastName');
  $email = mysql_result($result, 0, 'EMail');
  $dob = mysql_result($result, 0, 'DOB');
  $Country = mysql_result($result, 0, 'Country');
  $Sex = mysql_result($result, 0, 'Sex');
  $SHFirstName = mysql_result($result, 0, 'SHFirstName');
  $SHLastName = mysql_result($result, 0, 'SHLastName');
  $SHEmail = mysql_result($result, 0, 'SHEmail');
  $SHDOB = mysql_result($result, 0, 'SHDOB');
  $SHCountry = mysql_result($result, 0, 'SHCountry');
  $SHSex = mysql_result($result, 0, 'SHSex');
  $SHImage = mysql_result($result, 0, 'SHImage');
  $currentimage = mysql_result($result, 0, 'Filename');
?>
User avatar
hypedupdawg
Forum Commoner
Posts: 74
Joined: Sat Apr 10, 2010 5:21 am

Re: Upload a default image

Post by hypedupdawg »

I shoukld think that the easiest way to escape this is to simply put an extra criteria in your IF statement like this:

Code: Select all

if (strlen($currentimage) > 0 && $currentimage != "defaultImagePath") 
                  unlink("images/users/" . $currentimage);
As long as you input the default image path (or a variable for the default path) it should only unlink the file if there is a path AND it is not the specified name. You could do this with more than one path to allow the use of many images you want to keep on your site.
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: Upload a default image

Post by tito85 »

It is working!

Thanks for your Great Help!!!
User avatar
hypedupdawg
Forum Commoner
Posts: 74
Joined: Sat Apr 10, 2010 5:21 am

Re: Upload a default image

Post by hypedupdawg »

Good - it's nice to be able to say "I helped someone today!" :D
I presume you know about expanding these conditions as you have used them before in your code - for example, you could say:

Code: Select all

if (strlen($currentimage) > 0 && ($currentimage != "defaultImagePath" || $override == 1)) 
                  unlink("images/users/" . $currentimage);
 
...so that you or an admin could replace the default image by inserting an override code.

Just an idea...
Post Reply