简体   繁体   中英

Trying to upload files to the server with PHP but it's always converted as .jpg format

i'm trying to make an upload files function which allowing users to upload images, videos, and compressed files (.rar) and auto renamed the file in case to prevent files uploaded with the same name and replacing each others.

But when i'm trying to upload it one by one, everything uploaded is converted to .jpg format.

Can someone help me please ?

This is my script :

function reArrayFiles(&$file_post) {

$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);

for ($i=0; $i<$file_count; $i++) {
    foreach ($file_keys as $key) {
        $file_ary[$i][$key] = $file_post[$key][$i];
    }
}

return $file_ary;
}


if ($_FILES['upload']) {
    $file_ary = reArrayFiles($_FILES['upload']);

foreach ($file_ary as $file) {
  echo "<p>";
    print 'File Name: ' . $file['name'] . '<br />';
    print 'File Type: ' . $file['type'] . '<br />';
    print 'File Size: ' . $file['size'] . '<br />';
    print 'File Temp: ' . $file['tmp_name'] . '<br />';
  echo "</p>";

  if ($file['type'] == 'jpg' || 'jpeg') {
    $newname = date('YmdHis',time()).mt_rand().'.jpg';
    $dir = 'upload/images/'.$newname;
    move_uploaded_file($file['tmp_name'], $dir);
  }

  if ($file['type'] == 'mp4') {
    $newname_video = date('YmHis',time()).mt_rand().'.mp4';
    $dir2          = 'upload/videos/'. $newname_video;
    move_uploaded_file($file['tmp_name'], $dir2);
  }

  if ($file['type'] == 'rar') {
    $newname_other = date('YmHis',time()).mt_rand().'.rar';
    $dir3          = 'upload/others/'. $newname_other;
    move_uploaded_file($file['tmp_name'], $dir3);
  }
}
}

if ($file['type'] == 'jpg' || 'jpeg') {

is evaluated as if it were:

if (($file['type'] == 'jpg') || ('jpeg')) {

and a non-empty string evaluates to true so this if always passes.

Change it to:

if (($file['type'] == 'jpg') || ($file['type'] == 'jpeg')) {

and it should work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM