13 Replies - 2623 Views - Last Post: 24 July 2019 - 01:23 PM Rate Topic: -----

#1 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 556
  • Joined: 30-April 15

Issue uploading an image file

Posted 23 July 2019 - 12:44 PM

I am having troubles getting an img img file to upload. I am not getting any errors returning in the response of the console. My ajax success is running through because the alert fires. No errors are showing in my error logging.

I don't get what I am doing wrong. The only thing I can think of is that my image file isn't sending through in the ajax. Everything I try to do in the php file to see what the file name is never returns. You can see my var_dumps attempts.

Does anyone see what I am doing wrong? Any tips on how I can debug this further?

Form
<form action="" method="POST" id="projectForm" enctype="multipart/form-data">
    <label>Project Name</label>
    <input type="text" class="input block" name="p_name">
    <label>Project Img</label>
    <input type="file" id="file" name="file" class="file-input block">
    <button id="submit">Submit Project</button>
</form>


JS
$('#projectForm').validate({
    ignore: [],
    rules: {
        p_name: {
            required: true,
            minlength: 5
        }
    },
    messages: {
        p_name: {
            required: "Please enter the project name",
            minlength: "The project name is too short"
        }
    },
    submitHandler: function (form, e) {
        e.preventDefault();
        var formData = new FormData(form);
        category = $(this).data('category');

        console.log(category);


        $.ajax({
            url: '/php/projectSend.php',
            type: 'POST',
            data: formData,
            success: function (data) {
                /*if (data == null) {
                    alert("Unable to sned project!");
                    alert(data);
                } else {
                    var displayProjects = JSON.parse(data);
                        console.log(this.html);
                });*/
                alert("Sent");

            },
            contentType: false,
            processData: false,
            error: function (xhr, textStatus, errorThrown) {
                alert(textStatus + " | " + errorThrown);
                alert('There are currently no project images for this selection');
            }
        });
    }
});



PHP
ini_set('display_errors', 1);
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');

$p_name = trim(htmlspecialchars($_POST['p_name'], ENT_QUOTES));
$p_alt = trim(htmlspecialchars($_POST['p_alt']));
$category = trim(htmlspecialchars($_POST['categoryName']));
$creator = trim(htmlspecialchars($_POST['creatorName']));
$status = $_POST['status'];

// If you make a file function, you can change where things are saved
// You can also change the destination (for portability)
	function UploadFile($fileArray, $destinationFolder = '../project_images/') {
		//$p_img = $fileArray['file'];

		$fileUploadData = $fileArray['file'];
		//var_dump($fileUploadData);
		$filename       =   $fileUploadData['name'];
		var_dump("file name". $filename);
		$tmp_name       =   $fileUploadData['tmp_name'];
		$filesize       =   $fileUploadData['size'];
		$file_error     =   $fileUploadData['error'];
        //$file           =   $fileArray['file'];
		
		/*
		$filename       =   $fileArray[$fileNameVar];
        $tmp_name       =   $fileArray[$fileTmpNameVar];
        $filesize       =   $fileArray[$fileSizeVar];
        $file_error     =   $fileArray[$fileErrorVar];
        $file           =   $fileArray[$p_img];
*/
		//var_dump($filename);
        // Save all the default data.
        // Success and error should be set by default to fail
        $return['error']        =   true;
        $return['success']      =   false;
        $return['file']['dest'] =   $destinationFolder.$filename;
        $return['file']['size'] =   $filesize;

        if($file_error == 0)
            $return['error']    =   false;
        // I added a directory creation function so you don't have to 
        // manually make folders. This will do it for you.
        if(!is_dir($destinationFolder))
            mkdir($destinationFolder,0755,true);
        // If your filename is not empty, return success or fail of upload
        if (!empty($filename))
            $return['success']  = (move_uploaded_file($tmp_name, $destinationFolder.$filename));
			//var_dump($filename);

        return $return;
    }

