Jump to content

Uploading images fine but cant rename them to match userid


bluedaniel

Recommended Posts

Please help!

 

Im a rookie php developer and Im creating a recipes website, at the moment ive got the login working using sessions, the form below is one im using for uploading recipes, along with an image. trouble is the image just uploads itself into the directory under the origional name, it would like it to match the Recipe ID. also I cant get the User_ID inserted into the Recipes table.

 

 <form enctype="multipart/form-data" form id="form1" name="form1" method="post" action="newrecipe.php">
        <table width="801" border="0" id="recipeupload2">
          <tr>
            <td width="169" valign="top"><h1>
              <input name="user_id" type="hidden" id="user_id" value="<?php $_SESSION['user_id']; ?>" />
              Recipe Title:
              <label></label>
            </h1></td>
            <td width="622" valign="top"><input name="title" type="text" id="title" size="60" maxlength="60" />            </td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>Please choose your title carefully, it should be descriptive to other users.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Small Description:
              <label></label>
            </h1></td>
            <td valign="top"><textarea name="smalldesc" cols="60" rows="3" id="smalldesc"></textarea>            </td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>This will appear when a user searches for a recipe, this small description could be why you like this recipe or why others will want to try it. e.g. a Quick and Simple hearty meal etc.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Ingredients:
              <label></label>
            </h1></td>
            <td valign="top"><textarea name="ingredients" cols="60" rows="5" id="ingredients">100g pasta, 4 chicken breasts, grated cheese</textarea>            </td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>NOTE: To seperate each ingredient use a comma (,). If you use a comma then anything after that will be shown as a new item, above is the way you should type your ingredients.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Method:
              <label></label>
            </h1></td>
            <td valign="top"><textarea name="method" cols="60" rows="5" id="method"></textarea>            </td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>Separate steps using paragraphs, hit "enter" key. Do not number steps (we'll do that for you). </p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Time:
              <label></label>
            </h1></td>
            <td valign="middle"><input type="text" name="time" id="time" /></td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>How long will it take to make this recipe? This is a total figure with preperation taken into account.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Servings:
              <label></label>
            </h1></td>
            <td valign="middle"><input type="text" name="amount" id="amount" /></td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>How many servings will this recipe make? e.g You could type 'X Portions', 'X Helpings' or 'X Cookies'</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Upload Picture:</h1></td>
            <td valign="top"><label>
            	<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
            	<input name="uploaded_pic" type="file" />              
            </label></td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>This is greatly encouraged as it will make your recipe really stand out from the crowd, the dimensions will be 235px by 215px. It must be a jpeg image and not exceed 350kb in size.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Keywords:
              <label></label>
            </h1></td>
            <td valign="top"><textarea name="keywords" cols="60" rows="2" id="keywords"></textarea></td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>This is for our search engine, it could be anything you like and will mean that the words above will make your recipe appear when someone searches for that word. You could leave this blank if want.</p></td>
          </tr>
          <tr>
            <td colspan="2" valign="top"><label>
              <input type="button" name="cancel" id="cancel" value="Cancel" onclick="history.back()" />
              <input type="submit" name="continue" id="continue" value="Continue" />
            </label></td>
          </tr>
        </table>
    </form>

 

Here is the PHP handler:

 

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php confirm_logged_in(); ?>
<?php 
$title = $_POST['title'];
$smalldesc = $_POST['smalldesc'];
$ingredients = $_POST['ingredients'];
$method = $_POST['method'];
$time = $_POST['time'];
$amount = $_POST['amount'];
$keywords = $_POST['keywords'];
?>

<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_pic"])) && ($_FILES['uploaded_pic']['error'] == 0)) {
  //Check if the file is JPEG image and it's size is less than 350Kb
  $filename = basename($_FILES['uploaded_pic']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_pic"]["type"] == "image/jpeg") && 
    ($_FILES["uploaded_pic"]["size"] < 350000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/_images/_pic/'.$filename;
      //Check if the file with the same name is already exists on the server
      if (!file_exists($newname)) {
        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_pic']['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;
        } else {
           echo "Error: A problem occurred during file upload!";
        }
      } else {
         echo "Error: File ".$_FILES["uploaded_pic"]["name"]." already exists";
      }
  } else {
     echo "Error: Only .jpg images under 350Kb are accepted for upload";
  }
} else {
echo "Error: No file uploaded";
}
?>
<?php
$query = "INSERT INTO recipes (
			Title, Smalldesc, Ingredients, Method, Time, Amount, Keywords, 
		) VALUES (
		'{$title}', '{$desc}', '{$ingredients}', '{$method}', '{$time}', '{$amount}', '{$keywords}')";
		if (mysql_query($query, $connection)) {
			header("Location: allrecipes.php");
			exit;
		} else {
				echo "<p>Recipe not entered.</p>";
				echo "<p>" . mysql_error() . "</p>";
			}		
