Jump to content

Uploading image file is not working


mrenigma

Recommended Posts

Hello,

 

I am currently racking my brains trying to work this out. I am creating a basic CMS system and one of the functions is to give them the option of adding pictures to their gallery however at the moment the uploaded file is not uploading...at all, the FILES array seems to have no recollection of it actually being posted.

 

The script is meant to:

 

1. User types in specific details on the form and selects the picture for upload.

2. The script then validates the given details and checks the uploaded file is in fact a image.

3. The script then moves the uploaded file to the storage location on the server.

4. Some basic SQL is then run to transfer the given details and the storage location to the database.

 

Here is the main script:

 

<?php

require_once('../includes/Sentry.php');
$theSentry = new Sentry();
$loc = "http://" . $HTTP_HOST . $PATH_INFO;

if (!$theSentry->checkLogin(4) ){ header("Location: login.php?loc=".$loc.""); die(); }

// Get the PHP file containing the DbConnector class
require_once('../includes/DbConnector.php');
require_once('../includes/Validator.php');

// Create an instance of DbConnector
$connector = new DbConnector();

global $HTTP_POST_FILES;

// Check whether a form has been submitted. If so, carry on
if ($HTTP_POST_VARS){


// Validate the entries
$validator = new Validator();

$validator->validateTextOnly($HTTP_POST_VARS['title'],'Picture Title');
$validator->validateTextOnly($HTTP_POST_VARS['alttext'],'Alt Text');
$validator->validateFile($HTTP_POST_FILES['uploaded_file'],'Uploaded File');

// Check whether the validator found any problems
if ( $validator->foundErrors() ){
echo '<center>There was a problem with: <br/><br/>'.$validator->listErrors('<br></center'); // Show the errors, with a line between each
}else{

$target_path = "../images/Pictures/".basename( $_FILES['uploaded_file']['name'])."";


if (!file_exists($target_path)) {

if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
   		 echo "The file ".  basename( $_FILES['uploaded_file']['name']). 
   		 " has been uploaded";

echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

} else{
    	echo "<center>There was an error uploading the file, please try again! <br/><br/></center>";
}

} else{
echo "<center>This file already exists, please rename file and try again. </center>";
}

// Create an SQL query (MySQL version)
// The 'addslashes' command is used 5 lines below for added security
// Remember to use 'stripslashes' later to remove them (they are inserted in front of any
// special characters

$insertQuery = "INSERT INTO cmspictures (Title,Alt Text,uploaded_file) VALUES (".
"'".$HTTP_POST_VARS['title']."', ".
"'".$HTTP_POST_VARS['alttext']."', ".
$target_path."')";

// Save the form data into the database 
if ($result = $connector->query($insertQuery)){

	// It worked, give confirmation
	echo '<center><b>Picture added to the database</b></center><br /><br />';
	echo "<center><b>File Name:</b> ".$_FILES['uploaded_file']['name']."";

}else{

	// It hasn't worked so stop. Better error handling code would be good here!
	exit('<center>Sorry, there was an error saving to the database</center>');

}
}
}
?>

<body>
<form name="addPicture" method="post" action="newPicture.php" formenctype="multipart/form-data">
        <p> Title:
          <input name="title" type="text" id="title" />
        </p>
        <p> Alternative Text (If the picture fails to show e.g. Image of Cat):
          <input name="alttext" type="text" id="altext" />
        </p>
        <p> Image File:
        <input name="uploaded_file" id="uploaded_file" type="file" /> 

</p>
        <p align="center">
          <input type="submit" name="Submit" value="Upload Picture">
        </p>
</form>

 

And here is the validation script:

 

<?php
require_once 'SystemComponent.php';
class Validator extends SystemComponent {

var $errors; // A variable to store a list of error messages

// Validate something's been entered
// NOTE: Only this method does nothing to prevent SQL injection
// use with addslashes() command
function validateGeneral($theinput,$description = ''){
	if (trim($theinput) != "") {
		return true;
	}else{
		$this->errors[] = $description;
		return false;
	}
}

// Validate text only
function validateTextOnly($theinput,$description = ''){
	$result = ereg ("^[A-Za-z0-9\ ]+$", $theinput );
	if ($result){
		return true;
	}else{
		$this->errors[] = $description;
		return false; 
	}
}

// Validate text only, no spaces allowed
function validateTextOnlyNoSpaces($theinput,$description = ''){
	$result = ereg ("^[A-Za-z0-9]+$", $theinput );
	if ($result){
		return true;
	}else{
		$this->errors[] = $description;
		return false; 
	}
}


// Validate Filenames
function validateFile($theinput,$description = ''){
	$allowedextensions = array("jpg", "png", "gif", "bmp", "tif", "JPG", "PNG", "GIF", "BMP", "TIF");
	$file_ext = substr($theinput, strripos($theinput, '.')+1);
	if (in_array($file_ext, $allowedextensions)) {
		return true;
	}else{
		$this->errors[] = "<center>You can only upload picture files with the extensions .jpg, .png, .bmp, .tif<br/> Yours was: ".$file_ext."</center>";
		return false;
	}

}


// Validate email address
function validateEmail($themail,$description = ''){
	$result = ereg ("^[^@ ]+@[^@ ]+\.[^@ \.]+$", $themail );
	if ($result){
		return true;
	}else{
		$this->errors[] = $description;
		return false; 
	}

}

// Validate numbers only
function validateNumber($theinput,$description = ''){
	if (is_numeric($theinput)) {
		return true; // The value is numeric, return true
	}else{ 
		$this->errors[] = $description; // Value not numeric! Add error description to list of errors
		return false; // Return false
	}
}

// Validate date
function validateDate($thedate,$description = ''){

	if (strtotime($thedate) === -1 || $thedate == '') {
		$this->errors[] = $description;
		return false;
	}else{
		return true;
	}
}

// Check whether any errors have been found (i.e. validation has returned false)
// since the object was created
function foundErrors() {
	if (count($this->errors) > 0){
		return true;
	}else{
		return false;
	}
}

// Return a string containing a list of errors found,
// Seperated by a given deliminator
function listErrors($delim = ' '){
	return implode($delim,$this->errors);
}

// Manually add something to the list of errors
function addError($description){
	$this->errors[] = $description;
}	

}
?>

 

