0

I'm quite new to PHP and trying to upload an image to the server and then write it to the database using a form and php using the code and form below but it doesnt seem to be working for, if I take all of the photo content out the form works perfectly well with the other variables and content such as writing the out the article title and content, would anyone be able to tell me where I'm going wrong at all? thanks in advance guys.

<?php

session_start();

include_once('../php/connection.php');

if (isset($_SESSION['logged_in'])) {
    if (isset($_POST['title'], $_POST['content'], $_FILES['photo1'])) {
        $title = $_POST['title'];
        $content = nl2br($_POST ['content']);
        $photo1=($_FILES['photo1']);
        $target = "../lifestlye";
        $target = $target . basename( $_FILES['photo1']);


        $query =$pdo->prepare('INSERT INTO article (article_title, article_content, photo_1) VALUES (?,?,?)');

        $query->bindValue(1, $title);
        $query->bindValue(2, $content);
        $query->bindValue(3, $photo1);

        $query->execute();
        move_uploaded_file($_FILES['photo1'], $target);
{

}


        header('Location: index.php');
    }

    ?>




 <form action="add.php" method="post" autocomplete="off"/>


    <dl class="field four columns centered">
                    <dd><label for="title">Article Title</label></dd>
                    <dt class="text"><input type="text" name="title" id="title"/>
                    </dt>
                    </dl>
                    <dl class="field nine columns centered">
                <dd><label for="content">Content</label></dd>
                <dt class="textarea">
                <textarea name="content" id="message"></textarea></dt>
                </dl>
                <p class="blacktext">Photo</p>
                <input type="file" name="photo1">
                <input type="submit" id="add article"/>
                </form>
tezzataz
  • 137
  • 1
  • 1
  • 10
  • possible duplicate of [Upload Image to Server using PHP. Store file name in a MYSQL database, with other profile info](http://stackoverflow.com/questions/450876/upload-image-to-server-using-php-store-file-name-in-a-mysql-database-with-othe) – Rachel Gallen May 12 '13 at 16:05
  • Refer to this: http://stackoverflow.com/a/16499251/1846562 – mpyw May 12 '13 at 16:21

3 Answers3

1

Try this code:

<?php

session_start();

include_once('../php/connection.php');

if (isset($_SESSION['logged_in'])) {

    if (isset($_POST['title'], $_POST['content'], $_FILES['photo1'])) {

        $title    = $_POST['title'];
        $content  = nl2br($_POST['content']);
        $name     = $_FILES['photo1']['name'];
        $tmp_name = $_FILES['photo1']['tmp_name'];

        $target = '../lifestlye/'.$name;

        if (move_uploaded_file($tmp_name,$target)) {

            $stmt = $pdo->prepare('INSERT INTO article (article_title, article_content, photo_1) VALUES (?,?,?)');
            $stmt->execute(array($title,$content,$name));
            header('Location: index.php');
            exit();

        }

    }

}
mpyw
  • 5,526
  • 4
  • 30
  • 36
  • works perfectly apart from when it tries to put it on the server I get this error, is because I'm not defining the directory properly? Warning: move_uploaded_file(../lifestlye/Shop.png) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/content/55/10880055/html/admin/add.php on line 19 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php7JHFaJ' to '../lifestlye/Shop.png' in /home/content/55/10880055/html/admin/add.php on line 19 – tezzataz May 12 '13 at 17:03
  • Umm, `../lifestyle/` means `./lifestyle/`? Or this directory's permission is not **777**? – mpyw May 12 '13 at 17:18
  • spelling error sorry! thank you so much it works great now. One final question, if I wanted to upload multiple files e.g photo2 I could just make another $name and $tmp_name and add it to move _upload couldnt I? e.g. (move_upload_file($tmp_name,$tmp_name2,$target)? – tezzataz May 12 '13 at 17:35
  • No. It is enough that you receive files as array. Example: ``. Please refer to this: http://stackoverflow.com/a/16499251/1846562 – mpyw May 12 '13 at 17:43
0

You are making it way too simple. You need to read the manual page: http://www.php.net/manual/en/features.file-upload.post-method.php

First, add this to your form as parameter: enctype="multipart/form-data"

Then, understand that $_FILES['photo1'] will be an array, and $_FILES['photo1']['tmp_name'] will contain a temporary filename, which is the uploaded file. You can then move the file to a new location, or read it and put it into the database as a BLOB (but why do you want to keep binary data in a database?)

Palantir
  • 23,820
  • 10
  • 76
  • 86
0
  1. You should use absolute paths for moving the file. If you want to do something in the current dir, use __DIR__ or dirname(__FILE__) depending on your php version. The first one is to preferred if it's available.
  2. You should do error checking - read up on $_FILES array on php.net manual for what to look out for.
  3. Check the return value of move_uploaded_file, errors, notices - there might also be a problem with writing permissions (the target directory/file has to be writable by the webserver)
  4. You should consider generating a filename, otherwise if 2 ppl upload a file with the same name, the second one will override the first one. Then starts the fun about race conditions and the impossibility of php itself to do an atomic lock (using mysql get lock is the best I've come up so far, as semaphores and file locking suck in a web context with php)
  5. You should add some security checking, e.g. str_replace("\0", "", $filename) for avoding nul poisoning (and depending on your system and filesystem there are probably other things you should filter/check)
  6. This is just a tip, but really: Don't do anything with user input, especially file upload, in the open (e.g. publicly available web address) if you haven't got enough experience in regards to php/security. Otherwise you will see your server crashed, taken over, ... in a very short time. PHP is already very insecure as it is, adding in mysql and file upload doesn't really make it better. There is no guarantuee that the filename you get from $_FILES is safe - an attacker could send ANY filename (i can easily do with a few lines of script myself, and I'm not a real hacker).

Also, basename does not filter filenames, it just gives you whatever is before the last '.'.

Edit: + everything Palantir wrote, to make it work (sorry, there were so many things on this that I skipped some)

griffin
  • 1,261
  • 8
  • 24
  • @palantir thanks guys, basically this is for a cms i've made up for a blog and the file upload is basically for uploading pictures for a slideshow plugin at the top of the page. The reason why I want to write the data to the database after uploading is so that I can use the generated filename to dynamically input it into the slideshow e.g. – tezzataz May 12 '13 at 16:22
  • It's totally okay/standard, but as I've been building a new cms on php+mysql myself over the past 2 years, I can only emphasize how important it is in this context to: 1. read up on security (nul byte poisoning, utf8, ...) 2. read up on race conditions (e.g. so you don't have 2 files ending up as one) 3. NEVER trust ANY user input (even better: never trust ANY kind of input), and thus always validate, sanitize, filter, ... – griffin May 12 '13 at 16:26
  • This thing doesn't like alt+enter it seems ;) Anyway, you should also make sure that wherever you upload the files to, there is no chance that 1. you overwrite an existing file (I could pass '../index.php' as filename for example, and you would just append that!) 2. the uploaded files aren't directly accessible or at least the server won't execute them (think about uploading some backdoor.php file, and afterwards opening /whatever-upload-dir/backdoor.php in my browser) – griffin May 12 '13 at 16:28
  • thanks griffin, I'm reading up quite a bit about security and ive guarded against injection by using pdo and things like that but obviously its something i'll have to look at quite a bit. For the time being, to fix the upload matter, is it just a case of fixing the file path, giving it a temp file name '$_FILES['photo1']['tmp_name']' and adding enctype="multipart/form-data" to the form? – tezzataz May 12 '13 at 16:40
  • tmp_name should already be there, and it's what you should be using with move_upload_file - I think if you look at php.net manual of that function, you will see what you're missing to make the upload work. That, + form enctype. – griffin May 12 '13 at 17:49
  • just got it to work with Certain's code and it works well with the one photo but now I cant figure out how to upload multiple photos in the same way, ahh this is killing me!! haha – tezzataz May 12 '13 at 18:08
  • use [] in the name in the html form, then either use html 5 attribute multiple, or just multiple file input tags. In the php code you can then just loop over files, e.g. using foreach. – griffin May 12 '13 at 18:09
  • I've moved this to http://stackoverflow.com/questions/8088735/upload-multiple-files-to-server-and-write-to-database so I dont clog this up, could you explain it a bit more over there? I can't get it to work at all for some reason, I'd appreciate it so much – tezzataz May 12 '13 at 18:35