Jump to content

Please help uploading 2 images


lingo5

Recommended Posts

I've taken the liberty of cleaning the code up a bit, and rewritten it to how I'd do it. Hopefully you both will find it interesting, and useful. ;)

<?php

/**
* New version of quote_smart handling null values and locales with comma as decimal separator.
* For usage with mysqli or other database connectors change the mysql_real_escape string to match the
*  database specific escaper of your choice.
*
* Based on quote_smart function from php.net and feedback norskwebforum.no.
* Thanks to Zerd for pointing out problem with null values and magic_quotes
* 
* @version 1.01
* @author Ketil Stadskleiv <ks@akkreditering.net>
* @param mixed $value
* @return string
*/
function quote_smart($value){
        // Stripslashes
        if (get_magic_quotes_gpc() && !is_null($value) ) {
                $value = stripslashes($value);
        }

        //Change decimal values from , to . if applicable
        if( is_numeric($value) && strpos($value,',') !== false ){
                $value = str_replace(',','.',$value);
        }
        if( is_null($value) ){
                $value = 'NULL';
        }
        // Quote if not integer or null
        elseif (!is_numeric($value)) {
                $value = "'" . mysql_real_escape_string($value) . "'";
        }

        return $value;
}

/**
* Uploads document files to the new location set by $uploadDir.
* 
* If an error occurs it'll return false, and set the error message
* in the $error variable, which is sent by reference.
* Otherwise it'll return an array with the new file locations.
* 
* @param string $uploadDir
* @param string &$error
* @return mixed
*/
function upload_files ($uploadDir, &$error) {
$uploaded = array ();

// TODO: Verify that the uploadDir is writable.

// Run through the $_FILES, which is now an array with two keys "esp" and "cat".
foreach ($_FILES['documento_path'] as $lang => $file) {
	// TODO: Write the function that validates the filename.
	if (!$fileName = validateFileName ($file['name'])) {
		// TODO: Not a valid filename, set error message.
		$error = '';
		return false;
	}

	// Check for upload errors.
	if ($file['error'] != 0) {
		// TODO: Find and set the correcet error message from the error status.
		$error = '';
		return false;
	}

	// Set default picture, if no file has been uploaded.
	if (empty ($fileName)) {
		$fileName = 'img/none.jpg';
	}

	// Replace spaces with underscores.
	$fileName = str_replace (' ', '_', $fileName);

	// Move and rename the file.
	if (!move_uploaded_file ($file['tempname'], $fileName)) {
		// TODO: Failed moving the file, add error.
		$error = '';
		return false;
	}

	// Add new file path and location to the result array.
	$uploaded[$lang] = $fileName;
}

// Return array containing list of newly placed files.
return $uploaded;
}


// Define upload folder.
$uploadDir = '../uploads/';

// Check if any content have been submitted via the form.
if (isset ($_POST['upload'])) {
// TODO: Validate input!!
$documento_titulo_esp = $_POST["documento_titulo_esp"];
$documento_titulo_cat = $_POST["documento_titulo_cat"];

// Upload the files, and retrive paths.
$filePaths = upload_files ($uploadDir, $error);

if (empty ($error)) {
	// Create query, and use quote_smart () to escape output and defend against SQL injections etc.
	$fields = 'documento_titulo_esp, documento_titulo_cat, documento_path_esp, documento_path_cat';
	$query = sprintf ("INSERT INTO t_documentos ($fields) " . "VALUES (%s, %s, %s, %s)",
						quote_smart ($documento_titulo_esp), quote_smart ($documento_titulo_cat),
						quote_smart ($filePaths['esp']), quote_smart ($filePaths['cat']));

	mysql_query ($query) or die ('Error, query failed : ' . mysql_error ());

	header ("Location: PC_documentos_display.php?documentoinserted=true");
	die ();
} else {
	// Show error message and repopulate form.
}
}

?>
<form action="" method="post" enctype="multipart/form-data" id="form1">
<fieldset>
	<legend class="personalTitulo"><?=CNT_TXT_ETIQCLOUD_NUEVODOCUMENTO?></legend>

	<label><?=CNT_TXT_VARIOUS_TITULOESP?></label>
	<input name="documento_titulo_esp" type="text" class="CP_loginFormFields" id="documento_titulo_esp" value="<?=$tituloEsp?>" />

	<label><?=CNT_TXT_VARIOUS_TITULOCAT?></label>
	<input name="documento_titulo_cat" type="text" class="CP_loginFormFields" id="documento_titulo_cat" value="<?=$tituloCat?>" />


	<label><?=CNT_TXT_FICHACLIENTE_SELECTPDF?> <span class="CP_SiNoText"><?=CNT_TXT_FICHACLIENTE_PDFSONLY?></span></label>
	<input name="documento_path[esp]" type="file" class="CP_loginFormFieldsRED" id="documento_path_esp" />
	<input name="documento_path[cat]" type="file" class="CP_loginFormFieldsRED" id="documento_path_cat" />
</fieldset>

<fieldset>
	<input name="upload" type="submit" id="upload" value="<?=CNT_TXT_BOTONES_INSERTARDOCUMENTO?>" />
	<input type="hidden" name="MM_insert" value="form1" />
</fieldset>
</form>

 

You'll notice that I've stripped out all of the table-related HTML, and a lot of other unnecessary stuff. The design of the page should be determined by the use of CSS, not tables. As you can see, not only is it easier to read, but it'll give you a lot more options when it comes to actually getting stuff as you want them.

I've also left a few comments in there on stuff that needs to be done, most of which should be fairly straight forward. The only part that can be a bit difficult, is the filename validation. That said, there should be plenty of tips and/or guides on how to do this correctly, and you can always ask for help if you get stuck. ;)

Link to comment
Share on other sites

Thanks ChristianF....but I think your code is far too complicated for me at this stage....

I have tried it and didn't work. I guess it needs extra work from me...but I don't have the knwledge righ now.

I really like the use of CSS to layout the form!!!

 

 

Link to comment
Share on other sites

Hehe, yeah. You'll need to work a bit on the code yourself, but it shouldn't be too difficult. ;) I've prefixed the areas where you need to expand upon the code with "TODO:", to make it easier for you to spot them.

I recommend reading through it line by line, seeing for yourself what each line of code does, and reading the comments. It's not that different from your code, after all, just a bit optimized and secured. Should there be something that you're really stumped on, it's just to ask. :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.