Any help in resolving this issue would be greatly appreciated.

 

mrenigma

Link to comment
Share on other sites

Thanks Pikachu2000, that worked  ;D That was a very silly mistake lol

 

However I now have one more problem which I am hoping can be resolved.

 

I am getting this error:

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Text,Source) VALUES ('This is an image of Shrek', 'Image of Shrek', '../images/P' at line 1

 

The variable which sets the source comes out with this code:  ../images/Pictures/DSC05721.JPG

 

Here is the remade script which is causing the error:

 

<?php

require_once('../includes/Sentry.php');
require_once('../includes/CurrentPage.php');
$theSentry = new Sentry();
$loc = curPageName();

if (!$theSentry->checkLogin(4) ){ header("Location: login.php?loc=".$loc.""); die(); }

// Get the PHP file containing the DbConnector class
require_once('../includes/DbConnector.php');
require_once('../includes/Validator.php');

// Create an instance of DbConnector
$connector = new DbConnector();

global $_FILES;

// Check whether a form has been submitted. If so, carry on
if ($_POST){

    $file = basename($_FILES['uploaded_file']['name']);
    
// Validate the entries
$validator = new Validator();

$validator->validateTextOnly($_POST['title'],'Picture Title');
$validator->validateTextOnly($_POST['alttext'],'Alt Text');
$validator->validateFile($file,'Uploaded File');

// Check whether the validator found any problems
if ( $validator->foundErrors() ){
    echo '<center>There was a problem with: <br/><br/>'.$validator->listErrors('<br></center'); // Show the errors, with a line between each
}else{

    $target_path = "../images/Pictures/".$file."";


if (!file_exists($target_path)) {
    
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
            echo "<center>The file ".  $file. 
            " has been uploaded</center>";
    
    } else{
        echo "<center>There was an error uploading the file, please try again! <br/><br/></center>";
    }

} else{
    echo "<center>This file already exists, please rename file and try again. </center>";
}

// Create an SQL query (MySQL version)
// The 'addslashes' command is used 5 lines below for added security
// Remember to use 'stripslashes' later to remove them (they are inserted in front of any
// special characters

$insertQuery = "INSERT INTO cmspictures (Title,Alt Text,Source) VALUES (".
"'".$_POST['title']."', "."'".$_POST['alttext']."', '".$target_path."')";

    // Save the form data into the database 
    if ($result = $connector->query($insertQuery)){

        // It worked, give confirmation
        echo '<center><b>Picture added to the database</b></center><br /><br />';
        echo "<center><b>File Name:</b> ".$target_path."";

    }else{

        // It hasn't worked so stop. Better error handling code would be good here!
        echo('<center>Sorry, there was an error saving to the database</center><br/>');
        echo "<center><b>File Name:</b> ".$target_path."</center><br/>";
        die(mysql_error());
        

    }
}
}
?>

<body>
<form name="addPicture" method="post" action="newPicture.php" enctype="multipart/form-data">
        <p> Title:
          <input name="title" type="text" id="title" />
        </p>
        <p> Alternative Text (If the picture fails to show e.g. Image of Cat):
          <input name="alttext" type="text" id="altext" />
        </p>
        <p> Image File:
        <input name="uploaded_file" id="uploaded_file" type="file" /> 
        
</p>
        <p align="center">
          <input type="submit" name="Submit" value="Upload Picture">
        </p>
</form>

Link to comment
Share on other sites

:o Right again Pikachu2000, I didn't set up the SQL table right, I put Alt Text when I created the table rather than Alt_Text... I really don't know how I could be so stupid making silly mistakes.

 

Thank you for your help everyone  :D

 

I'll post the completed CMS onto the code snippets section for others to use when I am done.

 

mrenigma

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.