Jump to content

Error in transferring uploads from Temporary folder to specified folders


genzedu777

Recommended Posts

Hi,

 

Could anyone please help me to look at my code? I have been figuring out the past 1 week and I still do not understand what has happened.

 

Currently I am trying to code a registration form, which allows user to upload their photo. My understanding is that I have to transfer files which are stored in Temporary Folder to the folder which I specified. Hence I used define('GW_UPLOADPATH', 'uploads/');, and specified it to be redirected to 'uploads' folder. I have tried to test run it. and I realised the code which I have bold in red, is giving me problems.

 

Whenever I have tried to submit my form, my 'else' statement will appear 'Sorry, there is a problem in uploading your screen shot image'.

 

I have looked into my define('GW_UPLOADPATH', 'uploads/'), I have created a 'uploads' folder in my root path, and there should not be any problem. I'm seriously clueless of what has happened.

You may test it out at www.dress-a-holic.com/addscore.php.

 

Really appreciate if anyone could reply to my post. Thank you so much

 

<?php

define('GW_UPLOADPATH', 'uploads/');

require_once ('connectvars.php');

 

 

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

    // Grab the score data from the POST

    $name = $_POST['name'];

    $score = $_POST['score'];

$screenshot = $_FILES ['screenshot']['name'];

 

 

    if (!empty($name) && !empty($score) && !empty($screenshot)) {

 

//Move the file to the target upload folder

$target = GW_UPLOADPATH . time() . $screenshot;

if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) {

 

// Connect to the database

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)

or die ('Error in connecting to MySQL server');

 

// Write the data to the database

$query = "INSERT INTO guitar_list VALUES (0, NOW(), '$name', '$score', '$screenshot')";

     

mysqli_query($dbc, $query)

or die ('Error in querying');

 

// Confirm success with the user

echo '<p>Thanks for adding your new high score!</p>';

echo '<p><strong>Name:</strong> ' . $name . '<br />';

echo '<strong>Score:</strong> ' . $score . '<br />';

echo '<img src= "' . GW_UPLOADPATH . $screenshot . '" alt="Score Image" /></p>';

echo '<p><a href="index.php">Back to high scores</a></p>';

 

// Clear the score data to clear the form

$name = "";

$score = "";

$screenshot = "";

 

mysqli_close($dbc);

 

 

 

}else {

echo '<p class="error">Sorry, there is a problem in uploading your screen shot image</p>';

}

 

 

 

 

}else {

      echo '<p class="error">Please enter all of the information to add your high score.</p>';

    }

  }

?>

 

  <hr />

  <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

  <input type = "hidden" name = "MAX_FILE_SIZE" value = "<?php echo GW_MAXFILESIZE; ?>" />

    <label for="name">Name:</label>

    <input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />

    <label for="score">Score:</label>

    <input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" /><br />

<label for="screenshot">Screen Shot:</label>

<input type="file" id="screenshot" name="screenshot">

    <hr />

    <input type="submit" value="Add" name="submit" />

  </form>

</body>

</html>

Link to comment
Share on other sites

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

 

I believe there is a permission issue in the directory you are trying to move to.  If uploaded can be set with "chmod -R a=+w uploads" I'd try that.

Link to comment
Share on other sites

Hi Andrewgauger,

 

Really appreciate your reply. However as I am new in php programming, the "chmod -R a=+w uploads" looks alien to me.

 

What is chmod - R?

 

I understand a=+w is a = a + w, but what is the 'a' and 'w' for?

 

Please kindly advise.

 

Thank you

Link to comment
Share on other sites

Find out why the move_uploaded_file() statement is failing by getting php to display all the errors it detects. Add the following two lines of code immediately after the first opening <?php tag -

 

ini_set("display_errors", "1");
error_reporting(E_ALL);

Link to comment
Share on other sites

Hi PFMaBiSmAd,

 

Those 2 commands are really useful. Thank you so much. However I may need your help again

 

 

Warning: move_uploaded_file(images/1271172840belitasscore.gif) [function.move-uploaded-file]: failed to open stream: Permission denied in /var/www/vhosts/dress-a-holic.com/httpdocs/addscore.php on line 33

 

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpVfXuB5' to 'images/1271172840belitasscore.gif' in /var/www/vhosts/dress-a-holic.com/httpdocs/addscore.php on line 33

 

These are the errors. I am confused. I have clearly created a folder called 'images' in the same directory as all my .php files, however why is a 'Permission Denied'?

 

PFMaBiSmAd - Could you help me out?

 

andrewgauger - Anyway thanks for your help, greatly appreciated.

 

Thanks,

Wilson

Link to comment
Share on other sites

As for the

 

define('GW_UPLOADPATH', 'uploads/');

 

I have just changed it to