?>
<?php mysql_close($connection); ?>

 

any links to tutorials would be helpful as well!

 

thanks everyone

 

daniel

 

[attachment deleted by admin]

I'm explode happy today, but it works.

Where you have

$filename = basename($_FILES['uploaded_pic']['name']);

try

$file = basename($_FILES['uploaded_pic']['name']);
$file = "testingtxt.jpg";
list($file, $ext) = explode(".", $file);
$filename = $_POST['user_id'].".".$ext;

hmm thanks for the quick reply, Im not quite sure what ive done now but its not working all together, I had the values of $POST inserting into the database but thats not working now, on the other hand the image is being uploaded but without a filename.

 

Uploadrecipe.php:

<!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"><!-- InstanceBegin template="/Templates/Generic.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- InstanceBeginEditable name="doctitle" -->
<title>What Can I Cook | Upload Your Recipe</title>
<!-- InstanceEndEditable -->
<link href="/_css/template.css" rel="stylesheet" type="text/css" />
<link REL="SHORTCUT ICON" HREF="_images/favicon.ico">
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php confirm_logged_in(); ?>
<!-- InstanceBeginEditable name="head" -->
<link href="/_css/uploadrecipe.css" rel="stylesheet" type="text/css" />
<!-- InstanceEndEditable -->
</head>
<body>
<div id="wrapper">
  <div id="header">
   	<h1>What Can I Cook?</h1>
   	<div id="logoImage"></div>
  <ul id="mainNav">
    <li><a href="index.html">Home </a></li>
    <li><a href="allRecipes.php">Recipes </a></li>
    <li><a href="features.php">Features </a></li>
    <li><a href="blogs.php">Blogs </a></li>
    <li><a href="forum.php">Forum </a></li>
    <li><a href="share.php">Share </a></li>
    <li><a href="shop.html">Shop </a></li>
  </ul>
  </div>
  <!-- InstanceBeginEditable name="Main Content" -->
  <div id="content">    	
      <h1>Add your Recipe</h1>
      <p>We have tried to make this as painless as possible for you, below are the fields you can enter your information into and we have written tips and examples to the right of them to help smooth the process.</p>
