-1

I am trying to move an existing image file from a temp folder to a proper location with a proper filename, for some reason it always fails.

function move_temp_image($article_id)
{
    global $db, $config;

    if (($image_load = !@fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.jpg", 'r+')) && ($image_load = !@fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.png", 'r+')) && ($image_load = !@fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.gif", 'r+')))
    {
        $this->error_message = "Could not find temp image to load?";
        return false;
    }

    else
    {
        $image_info = getimagesize($image_load);
        $image_type = $image_info[2];
        $file_ext = '';
        if( $image_type == IMAGETYPE_JPEG ) 
        {
            $file_ext = 'jpg';
        } 

        else if( $image_type == IMAGETYPE_GIF )
        {
            $file_ext = 'gif';
        } 

        else if( $image_type == IMAGETYPE_PNG )
        {
            $file_ext = 'png';
        }

        // give the image a random file name
        $imagename = rand() . 'id' . $article_id . 'gol.' . $file_ext;

        // the actual image
        $source = $image_load;

        // where to upload to
        $target = $_SERVER['DOCUMENT_ROOT'] . "/uploads/articles/topimages/" . $imagename;  

        if (rename($source, $target))
        {           
            // remove old temp image
            if ($image['article_top_image'] == 1)
            {
                unlink($_SERVER['DOCUMENT_ROOT'] . '/uploads/temp/' . $image_load);
            }

            unset($_SESSION['temp_tagline']);

            $db->sqlquery("UPDATE `articles` SET `article_top_image` = 1, `article_top_image_filename` = ? WHERE `article_id` = ?", array($imagename, $article_id));
            return true;
        }

        else
        {
            $this->error_message = 'Could not move temp file to tagline uploads folder!';
            return false;
        }
    }
}

I am not sure what I am doing wrong, I read rename is the way to do this, but I am obviously overlooking something.

NaughtySquid
  • 1,947
  • 3
  • 29
  • 44

1 Answers1

1

You don't have the filename in $source - In your code, $source contains a file resource...

rename doesn't work only with file names, so you have to change your code.

i.e. replace your condition with the following code

$types = array('jpg', 'png', 'gif');
$file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.";
$image_load = false;
foreach ($types as $type) {
    if (file_exists($file . $type)) {
        $image_load = $file . $type;
        break;
    }
}

if (!file_exists($image_load))
Philipp
  • 15,377
  • 4
  • 35
  • 52