Nerede PHP fotoğraf yüklemesi için bazı iyi örnek kod nedir?

1 Cevap php

Kimse fotoğraf yükleme işlemek için nasıl bir iyi, iyi-put-birlikte örnekleme birlikte çeşitli StackOverflow sorular örnek kod tüm bağlı gibi görünüyor. İşte benim başlangıç ​​... bunu geliştirmek yardım lütfen.

İşte Kurulum:

  • Bizim dosya yükleme kontrolü $file, örneğin adlveırılmıştır <input type="file" name="<?= $file ?>" />.
  • Biz $photosPath, mesela fotoğraf kaydetmek istiyorum $photosPath = "/photos/".
  • Biz dosya, $targetFilename . ".jpg" olmak istediğiniz yere mesela $targetFilename bizim yükleme formunda bir username metin alanından olabilir.
  • Biz $filePath, örn edilen dosya yolunu saklamak istiyorum bir veritabanına yerleştirilmesi için.
  • Biz sadece kabul etmek istiyorum. Jpgs.
  • Biz sadece en $maxSize bayt dosyaları kabul etmek istiyorum.

1 Cevap

İşte bu benim atış:

// Given: $file, $targetFilename, $photosPath, $maxSize
$filePath = NULL;
if (array_key_exists($_FILES, $file)
    && $_FILES[$file]['size'] != 0
    && $_FILES[$file]['error'] == UPLOAD_ERR_OK)
{
    if ($_FILES[$file]['size'] > $maxSize)
    {
        throw new Exception("The uploaded photo was too large; the maximum size is $maxSize bytes.");
    }

    $imageData = getimagesize($_FILES[$file]['tmp_name']);
    $extension = image_type_to_extension($imageData[2]);
    if ($extension != ".jpg" && $extension != ".jpeg")
    {
        throw new Exception("Only .jpg photos are allowed.");
    }

    $possibleFilePath = $photosPath . $targetFilename . ".jpg";
    if (!move_uploaded_file($_FILES[$file]['tmp_name'],
                            $_SERVER['DOCUMENT_ROOT'] . $possibleFilePath)
    {
        throw new Exception("Could not save the uploaded photo to the server.");
    }

    $filePath = $possibleFilePath;
}