Unknown wrong behavior in PHP IF statement

114 views Asked by At

I'm writing a code to upload a file in PHP. But there is an unknown and strange problem in it's IF statement. It does operations in both true and false condition! Look at the code below please:

if (is_uploaded_file($_FILES['catalogue']['tmp_name']))
{
    $ext = find_extension('catalogue');
    $ext_array = array('pdf');

    if (!in_array($ext,$ext_array))
    {
        // echo something for error message.
    }
    else
    {
        echo ' Step1 ';
        @unlink ('../../catalogues/'.$id.'.pdf');
        if(@move_uploaded_file($_FILES['catalogue']['tmp_name'],"../../catalogues/".$id.'.pdf'))
        {
            @chmod ("../../catalogues/".$id.".pdf",'644');
            $sql = "UPDATE tbl_products SET catalogue = ? WHERE id = ?";
            $q = $db->prepare($sql);
            $query = $q->execute(array($id.'.pdf',$id));
        }
    }
}
else
{
    echo ' Step2 ';
    @unlink ('../../catalogues/'.$id.'.pdf');
    $sql = "UPDATE tbl_products SET catalogue = ? WHERE id = ?";
    $q = $db->prepare($sql);
    $query = $q->execute(array('',$id));
}

And the result is Step1 Step2 !
So when the file is uploaded successfully, new file will be uploaded and set to database, and then it will removed in step2 and its field in database will be empty. :(
This is very strange for me. Please help me.

Note: find_extension() function and $id are defined before these lines of code.

1

There are 1 answers

2
SDZ On

Try this:

if (is_uploaded_file($_FILES['catalogue']['tmp_name']))
{
    $ext = find_extension('catalogue');
    $ext_array = array('pdf');

    if (!in_array($ext,$ext_array))
    {
        // echo something for error message.
    }
    else
    {
        echo ' Step1 ';
        @unlink ('../../catalogues/'.$id.'.pdf');
        if(@move_uploaded_file($_FILES['catalogue']['tmp_name'],"../../catalogues/".$id.'.pdf'))
        {
            @chmod ("../../catalogues/".$id.".pdf",'644');
            $sql = "UPDATE tbl_products SET catalogue = ? WHERE id = ?";
            $q = $db->prepare($sql);
            $query = $q->execute(array($id.'.pdf',$id));
     }
}
else
{
    echo ' Step2 ';
    @unlink ('../../catalogues/'.$id.'.pdf');
    $sql = "UPDATE tbl_products SET catalogue = ? WHERE id = ?";
    $q = $db->prepare($sql);
    $query = $q->execute(array('',$id));
}

    }