try {
    $con = getConfig('pdo');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Create a save-to-database function so it's easier and reusable
	function SaveToDb($con,$filename = false) {
        // Return fail immediately if the connection is false or image is invalid
        if(empty($filename) || !$con)
            return false;
		$project_sql = "
			INSERT INTO project_gallery
			(p_name, p_img, date_added)
			VALUES(?, ?, NOW())
		";
		if ($project_stmt = $con->prepare($project_sql)) {
			$project_stmt->execute(array($p_name, $p_img));
			return true;
			$proj_succ = "Success";
			echo json_encode($proj_succ);
		}
		return false;
	}
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
	file_put_contents('error_log_new', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
}

	if(isset($_POST['create'])) {
        // Try uploading
        $upload =   UploadFile($_FILES);
        // If upload fails
        if(!$upload['success']) {
            echo '<h3>Sorry, an error occurred</h3>';
		}
        else {
            // You could add error handling here based on the results of 
            // each function's success or failure below.

            // Try to save it
            $saveToDb   =   SaveToDb($con,$upload['file']['dest']);
            // Get the profile from image name
            $profPic    =   ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;   
        }
    }


Is This A Good Question/Topic? 0
  • +

Replies To: Issue uploading an image file

#2 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 556
  • Joined: 30-April 15

Re: Issue uploading an image file

Posted 23 July 2019 - 01:41 PM

Also, anytime I try to echo something from the UploadFile function, nothing is echoed/returns.
Was This Post Helpful? 0
  • +
  • -

#3 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2355
  • View blog
  • Posts: 7,192
  • Joined: 15-January 14

Re: Issue uploading an image file

Posted 23 July 2019 - 03:31 PM

There's a whole lot of things you can check. You can check the ajax request to see what it's actually submitting, that should be first. Make sure it's actually sending the file data. Compare it with a regular HTML post form with a file if you want to see what the request is supposed to look like.

Quote

Also, anytime I try to echo something from the UploadFile function, nothing is echoed/returns.

The obvious answer would be that you're not running the function. Again, verify what you are sending to PHP. In the PHP code, you can print the entire $_POST or $_FILES arrays or send them to an error log.
Was This Post Helpful? 1
  • +
  • -

#4 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2906
  • View blog
  • Posts: 11,328
  • Joined: 03-December 12

Re: Issue uploading an image file

Posted 23 July 2019 - 05:29 PM

if(isset($_POST['create'])) {



I don't see that key anywhere?
Was This Post Helpful? 1
  • +
  • -

#5 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 556
  • Joined: 30-April 15

Re: Issue uploading an image file

Posted 24 July 2019 - 06:56 AM

Thanks for the help guys.

I did what both of you suggested.

Andrew - I added the key and that helped get this going.

ArtificialSoldier - I added the $_POST values to a log file. The values are sending through.

What is now working:
  • The image file is now being moved to the destination folder.
  • The UploadFile function is running


What isn't working:
  • When I attempt to add the values in the execute part of the query, they aren't added.


Notice: Undefined variable: p_alt in /admin/php/projectSend.php on line 66

Notice: Undefined variable: category in /admin/php/projectSend.php on line 66

Notice: Undefined variable: creator in /admin/php/projectSend.php on line 66

Notice: Undefined variable: status in /admin/php/projectSend.php on line 66

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'p_name' cannot be null in /admin/php/projectSend.php:66 Stack trace: #0 /admin/php/projectSend.php(66): PDOStatement->execute(Array) #1 /admin/php/projectSend.php(90): SaveToDb(Object(PDO), '../project_imag...') #2 {main} thrown in /admin/php/projectSend.php on line 66

This post has been edited by pfar54: 24 July 2019 - 06:56 AM

Was This Post Helpful? 0
  • +
  • -

#6 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2906
  • View blog
  • Posts: 11,328
  • Joined: 03-December 12

Re: Issue uploading an image file

Posted 24 July 2019 - 07:02 AM

Quote

Integrity constraint violation: 1048 Column 'p_name' cannot be null

So the name isn't making it through.

Quote

ini_set('display_errors', 1);
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');

$p_name = trim(htmlspecialchars($_POST['p_name'], ENT_QUOTES));
$p_alt = trim(htmlspecialchars($_POST['p_alt']));
$category = trim(htmlspecialchars($_POST['categoryName']));
$creator = trim(htmlspecialchars($_POST['creatorName']));
$status = $_POST['status'];

// If you make a file function, you can change where things are saved
// You can also change the destination (for portability)
	function UploadFile($fileArray, $destinationFolder = '../project_images/') {
		//$p_img = $fileArray['file'];

		$fileUploadData = $fileArray['file'];
		//var_dump($fileUploadData);
		$filename       =   $fileUploadData['name'];
		var_dump("file name". $filename);
		$tmp_name       =   $fileUploadData['tmp_name'];
		$filesize       =   $fileUploadData['size'];
		$file_error     =   $fileUploadData['error'];
        //$file           =   $fileArray['file'];
		
		/*
		$filename       =   $fileArray[$fileNameVar];
        $tmp_name       =   $fileArray[$fileTmpNameVar];
        $filesize       =   $fileArray[$fileSizeVar];
        $file_error     =   $fileArray[$fileErrorVar];
        $file           =   $fileArray[$p_img];
*/
		//var_dump($filename);
        // Save all the default data.
        // Success and error should be set by default to fail
        $return['error']        =   true;
        $return['success']      =   false;
        $return['file']['dest'] =   $destinationFolder.$filename;
        $return['file']['size'] =   $filesize;

        if($file_error == 0)
            $return['error']    =   false;
        // I added a directory creation function so you don't have to 
        // manually make folders. This will do it for you.
        if(!is_dir($destinationFolder))
            mkdir($destinationFolder,0755,true);
        // If your filename is not empty, return success or fail of upload
        if (!empty($filename))
            $return['success']  = (move_uploaded_file($tmp_name, $destinationFolder.$filename));
			//var_dump($filename);

        return $return;
    }

try {
    $con = getConfig('pdo');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Create a save-to-database function so it's easier and reusable
	function SaveToDb($con,$filename = false) {
        // Return fail immediately if the connection is false or image is invalid
        if(empty($filename) || !$con)
            return false;
		$project_sql = "
			INSERT INTO project_gallery
			(p_name, p_img, date_added)
			VALUES(?, ?, NOW())
		";
		if ($project_stmt = $con->prepare($project_sql)) {
			$project_stmt->execute(array($p_name, $p_img));
			return true;
			$proj_succ = "Success";
			echo json_encode($proj_succ);
		}
		return false;
	}
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
	file_put_contents('error_log_new', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
}

	if(isset($_POST['create'])) {
        // Try uploading
        $upload =   UploadFile($_FILES);
        // If upload fails
        if(!$upload['success']) {
            echo '<h3>Sorry, an error occurred</h3>';
		}
        else {
            // You could add error handling here based on the results of 
            // each function's success or failure below.

            // Try to save it
            $saveToDb   =   SaveToDb($con,$upload['file']['dest']);
            // Get the profile from image name
            $profPic    =   ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;   
        }
    }


This has several issues. $p_name isn't getting through because of a scope issue. And you shouldn't have a function contained within a try block. The try block should be as limiting as it makes sense to be, not all encompassing.
Was This Post Helpful? 1
  • +
  • -

#7 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 556
  • Joined: 30-April 15

Re: Issue uploading an image file

Posted 24 July 2019 - 07:03 AM

Why would the values show in the file log and when I echo them in the UploadFile function, but not make it through to this other function?
Was This Post Helpful? 0
  • +
  • -

#8 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2906
  • View blog
  • Posts: 11,328
  • Joined: 03-December 12

Re: Issue uploading an image file

Posted 24 July 2019 - 07:08 AM

Because in the Upload function the name is part of the $_FILE array, the logging the name exists because it is not in the function. With in the function, there is no $p_name, so it creates it as an empty string.
Was This Post Helpful? 0
  • +
  • -

#9 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 556
  • Joined: 30-April 15

Re: Issue uploading an image file

Posted 24 July 2019 - 07:13 AM

I thought that by defining the variables outside of a function makes them global and then the function just overwrites the variable if modifications are made?

Should I just add the $_POST variables inside of the SaveToDb function then or is there a better way?

Just saw your try/catch comment. Would it be best to just wrap the query in this?
Was This Post Helpful? 0
  • +
  • -

#10 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2906
  • View blog
  • Posts: 11,328
  • Joined: 03-December 12

Re: Issue uploading an image file

Posted 24 July 2019 - 07:31 AM

You have to declare them as global, and that is just a bad practice anyway, so don't do that. You need to pass what the function needs into it.

Quote

Just saw your try/catch comment. Would it be best to just wrap the query in this?


It should be like this,

// Create a save-to-database function so it's easier and reusable
function SaveToDb($con, $p_name, $p_img) {
    try {

        // Return fail immediately if the connection is false or image is invalid
        if(empty($p_name) || !$con)
            return false;
		$project_sql = "
			INSERT INTO project_gallery
			(p_name, p_img, date_added)
			VALUES(?, ?, NOW())
		";
		if ($project_stmt = $con->prepare($project_sql)) {
			$project_stmt->execute(array($p_name, $p_img));
			return true;
			$proj_succ = "Success";
			echo json_encode($proj_succ);
		}
        return false;
    } catch (PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
	file_put_contents('error_log_new', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
        return false;
    }

    
}

Was This Post Helpful? 1
  • +
  • -

#11 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 556
  • Joined: 30-April 15

Re: Issue uploading an image file

Posted 24 July 2019 - 07:42 AM

Gotcha. Thanks for that.

For defining globally, is this what I would do?

$GLOBALS['p_name'] = trim(htmlspecialchars($_POST['p_name'], ENT_QUOTES));
$GLOBALS['p_alt'] = trim(htmlspecialchars($_POST['p_alt']));

Was This Post Helpful? 0
  • +
  • -

#12 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 556
  • Joined: 30-April 15

Re: Issue uploading an image file

Posted 24 July 2019 - 09:50 AM

I just saw your post showed how to accomplish it. I just tried that way and received some errors.

Error:

Quote

Fatal error: Uncaught ArgumentCountError: Too few arguments to function SaveToDb(), 2 passed in /admin/php/projectSend.php on line 85 and exactly 8 expected in /admin/php/projectSend.php:49 Stack trace: #0 /admin/php/projectSend.php(85): SaveToDb(Object(PDO), '../project_imag...') #1 {main} thrown in /admin/php/projectSend.php on line 49


Do I have to add them here too?

$saveToDb   =   SaveToDb($con,$upload['file']['dest']);



Updated code for that function:

$con = getConfig('pdo');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Create a save-to-database function so it's easier and reusable
	function SaveToDb($con,$filename = false, $p_name, $p_img, $p_alt, $category, $creator, $status) {
		try {
        // Return fail immediately if the connection is false or image is invalid
			if(empty($filename) || !$con)
				return false;
			$project_sql = "
				INSERT INTO project_gallery
				(p_name, p_img, p_alt, category, creator, status, date_added)
				VALUES(?, ?, ?, ?, ?, ?, NOW())
			";
			if ($project_stmt = $con->prepare($project_sql)) {
				$project_stmt->execute(array($p_name, $p_img, $p_alt, $category, $creator, $status));
				return true;
				$proj_succ = "Success";
				echo json_encode($proj_succ);
			}
			return false;
		} catch (PDOException $e) {
			echo "Connection failed: " . $e->getMessage();
			file_put_contents('error_log_new', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
			return false;
		}
	}

Was This Post Helpful? 0
  • +
  • -

#13 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2906
  • View blog
  • Posts: 11,328
  • Joined: 03-December 12

Re: Issue uploading an image file

Posted 24 July 2019 - 09:54 AM

If you change the method signature, you need to update the code that calls that method. Why are you passing $filename in? It doesn't really use it so it is just a waste.
Was This Post Helpful? 1
  • +
  • -

#14 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 556
  • Joined: 30-April 15

Re: Issue uploading an image file

Posted 24 July 2019 - 01:23 PM

Thanks for the help! I got it working.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1