Image is being uploaded without extension

Asked

Viewed 48 times

0

I put a PHP code to upload images, the images are not being saved in the directory with the code below:

$post_id = $db->insert($query);
$ext = explode('.', $_FILES['img']['name']);
$path = "../content/img/".$post_id.".".$ext[count($ext)]-1;

$img = move_uploaded_file( $_FILES["img"]["tmp_name"], $path);

var_dump $path int -1

$ext

     array (size=2)
  0 => string 'nome-da-imagem' (length=14)
  1 => string 'jpg' (length=3)
(Já que é uma imagem jpg)

var_dump $img boolean true

But when I change the $path variable to only $path = "../content/img/".$post_id; var_dump gives string '../content/img/60' (length=17)

There saves (60 because it is the ID of this new post), but without the extension.

  • You have already tried using $ext[1] since it returns an array. Pq by var_dump it returns two positions 0 and 1 to regain some position you need to use $ext[0] or $ext[1].

  • The -1 you are using needs to stay inside the Dice and not outside $path = ".. /content/img/". $post_id.".". $ext[Count($ext)-1];

  • Both ways worked out!!

  • If it worked consider the answer I put below

  • One suggestion is to protect the upload pq vc by opening an access to the server and then if someone goes up a php script they already know :( . make restrictions with the extension type, size, encryption with sha1 or whatever you choose etc.

  • At the moment I’m creating the features, I really need to make these restrictions, thanks for the touch.

  • @Geovanic, there is better alternative to explode, use the function pathinfo

Show 2 more comments

1 answer

0


Try to use it like this:

$path = "../content/img/".$post_id.".".$ext[count($ext)-1]; # o -1 dentro do índice assim ele diminui com o count da variável.

Or:

$path = "../content/img/".$post_id.".".$ext[1];
  • It worked, the image is being saved with the correct extension now. :)

  • Vote on the question to help others :) and evaluate as correct :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.