Hello,

I am trying to create a form which could upload image file and copy it to a certain folder and also updating the mysql database which store it's image name and title.

input_image.php

<div id="menu">
      <center>
        <h2>Image Manager</h2>
      </center>
      <p>&nbsp;</p>

  <p>metode image managementnya masih konstruksi</p><center>
      <p>


<?php

    include('../includes/koneksi.php');

    $id = isset($_POST['id']) ? $_POST['id'] : '';  
    $confirmation = isset($_POST['confirmation']) ? $_POST['confirmation'] : '';  
    $judul = isset($_POST['judul']) ? $_POST['judul'] : ''; 
    $image = isset($_POST['image']) ? $_POST['image'] : '';

    //Load berita
    if (!empty($_REQUEST['id'])){
        $result = mysql_query("SELECT * FROM gallery WHERE id =".$_REQUEST['id']) or die(mysql_error());
        $data = mysql_fetch_array($result);
        $id = $data['id'];
        $judul = $data['judul'];
        $image = $image['image'];

    }

    //Simpan berita 
    if (isset($_REQUEST['ok'])){

        if (empty($_REQUEST['id']))
            $sqlstr = "INSERT INTO gallery(judul, image) VALUES('".$judul."','".$image."')";
        else
            $sqlstr = "UPDATE gallery SET judul='".$judul."', image='".$image."' WHERE id=".$_REQUEST['id'];
        $result = mysql_query($sqlstr) or die(mysql_error());

            // cek type file & simpan file pada folder
            $file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
            $upload_exts = end(explode(".", $_FILES["image"]["name"]));
            if ((($_FILES["image"]["type"] == "image/gif")
            || ($_FILES["image"]["type"] == "image/jpeg")
            || ($_FILES["image"]["type"] == "image/png")
            || ($_FILES["image"]["type"] == "image/pjpeg"))
            && ($_FILES["image"]["size"] < 2000000)
            && in_array($upload_exts, $file_exts))
            {
            if ($_FILES["image"]["error"] > 0)
            {
            echo "Return Code: " . $_FILES["image"]["error"] . "<br>";
            }
            else
            {
            echo "Upload: " . $_FILES["image"]["name"] . "<br>";
            echo "Type: " . $_FILES["image"]["type"] . "<br>";
            echo "Size: " . ($_FILES["image"]["size"] / 1024) . " kB<br>";   
            echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br>";
            // Enter your path to upload file here
            if (file_exists("c:\xampp\xampp\htdocs\rustoleum/photocms/" .
            $_FILES["image"]["name"]))
            {
            echo "<div class='error'>"."(".$_FILES["image"]["name"].")".
            " already exists. "."</div>";
            }
            else
            {
            move_uploaded_file($_FILES["image"]["tmp_name"],
            "c:\xampp\xampp\htdocs\rustoleum/photocms/" . $_FILES["image"]["name"]);
            echo "<div class='sucess'>"."Stored in: " .
            "c:\xampp\xampp\htdocs\rustoleum/photocms/" . $_FILES["image"]["name"]."</div>";
            }
            }
            }
            else
            {
            echo "<div class='error'>Invalid file</div>";
            }

        //Jika mode edit, maka tidak akan dikirimkan konfirmasi kepada subscriber
        //if (empty($_REQUEST['id']))   kirimEmail($idKategori, $judul, $news);
        $confirmation = ($result) ? "Data telah tersimpan." : "Gagal menyimpan data.";  
    }
    ?>
    <div align="center">
        <div style="width:800px;text-align:left;">
        <script type="text/javascript" src="../../Masterlink/cgoods/ckeditor/ckeditor.js"></script>
        <link href="../../Masterlink/cgoods/ckeditor/content.css" rel="stylesheet" type="text/css"/>
        <?php echo $confirmation;?>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
            <input type="hidden" name="id" value="<?php echo $id; ?>"/>
            <table>
                <tr>
                    <th>Judul</th>
                    <th>Image</th>
                </tr>
                <tr>
                    <td><input size="30px" type="text" name="judul" value="<?php echo $judul; ?>"/></td>
                </tr>
                <tr>
                    <td><input size="30px" type="file" name="image" value="<?php echo $image; ?>"/></td>
                </tr>
                <tr><?php // showing the picture ?>
                    <td><img src="photos/<?php echo $image; ?>"/></td>
                </tr>                
                <tr>             
                    <td><input type="submit" name="ok" value="Simpan"/></td>
              </tr>
            </table>
        </form>
        </div>
    </div>

The problem with this code is that when I try uploading an image called scenary (44 KB - JPEG). An error message "Invalid image" appears. I wonder why? I thought the image is small enough and has the correct file extension.

Recommended Answers

All 19 Replies

Why are you using directories with slashes in both directions "c:\xampp\xampp\htdocs\rustoleum/photocms/" ?

Have you checked If this folder exists and If you have full write permissions ?

I have a similar problem.

I want my users to be able to create events. Each event should have an image. I have created a subfolder (events) in the uploads/ in which images for profile pictures are stored so it doesnt has read/write issues. The input type is this.

<input type="file" name="event_img" id="event_img">
<input type="submit" name="Events" id="Events"> 


and the php code i use is this

if(isset($_POST['Events']))

$event_id=mysql_real_escape_string($event_id);
$uid=mysql_real_escape_string($uid);
$title = $_POST['event_title'];
$date = $_POST['datetimepicker'];
$venue= $_POST['venue_name'];

$name = $_POST['event_img'];
$path= "uploads/events/";
$tmp = $_FILES['event_img']['tmp_name'];

