Jump to content

[SOLVED] Uploading Images to server and MySQL


Dada78

Recommended Posts

Wait a minute it is not completely fixed. When I update an image with my update form for images it does what it was doing before with all the images being named 0.gif. Also when I update an image I have to refresh the page to see the updated image on the page. Is their something I can add that will refresh the page after it updates.

 

Here is the current code.

 

<?php

   include ('session.php');
   $email = $_SESSION['email'];

   $image_dir = dirname(__FILE__).'/submitted/';
   if(!is_dir($image_dir)) die("Image dir does not exist");
   if(!is_writable($image_dir)) die("Image dir is not writable");

  // MAKE CONNECTION
      include ('db_connect.php');

  //Get user info
  if(!($result = mysql_query("SELECT * FROM users WHERE email='$email'")))
    die(mysql_error());
  if(mysql_num_rows($result) !== 1)
    die("Too many users");
  $user = mysql_fetch_array($result);

  $sql = "SELECT * FROM users WHERE email='$email'";
  if ($result = mysql_query($sql)) {
    if (mysql_num_rows($result)) {
      $row = mysql_fetch_array($result);
      $imgurl = $row["imgurl"];    
    } else {
      die("No user found");
    }
  } else {
    die(mysql_error());
  } 

  // here, we check if the form has been submitted, because we need to handle
  // redirection before we handle outputting the HTML stuff.

  if(isset($_POST['submit'])){
    if(!is_uploaded_file($_FILES['imagefile']['tmp_name']))
      $error = '*Please upload a picture.';
    elseif($_FILES['imagefile']['error']){
      $uploadErrors = array(
        UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
        UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
        UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
        UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
      );
      $error = '*'.$uploadErrors[$_FILES['imagefile']['error']];
    }else{

    //Move image
      $userid = mysql_insert_id();
      $ext = substr($_FILES['imagefile']['name'], strrpos($_FILES['imagefile']['name'], '.') + 1);
      $filename = $userid.$ext;
      if(!is_readable($_FILES['imagefile']['tmp_name']))
        die("Can't read temp file: ".$_FILES['imagefile']['tmp_name']);
      if(!move_uploaded_file($_FILES['imagefile']['tmp_name'], $image_dir.$filename))
        die("Failed to move uploaded file to ".$image_dir.$filename);

      //Update user info
      mysql_query("UPDATE users SET imgurl = '".mysql_real_escape_string($filename)."'  WHERE email='$email'")or die (mysql_error());

      $error = "Image Updated";

    }
}

?>

 

-Thanks

 

 

  • Replies 64
  • Created
  • Last Reply

You are working with the old code to generate the filename. You can't use this:

$userid = mysql_insert_id();

since you are doing an UPDATE (only works for an INSERT). Look closely at my last post around these lines:

 

      //Move image

      $ext = substr($_FILES['imgdata']['name'], strrpos($_FILES['imgdata']['name'], '.') + 1);

      $filename = $user['id'].$ext;

I am not sure I follow you, it was the last working code that I am using for this. Everything uploads fine it just doesn't name it to the ID of the user anymore like it use to.

 

Would I remove this line so it just update the image?

 

$filename = $user['id'].$ext;

Wait a minute it is not completely fixed. When I update an image with my update form for images it does what it was doing before with all the images being named 0.gif. Also when I update an image I have to refresh the page to see the updated image on the page. Is their something I can add that will refresh the page after it updates.

 

Here is the current code.

 

<?php

   include ('session.php');
   $email = $_SESSION['email'];

   $image_dir = dirname(__FILE__).'/submitted/';
   if(!is_dir($image_dir)) die("Image dir does not exist");
   if(!is_writable($image_dir)) die("Image dir is not writable");

  // MAKE CONNECTION
      include ('db_connect.php');

  //Get user info
  if(!($result = mysql_query("SELECT * FROM users WHERE email='$email'")))
    die(mysql_error());
  if(mysql_num_rows($result) !== 1)
    die("Too many users");
  $user = mysql_fetch_array($result);

  $sql = "SELECT * FROM users WHERE email='$email'";
  if ($result = mysql_query($sql)) {
    if (mysql_num_rows($result)) {
      $row = mysql_fetch_array($result);
      $imgurl = $row["imgurl"];    
    } else {
      die("No user found");
    }
  } else {
    die(mysql_error());
  } 

  // here, we check if the form has been submitted, because we need to handle
  // redirection before we handle outputting the HTML stuff.

  if(isset($_POST['submit'])){
    if(!is_uploaded_file($_FILES['imagefile']['tmp_name']))
      $error = '*Please upload a picture.';
    elseif($_FILES['imagefile']['error']){
      $uploadErrors = array(
        UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
        UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
        UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
        UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
      );
      $error = '*'.$uploadErrors[$_FILES['imagefile']['error']];
    }else{

    //Move image
      $userid = mysql_insert_id();
      $ext = substr($_FILES['imagefile']['name'], strrpos($_FILES['imagefile']['name'], '.') + 1);
      $filename = $userid.$ext;
      if(!is_readable($_FILES['imagefile']['tmp_name']))
        die("Can't read temp file: ".$_FILES['imagefile']['tmp_name']);
      if(!move_uploaded_file($_FILES['imagefile']['tmp_name'], $image_dir.$filename))
        die("Failed to move uploaded file to ".$image_dir.$filename);

      //Update user info
      mysql_query("UPDATE users SET imgurl = '".mysql_real_escape_string($filename)."'  WHERE email='$email'")or die (mysql_error());

      $error = "Image Updated";

    }
}

