2017-09-01 7 views
0

私はこの機能を書いており、これを使って自分のローカルサーバーに画像を動的にアップロードしています。ifステートメント内で使用される関数の結果を表示して返す方法は?

私はデータベースに挿入できるように、私は$image_nameを返すことができませんuploadImage functionを呼び出すときに、私はそれを返すするかどうかはわかりません、$image_nameがその内部で生成され、次の問題に遭遇しました変数。

public function uploadImage($data, $uploadLocation, $nameTag){ 
    if($data['size'] != 0) { 
     $errors  = array(); 
     $maxsize = 16777216; 
     $acceptable = array(
      'image/jpeg', 
      'image/jpg', 
     ); 
     $image_extension = pathinfo($data['name'], PATHINFO_EXTENSION); 

     //image_name variable I'm referring to 
     $image_name = uniqid($nameTag, true) . '.' . $image_extension; 

     if($data['size'] >= $maxsize) { 
      $errors[] = 'File too large. File must be less than 16 megabytes.'; 
     } else if($data['size'] == 0){ 
      $errors[] = 'You need to upload an image.'; 
     } 

     if((!in_array($data['type'], $acceptable)) || (empty($data['type']))) { 
      $errors[] = 'Invalid file type. Only JPG, GIF and PNG types are accepted.'; 
     } 

     if(count($errors) === 0) { 
      $moveFile = move_uploaded_file($data['tmp_name'], $uploadLocation . '/' . $image_name); 

      if($moveFile){ 
       return true; 
      } 
     } 
    } 

    return false; 
} 

ここでは、uploadImage関数を使用しています。

if($moveFile){ 
    return true; 
} 

は私が本当の代わりに$image_nameを返すこともできますが、私はそれが内側なので、私が使用できるようにそれをキャッチしたいかわからないよ:

$uploadImage = new UploadImages(); 

if($uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_')){ 

    //here I'd like to return the $image_name from the function 
    //I'm using PDO to insert the name in database 
    $sth = $db->prepare('UPDATE instructions SET image = :image WHERE id = :id'); 
    $sth->bindValue(':image', //name returned from the function, PDO::PARAM_STR); 
    $sth->bindValue(':id', $instructionsId, PDO::PARAM_INT); 
    $sth->execute(); 
} 

私はコードの一部であることを考え出しましたifステートメント。

特定のデータをどのように返すことができますか、それらのニーズに合わせてコードを書き直す方法の提案は素晴らしいでしょう。

+1

あなたが言った正確に何をすべきか、 '$ image_name'または' getImageName() 'のようなメソッドを作成し返します。 – Rasclatt

+0

@Rasclattイメージ名を取得するメソッドを作成することに気をつけませんでした。ガイダンスをありがとう。 – Craig

答えて

1

、私は多分これと類似の構造を考えるでしょう:

class UploadImages 
    { 
     # Save all your persisting variables 
     protected $errors = array(); 
     protected $image_name, 
        $success = false; 
     # You may want to make this editable in the future 
     protected $maxsize = 16777216; 
     # You may want to add more mimes later 
     protected $acceptable = array(
         'image/jpeg', 
         'image/jpg', 
       ); 
     # Make a listener 
     public function listen($data, $uploadLocation, $nameTag) 
     { 
      if(!empty($data['size'])) { 
       $image_extension = pathinfo($data['name'], PATHINFO_EXTENSION); 
       # Store the file name 
       $this->image_name = uniqid($nameTag, true) . '.' . $image_extension; 
       # Use the editable variable 
       if($data['size'] >= $this->maxsize) { 
        # Store error 
        $this->errors[] = 'File too large. File must be less than 16 megabytes.'; 
       } 
       # Check editable mime 
       if((!in_array($data['type'], $this->acceptable)) || (empty($data['type']))) { 
        $this->errors[] = 'Invalid file type. Only JPG, GIF and PNG types are accepted.'; 
       } 
       # Store the success 
       if(count($this->errors) === 0) { 
        $this->success = move_uploaded_file($data['tmp_name'], $uploadLocation . '/' . $this->image_name); 
       } 
      } else { 
       $this->errors[] = 'You need to upload an image.'; 
      } 
      # Return the object 
      return $this; 
     } 

     public function getFileName() 
     { 
      return $this->image_name; 
     } 

     public function isUploaded() 
     { 
      return $this->success; 
     } 

     public function getErrors() 
     { 
      return $this->errors; 
     } 

     public function hasErrors() 
     { 
      return (!empty($this->errors)); 
     } 
    } 
# Create the class, since the listen() method returns the object, you can 
# run that right off the top 
$uploadImage = (new UploadImages())->listen($data['image_data'], 'uploads/img/instructions', 'instruction_'); 
# Check if there are errors or if the upload itself failed 
if($uploadImage->hasErrors() || !$uploadImage->isUploaded()) { 
    # Write the error depending on which error occurred 
    echo ($uploadImage->hasErrors())? implode('<br />',$uploadImage->getErrors()) : 'Your upload failed do to an unknown error.'; 
} 
else { 
    # Fetch name on success 
    $img = $uploadImage->getName(); 
    $sth = $db->prepare('UPDATE instructions SET image = ? WHERE id = ?'); 
    $sth->execute(array($img,$instructionsId)); 
} 
1

UploadImagesフィールドに格納し、取得する方法を書き込むことができます。

0

関数から$image_nameを返すことができます。関数がfalse/null or 0値以外を返す場合は、trueという条件で実行されます。

if($moveFile){ 
    return $image_name; //you can add file name here 
} 

アップロード画像機能

//Following condition become true if function return file name and not `false` 
if($image_name = $uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_')){ 
    //You can use filename now 
    //here I'd like to return the $image_name from the function 
    //I'm using PDO to insert the name in database 
    $sth = $db->prepare('UPDATE instructions SET image = :image WHERE id = :id'); 
    $sth->bindValue(':image', //name returned from the function, PDO::PARAM_STR); 
    $sth->bindValue(':id', $instructionsId, PDO::PARAM_INT); 
    $sth->execute(); 
} 
0

あなたがこれを行うことができますいくつかの方法があります。まず、$ image_nameをtrueではなくsuccessに返す必要があります。そして、あなたは第2の方法では

$filename = $uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_'); 
if($filename !== false){ //uploadImage returns false on error 
    ... 

または

if($filename = $uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_')){ 

を行うことができ、単一等しい演算子は、関数呼び出しの結果に$ファイル名を設定し、全体の文も、結果に評価します関数呼び出し。私は読みやすく、理解しやすいので、最初の方法を好む。また、私のコメントへ

関連する問題