简体   繁体   中英

php single vs. double quotes $_FILES

I am new to php, taking my first course now. I cannot, for the life of me, figure out why only $screenshot = $_FILES["screenshot"]["name"] needs double quotes. I originally had single quotes and it wasn't working. I randomly decided to try double quotes and it started working... can somebody tell me why?

<?php
  // Define the upload path and maximum file size constants
  define('GW_UPLOADPATH', 'images/');

  if (isset($_POST['submit'])) {
    // Grab the score data from the POST
    $name = $_POST['name'];
    $score = $_POST['score'];
    $screenshot = $_FILES["screenshot"]["name"];

    if (!empty($name) && !empty($score)) {
      // Move the file to the targe upload folder
      $target = GW_UPLOADPATH . $screenshot;
      // Connect to the database
      $dbc = mysqli_connect('localhost', 'root', 'Bandito8', 'gwdb')
        or die('Unable to connect to databse');

      // Write the data to the database
      $query = "INSERT INTO guitarwars VALUES (0, NOW(), '$name', '$score', '$screenshot')";
      mysqli_query($dbc, $query)
        or die('Unable to complete query');

      // Confirm success with the user
      echo '<p>Thanks for adding your new high score!</p>';
      echo '<p><strong>Name:</strong> ' . $name . '<br>';
      echo '<strong>Score:</strong> ' . $score . '</p>';
      echo '<img src="' . GW_UPLOADPATH . $screenshot . '" alt="Score image"></p>';
      echo '<p><a href="index.php">&lt;&lt; Back to high scores</a></p>';

      // Clear the score data to clear the form
      $name = "";
      $score = "";
      $screenshot = "";

      mysqli_close($dbc);
    }
    else {
      echo '<p class="error">Please enter all of the information to add your high score.</p>';
    }
  }
?>

The php parser try to interpret string in double quotes as variable while string in single quotes are interpreted as literally string...

the php interpret is searching for variable and takes more php time since it doesn't find any variable...

echo $_FILES["upload"]["size"];

the php interpret is searching for string and takes less php time since it hasn't to find any variable...

echo $_FILES['upload']['size'];

Another example:

this example treats $hidden as variable and works fine...

echo "the red fox was $hidden to the hunter";

this example treats $hidden as string and cannot works as expected...

echo 'the red fox was $hidden to the hunter';

Hope this helps!

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