?>

 

-Thanks

 

 

 

I was looking at this code you posted. Replace

    //Move image
      $userid = mysql_insert_id();
      $ext = substr($_FILES['imagefile']['name'], strrpos($_FILES['imagefile']['name'], '.') + 1);
      $filename = $userid.$ext;

with

      //Move image
      $ext = substr($_FILES['imgdata']['name'], strrpos($_FILES['imgdata']['name'], '.') + 1);
      $filename = $user['id'].$ext;

Ok I made the changes, actually just removed $userid = mysql_insert_id(); from the code as I see that is all you did. The pictures are getting inserted but the names are just .jpg in the database.

 

Also is their something I can add that will allow the picture to show the new image without having to refresh the page?

 

Here is a pic of what the page looks like. When I first got the code working, the first time I changed the image it changed on the page without having to refresh. Now in order to see the update picture I have to refresh the page.

 

exampleln1.png

Paste the current copy of the code.

 

Also, I'm guessing it's the browser caching the image. In the URL of the image, add a timestamp like so:

 

<img src="/submitted/{$filename}?_=<?php echo time(); ?>" />

 

This will make a unique URL every time the page loads, forcing the browser to not cache it.

Where I added this code.

 

<img src="/submitted/{$filename}?_=<?php echo time(); ?>" width='460' height='345' /

 

It removes the call to the field in the database allowing the image to show.

 

 

Here is the full code for the page

 

<?php

   include ('session.php');
   $email = $_SESSION['email'];

   $image_dir = dirname(__FILE__).'/submitted/';
   if(!is_dir($image_dir)) die("Image dir does not exist");
   if(!is_writable($image_dir)) die("Image dir is not writable");

  // MAKE CONNECTION
      include ('db_connect.php');

  //Get user info
  if(!($result = mysql_query("SELECT * FROM users WHERE email='$email'")))
    die(mysql_error());
  if(mysql_num_rows($result) !== 1)
    die("Too many users");
  $user = mysql_fetch_array($result);
  
  $sql = "SELECT * FROM users WHERE email='$email'";
  if ($result = mysql_query($sql)) {
    if (mysql_num_rows($result)) {
      $row = mysql_fetch_array($result);
      $imgurl = $row["imgurl"];    
    } else {
      die("No user found");
    }
  } else {
    die(mysql_error());
  } 

  // here, we check if the form has been submitted, because we need to handle
  // redirection before we handle outputting the HTML stuff.

  if(isset($_POST['submit'])){
    if(!is_uploaded_file($_FILES['imagefile']['tmp_name']))
      $error = '*Please upload a picture.';
    elseif($_FILES['imagefile']['error']){
      $uploadErrors = array(
        UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
        UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
        UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
        UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
      );
      $error = '*'.$uploadErrors[$_FILES['imagefile']['error']];
    }else{

    //Move image
      $ext = substr($_FILES['imagefile']['name'], strrpos($_FILES['imagefile']['name'], '.') + 1);
      $filename = $userid.$ext;
      if(!is_readable($_FILES['imagefile']['tmp_name']))
        die("Can't read temp file: ".$_FILES['imagefile']['tmp_name']);
      if(!move_uploaded_file($_FILES['imagefile']['tmp_name'], $image_dir.$filename))
        die("Failed to move uploaded file to ".$image_dir.$filename);

      //Update user info
      mysql_query("UPDATE users SET imgurl = '".mysql_real_escape_string($filename)."'  WHERE email='$email'")or die (mysql_error());

      $error = "Image Updated";

    }
}

?>

<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>	
	<table width="100%" border="0" align="left" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">