define('GW_UPLOADPATH', 'images/');

 

So please don't get confused. It is not the folder's name, cause I have just changed from 'uploads' to 'images' and I am still facing the Permission Denied error. How do I solve it?

 

Thanks

Link to comment
Share on other sites

Hi,

I had a similar problem and happened that I did not have the correct directort selected. You can use the realpath() function to help you:

 

http://www.php.net/manual/en/function.realpath.php

 

echo the directories you are using and you'll see

 

You can try this code as well to echo all information:

 

<?php 

$myDir = '../../dir/targetDir/'; 

if(chmod(realpath($myDir), 0777)) { echo 'Successfully changed dir to 0777 permissions!'; } 

echo '<br />Safe Mode is: ' . ini_get('safe_mode'); 

echo '<br />'; 

clearstatcache(); 
echo 'Permissions: ' . substr(sprintf('%o', fileperms('/tmp')), -4); 

echo '<br />'; 

if(chmod(realpath($myDir), 0755)) { echo 'Successfully changed dir to 0755 permissions!'; } 

echo '<br />'; 

clearstatcache(); 
echo 'Permissions: ' . substr(sprintf('%o', fileperms('/tmp')), -4); 
?> 

 

Peace

 

JP

 

Link to comment
Share on other sites

Hi andrewgauger

 

After putting...chmod(GW_UPLOADPATH, 0666); below my code, i am getting some error again. Do you think you can help? I still dont understand what went wrong, as I have already created a folder in the correct directory.

 

Why does the error msg states, 'no such directory'?

 

<?php

 

ini_set("display_errors", "1");

error_reporting(E_ALL);

chmod(GW_UPLOADPATH, 0666);

 

  define('GW_UPLOADPATH', 'images/');

  require_once ('connectvars.php');

 

 

Notice: Use of undefined constant GW_UPLOADPATH - assumed 'GW_UPLOADPATH' in /var/www/vhosts/dress-a-holic.com/httpdocs/addscore.php on line 15

 

Warning: chmod() [function.chmod]: No such file or directory in /var/www/vhosts/dress-a-holic.com/httpdocs/addscore.php on line 15

 

Thanks,

Wilson

Link to comment
Share on other sites

Hi Andrew,

 

Thank you so much for your reply, I have followed your instruction and done as followed. I have removed all my code and added only the 3 lines which you have told me.

 

But I am still getting this error...do you know what exactly happened?

 

Is there other methods in coding to upload pictures and store it into our database directory? Thanks

 

Guitar Wars - Add Your High Score

Warning: chmod() [function.chmod]: Operation not permitted in /var/www/vhosts/dress-a-holic.com/httpdocs/addscore(today).php on line 15

 

 

 

<!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" xml:lang="en" lang="en">

<head>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

  <title>Guitar Wars - Add Your High Score</title>

  <link rel="stylesheet" type="text/css" href="style.css" />

</head>

<body>

  <h2>Guitar Wars - Add Your High Score</h2>

 

<?php

 

ini_set("display_errors", "1");

error_reporting(E_ALL);

chmod('images/', 0666);

 

?>

 

</body>

</html>

Link to comment
Share on other sites

Your host is not permitting you to modify using chmod in php.  What you might be able to do is modify the permissions of the folder on the administrative website the host provides.  I have attached a picture of how to do it on one of my hosts using control panel. 

 

[attachment deleted by admin]

Link to comment
Share on other sites

Hi Andrew,

 

I got it!!! Thanks, I actually allowed all access under my 'images' folder and it works....really appreciate your kind efforts...

 

Last qns, I'm actually picking up php language on my own now, and the coding which I am showing is written by the author.

 

The codes work perfectly fine, but i have a question.

Those which I have highlighted in Blue, what I do not understand is that, why did the author name it as 'image/jpeg' and not 'images/' since I have assigned all my uploads to 'images/' folder? It doesn't really make sense to me, do you have any advise?

 

Thanks,

Wilson

 

 

<?php

  require_once('appvars.php');

  require_once('connectvars.php');

 

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

    // Grab the score data from the POST

    $name = $_POST['name'];

    $score = $_POST['score'];

    $screenshot = $_FILES['screenshot']['name'];

    $screenshot_type = $_FILES['screenshot']['type'];

    $screenshot_size = $_FILES['screenshot']['size'];

 

