0

How to add image upload to this code? Here's the code where you write a news. I would like to add image upload to this code, so I could write a news with a picture. It prints only the text now.

<?php
        if ( !isset($database_link))
        {
            die(header('location: index.php?page=news'));
        }
        if ( !isset($_GET['category_id']))
        {
            die(header('location: index.php?page=news'));
        }
        $category_id = ($_GET['category_id'] * 1);



        $news_title = '';
        $news_content = '';
        $user_id = $_SESSION['user']['user_id'];


        if (isset($_POST['news_submit']))
        {
            $form_ok = true;

            $news_title = mysqli_real_escape_string($database_link, $_POST['news_title']);
            $news_content = mysqli_real_escape_string($database_link, $_POST['news_content']);




            if ($news_title == '')
            {
                $form_ok = false;
                echo '<p class="alert alert-error">Please complete</p>';
            }
            if ($news_content == '')
            {
                $form_ok = false;
                echo '<p class="alert alert-error">Please complete</p>';
            }


                    if ($form_ok) 

            {
                $query = "
                    INSERT INTO news 
                        (news_title, news_content, news_postdate, fk_users_id, fk_categories_id) 
                    VALUES 
                        ('$news_title','$news_content', NOW(), '$user_id', '$category_id')";
                $result = mysqli_query($database_link, $query) or if_sql_error_then_die(mysqli_error($database_link), $query);

                if ($result)
                {
                    generateRss($category_id);
                    die(header('location: index.php?page=news&category_id='.$category_id));
                }
            }
        }
    ?>

    <div class="col-lg-12">
      <form method="post" role="form">
        <div class="form-group">
          <label for="news_title">News Titel</label>
          <input type="text" class="form-control" name="news_title" id="news_title" placeholder="Nyheds Titel" value="<?php echo $news_title; ?>" maxlength="64" required>
        </div>
        <div class="form-group ">
          <label for="news_content">News text</label>
          <textarea class="form-control" id="editor1" name="news_content" placeholder="Nyheds Tekst" rows="10" cols="80" required>

                </textarea>
          <script>

                    CKEDITOR.replace( 'editor1' );
                </script> 
        </div>
        <div class="form-group">
          <label for="category_id">News</label>
          <select class="form-control-select" name="category_id" id="category_id">
            <option value="0">Choose News</option>
            <?php
                        $query = "SELECT category_id, category_title FROM categories ORDER BY category_title ASC";
                        $result = mysqli_query($database_link, $query) or if_sql_error_then_die(mysqli_error($database_link), $query);
                        if (mysqli_num_rows($result) > 0)
                        {
                            while ($row = mysqli_fetch_assoc($result))
                            {
                                $selected = ($category_id == $row['category_id'] ? ' selected="selected"' : '');
                                echo '<option value="'.$row['fk_categories_id'].'"'.$selected.'>'.$row['category_title'].'</option>';
                            }
                        }
                    ?>
          </select>
        </div>
        <input type="submit" class="btn-send" style="background-color:#D67400; border-color:#D67400;" name="news_submit" value="Gem" />
        <a href="index.php?page=news&amp;category_id=<?php echo $category_id; ?>" class="btn btn-default" onclick="return confirm('Are you sure you want to cancel?')">Annuller</a>
      </form>
    </div>

Here is the code where it gets from database and then prints the images on this. It only prints text without pictures as you can see.

 <?php
    if ( !isset($database_link))
    {
        die(header('location: index.php'));
    }

    > $query = "  SELECT news_id, news_title, news_content, news_postdate,
    > category_id, category_title, user_name 
    >               FROM news
    >               INNER JOIN categories ON categories.category_id = news.fk_categories_id
    >               INNER JOIN users ON users.user_id = news.fk_users_id
    >               ORDER BY news_postdate DESC
    >               LIMIT 10";
    >     $result = mysqli_query($database_link, $query) or if_sql_error_then_die(mysqli_error($database_link), $query);
    >     if (mysqli_num_rows($result) <= 0)
    >     {

        echo '  <p class="alert alert-info">emty...</p>';
    }
    else
    {

        while ($row = mysqli_fetch_assoc($result))
        {
            $news_id = $row['news_id'];
            $news_title = $row['news_title'];
            $news_content = substr(strip_tags($row['news_content']), 0, 200).'...';
            $news_postdate = strftime('%A d. %d. %B %Y  %H:%M', strtotime($row['news_postdate']));
            $user_name = $row['user_name'];
            $category_id = $row['category_id'];
            $category_title = $row['category_title'];
            echo '
                    <section class="news_category">
                        <h1>'.$news_title.'</h1>
                        <p1>  '.$news_postdate.' </p1>
                        <p><a href="index.php?page=news&amp;category_id='.$category_id.'&amp;news_id='.$news_id.'">'.$news_content.'</a></p>
                        <em> '.$user_name.', in category: '.$category_title.'</em><hr />
                    </section>';
                    echo '<div class="spacer"> </div>';
        }
    }
2

2 Answers 2

1

The website W3Schools has a nice tutorial about it. It even shows the code. Now for not making this a just link answer:

Form example:

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

The upload script:

<?php
if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  echo "Type: " . $_FILES["file"]["type"] . "<br>";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
?>

Saving the file:

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

@andrew Though this example is great. My teacher told me w3schools is bad as well but this one worked good for me.
0

you'll need to add enctype="multipart/form-data" attribute to your form to be able to upload files, and add a <input type="file" name="file"/> input

you can retrieve the uploaded files server side using the $_FILES variable

Here is some more useful info on handling uploaded files

EDIT:

Here is a very basic example which does not perform any error checking etc.

<?php 
   if ($_SERVER['REQUEST_METHOD'] == 'POST') {
       move_uploaded_file($_FILES['file']['tmp_name'], realpath('../yourFilePath'));
   }
?>


<form  method="post" enctype="multipart/form-data">
  <input type="file" name="file"/>
  <input type="text" name="anotherInput">
</form>

1 Comment

Can you tell me how exactly?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.