<td><a href="user.php?action=editprofile">Edit Profile</a> | <a href="submit.php">Add Display</a> | <a href="user.php?action=edit">Edit Display</a> | <a href="user.php?action=images">Edit Images</a> | <a href="user.php?action=promote">Promote Your Display</a> | <a href="browse.php">Browse Displays</a>| <a href="logout.php">Log Out</a></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>  </td>
</tr>
<tr>
<td> <div align='center'><img src="/submitted/{$filename}?_=<?php echo time(); ?>" width='460' height='345' /></div></td>
</tr>
<tr>
<td> <div align='center'> This is your default display picture.</div></td>
</tr>
<tr>
<td> <div class='errorText' align='center'>
<?PHP
// then we check for the error message
if (isset($error)) {
   echo $error . '<br />';
}
?> </div>
</td>
<tr>
<tr>
<td>  </td>
</tr>
<tr>
<td> <p> <ul>
            <li> Photos may not contain nudity, violent or offensive material, or
copyrighted images. If you violate these terms your account will be deleted. </li>
            <li> Photos must be less than 5MB and in the following formats:  .jpg,.gif</li>
          </ul></p>
</td>
</tr>
<tr>
<td> <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" bgcolor="#990000">

<td><form name="images" method="post" action="user.php?action=images" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="3" cellspacing="1">
  <tr class="bg2">
    <td valign='bottom' width="383"><input type="file" name="imagefile"></td>
    <td valign='middle'><div align='right'><input type="submit" name="submit" value="Update"></div></td>
  </tr>
</table>
</form></td>
</tr>
</table>
</td>
</tr>
</table></td>
</tr>
</table>

this should work:

 

<?php

   include ('session.php');
   $email = $_SESSION['email'];

   $image_dir = dirname(__FILE__).'/submitted/';
   if(!is_dir($image_dir)) die("Image dir does not exist");
   if(!is_writable($image_dir)) die("Image dir is not writable");

  // MAKE CONNECTION
      include ('db_connect.php');

  //Get user info
  if(!($result = mysql_query("SELECT * FROM users WHERE email='$email'")))
    die(mysql_error());
  if(mysql_num_rows($result) !== 1)
    die("Too many users");
  $user = mysql_fetch_array($result);
  //Get URL of current image
  $filename = $user['imgurl'];

//Remove this block of code. It is redundent of the above code
//  $sql = "SELECT * FROM users WHERE email='$email'";
//  if ($result = mysql_query($sql)) {
//    if (mysql_num_rows($result)) {
//      $row = mysql_fetch_array($result);
//      $imgurl = $row["imgurl"];    
//    } else {
//      die("No user found");
//    }
//  } else {
//    die(mysql_error());
//  } 

  // here, we check if the form has been submitted, because we need to handle
  // redirection before we handle outputting the HTML stuff.

  if(isset($_POST['submit'])){
    if(!is_uploaded_file($_FILES['imagefile']['tmp_name']))
      $error = '*Please upload a picture.';
    elseif($_FILES['imagefile']['error']){
      $uploadErrors = array(
        UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
        UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
        UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
        UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
      );
      $error = '*'.$uploadErrors[$_FILES['imagefile']['error']];
    }else{

    //Move image
      $ext = substr($_FILES['imagefile']['name'], strrpos($_FILES['imagefile']['name'], '.') + 1);
      $filename = $userid.$ext;
      if(!is_readable($_FILES['imagefile']['tmp_name']))
        die("Can't read temp file: ".$_FILES['imagefile']['tmp_name']);
      if(!move_uploaded_file($_FILES['imagefile']['tmp_name'], $image_dir.$filename))
        die("Failed to move uploaded file to ".$image_dir.$filename);

      //Update user info
      mysql_query("UPDATE users SET imgurl = '".mysql_real_escape_string($filename)."'  WHERE email='$email'")or die (mysql_error());

      $error = "Image Updated";

    }
}

?>

<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>	
	<table width="100%" border="0" align="left" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">

<td><a href="user.php?action=editprofile">Edit Profile</a> | <a href="submit.php">Add Display</a> | <a href="user.php?action=edit">Edit Display</a> | <a href="user.php?action=images">Edit Images</a> | <a href="user.php?action=promote">Promote Your Display</a> | <a href="browse.php">Browse Displays</a>| <a href="logout.php">Log Out</a></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>  </td>
</tr>
<tr>
<td> <div align='center'><img src="/submitted/{$filename}?_=<?php echo time(); ?>" width='460' height='345' /></div></td>
</tr>
<tr>
<td> <div align='center'> This is your default display picture.</div></td>
</tr>
<tr>
<td> <div class='errorText' align='center'>
<?PHP
// then we check for the error message
if (isset($error)) {
   echo $error . '<br />';
}
?> </div>
</td>
<tr>
<tr>
<td>  </td>
</tr>
<tr>
<td> <p> <ul>
            <li> Photos may not contain nudity, violent or offensive material, or