<form enctype="multipart/form-data" form id="form1" name="form1" method="post" action="newrecipe.php">
        <table width="801" border="0" id="recipeupload2">
          <tr>
            <td width="169" valign="top"><h1>
              <input name="user_id" type="hidden" id="user_id" value="<?php $_SESSION['user_id']; ?>" />
              Recipe Title:
              <label></label>
            </h1></td>
            <td width="622" valign="top"><input name="title" type="text" id="title" size="60" maxlength="60" />            </td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>Please choose your title carefully, it should be descriptive to other users.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Small Description:
              <label></label>
            </h1></td>
            <td valign="top"><textarea name="smalldesc" cols="60" rows="3" id="smalldesc"></textarea>            </td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>This will appear when a user searches for a recipe, this small description could be why you like this recipe or why others will want to try it. e.g. a Quick and Simple hearty meal etc.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Ingredients:
              <label></label>
            </h1></td>
            <td valign="top"><textarea name="ingredients" cols="60" rows="5" id="ingredients">100g pasta, 4 chicken breasts, grated cheese</textarea>            </td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>NOTE: To seperate each ingredient use a comma (,). If you use a comma then anything after that will be shown as a new item, above is the way you should type your ingredients.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Method:
              <label></label>
            </h1></td>
            <td valign="top"><textarea name="method" cols="60" rows="5" id="method"></textarea>            </td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>Separate steps using paragraphs, hit "enter" key. Do not number steps (we'll do that for you). </p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Time:
              <label></label>
            </h1></td>
            <td valign="middle"><input type="text" name="time" id="time" /></td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>How long will it take to make this recipe? This is a total figure with preperation taken into account.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Servings:
              <label></label>
            </h1></td>
            <td valign="middle"><input type="text" name="amount" id="amount" /></td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>How many servings will this recipe make? e.g You could type 'X Portions', 'X Helpings' or 'X Cookies'</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Upload Picture:</h1></td>
            <td valign="top"><label>
            	<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
            	<input name="uploaded_pic" type="file" />              
            </label></td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>This is greatly encouraged as it will make your recipe really stand out from the crowd, the dimensions will be 235px by 215px. It must be a jpeg image and not exceed 350kb in size.</p></td>
          </tr>
          <tr>
            <td valign="top"><h1>Keywords:
              <label></label>
            </h1></td>
            <td valign="top"><textarea name="keywords" cols="60" rows="2" id="keywords"></textarea></td>
          </tr>
          <tr>
            <td valign="top"> </td>
            <td valign="top"><p>This is for our search engine, it could be anything you like and will mean that the words above will make your recipe appear when someone searches for that word. You could leave this blank if want.</p></td>
          </tr>
          <tr>
            <td colspan="2" valign="top"><label>
              <input type="button" name="cancel" id="cancel" value="Cancel" onclick="history.back()" />
              <input type="submit" name="continue" id="continue" value="Continue" />
            </label></td>
          </tr>
        </table>
    </form>
      </div>
  <!-- InstanceEndEditable -->
  <div id="clear"></div>
  <div id="footer">© 2007 Cheek Chastain Gallery. No portion of this  website or artwork portrayed herein may be redistributed of republished  without the expressed consent of Cheek Chastain Gallery. View our full  legal disclaimer here.</div>
</div>
</body>
<!-- InstanceEnd --></html>

 

Newrecipe.php:

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php 
$title = $_POST['title'];
$smalldesc = $_POST['smalldesc'];
$ingredients = $_POST['ingredients'];
$method = $_POST['method'];
$time = $_POST['time'];
$amount = $_POST['amount'];
$keywords = $_POST['keywords'];
?>
<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_pic"])) && ($_FILES['uploaded_pic']['error'] == 0)) {
  //Check if the file is JPEG image and it's size is less than 350Kb
$file = basename($_FILES['uploaded_pic']['name']);
$file = "testingtxt.jpg";
list($file, $ext) = explode(".", $file);
$filename = $_POST['user_id'].".".$ext;
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_pic"]["type"] == "image/jpeg") && 
    ($_FILES["uploaded_pic"]["size"] < 350000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/_images/_pic/'.$filename;
      //Check if the file with the same name is already exists on the server
      if (!file_exists($newname)) {
        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_pic']['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;
        } else {
           echo "Error: A problem occurred during file upload!";
        }
      } else {
         echo "Error: File ".$_FILES["uploaded_pic"]["name"]." already exists";
      }
  } else {
     echo "Error: Only .jpg images under 350Kb are accepted for upload";
  }
} else {
echo "Error: No file uploaded";
}
?>
<?php
$query = "INSERT INTO recipes (
			Title, Smalldesc, Ingredients, Method, Time, Amount, Keywords, 
		) VALUES (
		'{$title}', '{$desc}', '{$ingredients}', '{$method}', '{$time}', '{$amount}', '{$keywords}')";
		if (mysql_query($query, $connection)) {
			header("Location: allrecipes.php");
			exit;
		} else {
				echo "<p>Recipe not entered.</p>";
				echo "<p>" . mysql_error() . "</p>";
			}		
?>
<?php mysql_close($connection); ?>

 

Sorry for the really long posts!

change

$file = basename($_FILES['uploaded_pic']['name']);
$file = "testingtxt.jpg";
list($file, $ext) = explode(".", $file);
$filename = $_POST['user_id'].".".$ext;

to

$file = basename($_FILES['uploaded_pic']['name']);
list($file, $ext) = explode(".", $file);
$filename = $_POST['user_id'].".".$ext; //as is, this will make the file name something like 12.jpg
//You can modify the name by adding more to the $filename = line above.

and cross fingers

Hey thanks everyone who looked but the problem was a single comma at the end of the SQL query i forgot to remove!!

 

anyway Ive decided to insert the jpg with the filename being the same as the title of the recipe which works well.

 

however I cant get the User_ID varible to insert into the database, for some reason it is not stored in the _POST array, any ideas?

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.