move_uploaded_file($tmp, $path.$name);
$query = mysql_query("INSERT INTO events (event_id, user_id, event_title, event_date, venue_name, event_img) VALUES ('$event_id', '$uid', '$title', '$date', '$venue', '$name')") or die(mysql_error());
}
?>
 {

No matter what i try the image, although it is saved on my database but it doesnt' saved on the uploads/events/ subfolder

I googled this but it doesnt seem that i made something wrong.

Regarding the read/write permissions of the subfolder the image does appear even when i set the $path to be $path= "uploads/";

Anyone help?

where do you move your file in move_uploaded_file($tmp, $path.$name); ?

does your created file has the name you expect it to have ?

finally does the file appear on /uploads/events/ or not ?

I only following a tutorial that works: Upload Image Tutorial

I tried to change "/" with "\" then I start having problem with the quotation mark - the text highlight doesn't seems right; therefore I leave it as the way before.

have you tried with other images/formats ? What is the output If you upload gifs or other pngs ?

hyp3rkyd i move my file on uploads/events/ i tried it also as "c:\wamp\www\wall\upload/events/". On my database it saves as expected but it doesnt appear on uploads/events/
yes i used png as well
davy_yg i tried it too but nothing here is the code as i used it

oww and i get invalid type.

$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
    $upload_exts = end(explode(".", $_FILES["event_img"]["name"]));
    if ((($_FILES["event_img"]["type"] == "image/gif")
    || ($_FILES["event_img"]["type"] == "image/jpeg")
    || ($_FILES["event_img"]["type"] == "image/png")
    || ($_FILES["event_img"]["type"] == "image/pjpeg"))
    && ($_FILES["event_img"]["size"] < 2000000)
    && in_array($upload_exts, $file_exts))
    {
    if ($_FILES["event_img"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["event_img"]["error"] . "<br>";



}
    else
    {
    echo "Upload: " . $_FILES["event_img"]["name"] . "<br>";
    echo "Type: " . $_FILES["event_img"]["type"] . "<br>";
    echo "Size: " . ($_FILES["event_img"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["event_img"]["tmp_name"] . "<br>";
// Enter your path to <span class="IL_AD" id="IL_AD3">upload file</span> here
    if (file_exists("c:\wamp\www\upload/newupload/" .
    $_FILES["file"]["name"]))
    {
    echo "<div class='error'>"."(".$_FILES["file"]["name"].")".
    " already exists. "."</div>";
    }
    else
    {
    move_uploaded_file($_FILES["event_img"]["tmp_name"],
    "c:\wamp\www\upload/newupload/" . $_FILES["event_img"]["name"]);
    echo "<div class='sucess'>"."Stored in: " .
    "c:\wamp\www\upload/newupload/" . $_FILES["event_img"]["name"]."</div>";
    }
    }
}
    else
{
    echo "<div class='error'>Invalid file</div>";
    }

i mean invalid file

i tried again now it says

Upload: ds.png
Type: image/png
Size: 57.8017578125 kB
Temp file: C:\wamp\tmp\php48D1.tmp
(ds.png) already exists.

although i upload the image for the first time

if this helps anyone

your upload must be failed and the tmp file is left in folder. Try browsing the path and delete manually the file, then upload again.

Does "c:\wamp\www\upload" exist? If yes, create a folder "newupload" in it. Change all your links to 'c:\wamp\www\upload\newupload\'. Use ' instead of " (backslash must be escaped as was said)

also try to debug by placing print_r($_FILES); in different positions.

I deleted the tmp files and uploaded again. Same thing. also the folder and the subfolder both exist. Trying print_r now

Here is some more debugging info:Array ( [event_img] => Array ( [name] => 138554471714.jpg [type] => image/jpeg [tmp_name] => C:\wamp\tmp\php713C.tmp [error] => 0 [size] => 265166 )

So the code fails here:

if (file_exists("c:\wamp\www\upload/newupload/" .
    $_FILES["file"]["name"]))
    {
    echo "<div class='error'>"."(".$_FILES["file"]["name"].")".
    " already exists. "."</div>";
    }

Try to put a print_r("FAIL"); exit(); before the closing bracket }. This is what I usually do: I break the execution in several places going backwards to find the cause. If it fails here, it means that the program finds out that your file exists in place.

The array you got means you have no errors. Have you looked at the folder If your image exists ? It might exist but the error still displayed.

Try this for your upload path.

$upload_path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/';

if(!file_exists($upload_path){
    mkdir($upload_path);
}

I looked on the fo flder and it exists
i put print_r("FAIL"); exit(); and itreturns fail

Upload: g.jpg
Type: image/jpeg
Size: 586.4560546875 kB
Temp file: C:\wamp\tmp\phpEE6B.tmp
(g.jpg) already exists.
Here is some more debugging info:Array ( [event_img] => Array ( [name] => g.jpg [type] => image/jpeg [tmp_name] => C:\wamp\tmp\phpEE6B.tmp [error] => 0 [size] => 600531 ) ) FAIL

gabrielcastillo

i tried this and got nothing

$upload_path = $_SERVER['DOCUMENT_ROOT'] . 'c:/wamp/www/wall/uploads/events/';
    if(!file_exists($upload_path))
    {
    mkdir($upload_path);
    echo 'jh';
    }
    else
    {
    echo 'eo';
    }

OK guys done it!! Is it possible that this file session_dir was the problem?
If not it was the brackets. Thanks for your time. If anyone has same problem check brackets and file read/write permissions. Thanx a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.