if (!empty($name) && !empty($score) && !empty($screenshot)) {

      if ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/pjpeg') || ($screenshot_type == 'image/png'))

        && ($screenshot_size > 0) && ($screenshot_size <= GW_MAXFILESIZE)) {

        if ($_FILES['screenshot']['error'] == 0) {

          // Move the file to the target upload folder

          $target = GW_UPLOADPATH . $screenshot;

          if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) {

            // Connect to the database

            $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

 

            // Write the data to the database

            $query = "INSERT INTO guitarwars VALUES (0, NOW(), '$name', '$score', '$screenshot')";

            mysqli_query($dbc, $query);

 

            // Confirm success with the user

            echo '<p>Thanks for adding your new high score! It will be reviewed and added to the high score list as soon as possible.</p>';

            echo '<p><strong>Name:</strong> ' . $name . '<br />';

            echo '<strong>Score:</strong> ' . $score . '<br />';

            echo '<img src="' . GW_UPLOADPATH . $screenshot . '" alt="Score image" /></p>';

            echo '<p><a href="index.php"><< Back to high scores</a></p>';

 

            // Clear the score data to clear the form

            $name = "";

            $score = "";

            $screenshot = "";

 

            mysqli_close($dbc);

          }

          else {

            echo '<p class="error">Sorry, there was a problem uploading your screen shot image.</p>';

          }

        }

      }

      else {

        echo '<p class="error">The screen shot must be a GIF, JPEG, or PNG image file no greater than ' . (GW_MAXFILESIZE / 1024) . ' KB in size.</p>';

      }

 

      // Try to delete the temporary screen shot image file

      @unlink($_FILES['screenshot']['tmp_name']);

    }

    else {

      echo '<p class="error">Please enter all of the information to add your high score.</p>';

    }

  }

?>

 

  <hr />

  <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo GW_MAXFILESIZE; ?>" />

    <label for="name">Name:</label>

    <input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />

    <label for="score">Score:</label>

    <input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" /><br />

    <label for="screenshot">Screen shot:</label>

    <input type="file" id="screenshot" name="screenshot" />

    <hr />

    <input type="submit" value="Add" name="submit" />

  </form>

</body>

</html>

 

 

[attachment deleted by admin]

Link to comment
Share on other sites

I actually allowed all access under my 'images' folder and it works

 

Great, just don't enable execute because someone might upload something malicious and execute it.  Read+Write=perfect.

 

if ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/pjpeg') || ($screenshot_type == 'image/png'))

is testing if the uploaded file is a gif, jpeg, or png.  see the "_type =="  that is implying that it is testing the type of image.  Always thinking, I like that.  Don't modify the code, it needs to be "image/type"

Link to comment
Share on other sites

Icic..thank you so much,

 

by the way, i need to check the checkboxes of 'execute' as well, tried unchecking it, but I could not upload my photos.

 

Lastly, as you understand, usually user's uploads may have the same file name as others, like jean.jpg, and along the way, there might be another jean.jpg upload. To prevent this from happening, I added 'time ()' function in front of each uploaded file name.

 

Example jean.jpg will become 1234335jean.jpg, even if there is another same filename upload, the file name will be different because of the time() function.

 

But the problem I am facing now is, even though 1234335jean.jpg is in my 'images' folder, under www.dress-a-holic.com/index.php, the image is not showing.

 

Then I tried removing 'time()' from

$target = GW_UPLOADPATH  . $screenshot; 

The image appears in index. I am confused,  I believe it was my 'time()' that caused the image not to show up, but why is it so?

 

Do you have any other methods to advise, so that similar file name will not overwrite each other? Thank you.

 

if (!empty($name) && !empty($score) && !empty($screenshot)) {

      if ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/pjpeg') || ($screenshot_type == 'image/png'))

        && ($screenshot_size > 0) && ($screenshot_size <= GW_MAXFILESIZE)) {

        if ($_FILES['screenshot']['error'] == 0) {

          // Move the file to the target upload folder

          $target = GW_UPLOADPATH . time() . $screenshot;

          if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) {

Link to comment
Share on other sites

well, time() is always changing.

 

So when you uploaded the image time()=12345

but when you go to look up the picture time()= 12357

 

so when you look for 12357jean.jpg, it doesn't exist.

 

Make sure you append time() when you upload it, but don't include it when you reference it.

Link to comment
Share on other sites

  • 2 weeks later...

Hi Andrew,

 

Really appreciate the useful tips which you have given me. Truly appreciate it.

 

However could you briefly elaborate what do you mean by append the time?

 

So what should I do with the coding?

$target = GW_UPLOADPATH .time() . $screenshot;

 

Lastly, I have a question regarding SQL.

I have created a database, and occasionally I will delete records from the table, and I realised the ID number, which I have set as auto-incremental is no longer in sequence.

 

For example, I have

ID

1

2

3

4

5

 

and I decided to delete record 3, and it will become

ID

1

2

4

5

6

 

How can I rectify this problem? Is there a way when I delete the record, the rest of the following records will auto rearrange their ID numbers to be in sequence?

 

Appreciate your time in reading this thread. Thank you

 

Wilson

 

[attachment deleted by admin]

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.