copyrighted images. If you violate these terms your account will be deleted. </li>
            <li> Photos must be less than 5MB and in the following formats:  .jpg,.gif</li>
          </ul></p>
</td>
</tr>
<tr>
<td> <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" bgcolor="#990000">

<td><form name="images" method="post" action="user.php?action=images" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="3" cellspacing="1">
  <tr class="bg2">
    <td valign='bottom' width="383"><input type="file" name="imagefile"></td>
    <td valign='middle'><div align='right'><input type="submit" name="submit" value="Update"></div></td>
  </tr>
</table>
</form></td>
</tr>
</table>
</td>
</tr>
</table></td>
</tr>
</table>

Update this line, that should fix the image not displaying:

<td> <div align='center'><img src="/submitted/<?php echo $filename.'?_='.time(); ?>" width='460' height='345' /></div></td>

 

Is the new file at least getting uploaded and stored on the system?

ok...i replicated and tested this stuff on my system, so it better work now :)

 

<?php

   include ('session.php');
   $email = $_SESSION['email'];

   $image_dir = dirname(__FILE__).'/submitted/';
   if(!is_dir($image_dir)) die("Image dir does not exist");
   if(!is_writable($image_dir)) die("Image dir is not writable");

  // MAKE CONNECTION
      include ('db_connect.php');

  //Get user info
  if(!($result = mysql_query("SELECT * FROM users WHERE email='$email'")))
    die(mysql_error());
  if(mysql_num_rows($result) !== 1)
    die("Too many users");
  $user = mysql_fetch_array($result);
  //Get URL of current image
  $filename = $user['imgurl'];

  // here, we check if the form has been submitted, because we need to handle
  // redirection before we handle outputting the HTML stuff.

  if(isset($_POST['submit'])){
    if(!is_uploaded_file($_FILES['imagefile']['tmp_name']))
      $error = '*Please upload a picture.';
    elseif($_FILES['imagefile']['error']){
      $uploadErrors = array(
        UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
        UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
        UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
        UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
      );
      $error = '*'.$uploadErrors[$_FILES['imagefile']['error']];
    }else{

    //Move image
      $ext = substr($_FILES['imagefile']['name'], strrpos($_FILES['imagefile']['name'], '.'));
      $filename = $user['id'].$ext;
      if(!is_readable($_FILES['imagefile']['tmp_name']))
        die("Can't read temp file: ".$_FILES['imagefile']['tmp_name']);
      if(!move_uploaded_file($_FILES['imagefile']['tmp_name'], $image_dir.$filename))
        die("Failed to move uploaded file to ".$image_dir.$filename);

      //Update user info
      mysql_query("UPDATE users SET imgurl = '".mysql_real_escape_string($filename)."'  WHERE email='$email'")or die (mysql_error());

      $error = "Image Updated";

    }
}

?>

<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
  <td>  
    <table width="100%" border="0" align="left" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">

<td><a href="user.php?action=editprofile">Edit Profile</a> | <a href="submit.php">Add Display</a> | <a href="user.php?action=edit">Edit Display</a> | <a href="user.php?action=images">Edit Images</a> | <a href="user.php?action=promote">Promote Your Display</a> | <a href="browse.php">Browse Displays</a>| <a href="logout.php">Log Out</a></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>  </td>
</tr>
<tr>
<td> <div align='center'><img src="submitted/<?php echo $filename.'?_='.time(); ?>" width='460' height='345' /></div></td>
</tr>
<tr>
<td> <div align='center'> This is your default display picture.</div></td>
</tr>
<tr>
<td> <div class='errorText' align='center'>
<?PHP
// then we check for the error message
if (isset($error)) {
   echo $error . '<br />';
}
?> </div>
</td>
<tr>
<tr>
<td>  </td>
</tr>
<tr>
<td> <p> <ul>
            <li> Photos may not contain nudity, violent or offensive material, or
copyrighted images. If you violate these terms your account will be deleted. </li>
            <li> Photos must be less than 5MB and in the following formats:  .jpg,.gif</li>
          </ul></p>
</td>
</tr>
<tr>
<td> <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" bgcolor="#990000">

<td><form name="images" method="post" action="user.php?action=images" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="3" cellspacing="1">
  <tr class="bg2">
    <td valign='bottom' width="383"><input type="file" name="imagefile"></td>
    <td valign='middle'><div align='right'><input type="submit" name="submit" value="Update"></div></td>
  </tr>
</table>
</form></td>
</tr>
</table>
</td>
</tr>
</table></td>
</tr>
</table>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.