Hướng dẫn image type php

Với mọi trang web đều phải có chức năng upload image lên đưa Database với mục đích thêm hình ảnh vào cơ sở dữ liệu MySQL. Bài viết này sẽ hướng dẫn bạn cách upload ảnh bằng PHP và MySQL với những đoạn code dễ hiểu đọc xong bạn hoàn toàn có thể làm được.

  • Readmore : Code hiển thị nội dung bài viết trong PHP

Với bài tập này bạn sẽ biết cách lưu đường dẫn ảnh vào Database và hiển thị bức ảnh lên trên website. Nào hãy bắt đầu thôi!

Hướng dẫn image type php

Bước 1: Bạn sẽ khởi tạo 4 file như trong hình

  • photo: dùng để lưu hình ảnh trên máy tính
  • connect.php; kết nối tới Database
  • style; thêm CSS để trang trí form
  • upload.php; file upload ảnh
  • xuly.php; xử lý ảnh sau khi upload

Tạo 1 cơ sở dữ liệu Database tên là ‘upload_image‘ => sau đó tạo bảng Table tên là images bằng paste đoạn MySQL vào Database

CREATE TABLE IF NOT EXISTS `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Bước 2: Tiếp theo bạn sẽ tạo một file upload.php

 
 
 
Image Upload 
 
 
 

Bước 3: Tiếp theo sẽ tạo một file là xuly.php

 2097152) {
$errors[]='Kích thước file không được lớn hơn 2MB';
}
$image = $_FILES['image']['name'];
$target = "photo/".basename($image);
$sql = "INSERT INTO images (image) VALUES ('$image')";
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
echo '';
}else{
echo '';
}
}
$result = mysqli_query($conn, "SELECT * FROM images");
?>



Image Upload



"; echo ""; echo "
"; } ?>

Bước 4: Tạo file connect.php để kết nối database

Bước 5: Thêm file style.css

#content{
margin: 20px auto;
border: 1px solid #cbcbcb;
overflow: auto;
padding: 20px;
}
form{
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
padding: 5px;
border: 1px solid #cbcbcb;
float: left
}
#img_div:after{
content: "";
display: block;
clear: both;
}
#img_div img{
float: left;
margin: 5px;
width: 400px;
height: auto;
}

Sau khi tạo xong 4 file: thư mục photo trong máy tính, upload.php, xuly.php và connect.php, style.css bạn thử chạy vào xem kết quả như thế nào.

Kết luận: Trên đây là code upload hình ảnh lên Database bằng PHP và MySQL, với bài hướng dẫn với các bước đơn giản trên hi vọng sẽ giúp bạn học thêm một chút kiến thức về lập trình PHP.

Đọc thêm: Cách lấy dữ liệu trong MySQL

Với mọi trang web đều phải có chức năng upload image lên đưa Database với mục đích thêm hình ảnh vào cơ sở dữ liệu MySQL. Bài viết này sẽ hướng dẫn bạn cách upload ảnh bằng PHP và MySQL với những đoạn code dễ hiểu đọc xong bạn hoàn toàn có thể làm được.

  • Readmore : Code hiển thị nội dung bài viết trong PHP

Với bài tập này bạn sẽ biết cách lưu đường dẫn ảnh vào Database và hiển thị bức ảnh lên trên website. Nào hãy bắt đầu thôi!

Bước 1: Bạn sẽ khởi tạo 4 file như trong hình

  • photo: dùng để lưu hình ảnh trên máy tính
  • connect.php; kết nối tới Database
  • style; thêm CSS để trang trí form
  • upload.php; file upload ảnh
  • xuly.php; xử lý ảnh sau khi upload

Tạo 1 cơ sở dữ liệu Database tên là ‘upload_image‘ => sau đó tạo bảng Table tên là images bằng paste đoạn MySQL vào Database

CREATE TABLE IF NOT EXISTS `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Bước 2: Tiếp theo bạn sẽ tạo một file upload.php

 
 
 
Image Upload 
 
 
 

Bước 3: Tiếp theo sẽ tạo một file là xuly.php

 2097152) {
$errors[]='Kích thước file không được lớn hơn 2MB';
}
$image = $_FILES['image']['name'];
$target = "photo/".basename($image);
$sql = "INSERT INTO images (image) VALUES ('$image')";
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
echo '';
}else{
echo '';
}
}
$result = mysqli_query($conn, "SELECT * FROM images");
?>



Image Upload



"; echo ""; echo "
"; } ?>

Bước 4: Tạo file connect.php để kết nối database

Bước 5: Thêm file style.css

#content{
margin: 20px auto;
border: 1px solid #cbcbcb;
overflow: auto;
padding: 20px;
}
form{
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
padding: 5px;
border: 1px solid #cbcbcb;
float: left
}
#img_div:after{
content: "";
display: block;
clear: both;
}
#img_div img{
float: left;
margin: 5px;
width: 400px;
height: auto;
}

Sau khi tạo xong 4 file: thư mục photo trong máy tính, upload.php, xuly.php và connect.php, style.css bạn thử chạy vào xem kết quả như thế nào.

Kết luận: Trên đây là code upload hình ảnh lên Database bằng PHP và MySQL, với bài hướng dẫn với các bước đơn giản trên hi vọng sẽ giúp bạn học thêm một chút kiến thức về lập trình PHP.

Đọc thêm: Cách lấy dữ liệu trong MySQL

I have a PHP script that should create a valid image file on server side. The following code runs fine:

$filename = $_GET['filename'];

// Only proceed if we got valid input
if ($filename !== null) {
    echo "$filename is not null.";
    $image = @imagecreatetruecolor(10, 10)
                or die('Cannot Initialize new GD image stream');

    if (strpos($image, '/gif') !== false) {
        $image_type = "GIF";
        header('Content-Type: image/gif');
        $successful = imagegif($image, "./$filename");
    } else if (strpos($image, '/jpeg') !== false) {
        $image_type = "JPG";
        header('Content-Type: image/jpeg');
        $successful = imagejpeg($image, "./$filename");
    } else if (strpos($image, '/png') !== false) {
        $image_type = "PNG";
        header('Content-Type: image/png');
        $successful = imagepng($image, "./$filename");
    }

    if ($successful) {
        echo "Image written to '$filename'.";
    } else {
        echo "Could not write $image_type image to '$filename'.";
    }
    imagedestroy($image);
    echo "image destroyed.";
} else {
    echo "$filename is null.";
}

This works fine & an image with the $filename is created. But actually, I have to receive not only the file name but the image also. So, the real code is

$filename = $_GET['filename'];

$image = $_GET['image'];

echo "file $filename = '$image'.";

// Only proceed if we got valid input
if ($filename !== null) {
    echo "$filename is not null.";

    if (strpos($image, '/gif') !== false) {
        $image_type = "GIF";
        header('Content-Type: image/gif');
        $successful = imagegif($image, "./$filename");
    } else if (strpos($image, '/jpeg') !== false) {
        $image_type = "JPG";
        header('Content-Type: image/jpeg');
        $successful = imagejpeg($image, "./$filename");
    } else if (strpos($image, '/png') !== false) {
        $image_type = "PNG";
        header('Content-Type: image/png');
        $successful = imagepng($image, "./$filename");
    }

    if ($successful) {
        echo "Image written to '$filename'.";
    } else {
        echo "Could not write $image_type image to '$filename'.";
    }
    imagedestroy($image);
    echo "image destroyed.";
} else {
    echo "$filename is null.";
}

This does not work, and the result is

file t.png = 'data:image/jpeg;base64,/9j/4AAQSkZJ … qA/Cz//Z'.t.png is not null.Image written to 't.png'.image destroyed.

How can I create from the 'data:image/jpeg … ' string a valid image in PHP?

EDIT 1: I added one line to the code above to see that it is not a possible duplicate of another question:

// Only proceed if we got valid input
if ($filename !== null) {
    echo "$filename is not null.";
    $image = base64_decode($image); // <<<<

EDIT 2: I modified the code so that the file is deleted:

$filename = $_GET['filename'];

$image = $_GET['image'];

// Only proceed if we got valid input
if ($filename !== null) {
    echo "$filename is not null.";
    $image = base64_decode($image);
    $slash2 = strpos($image, '/');

    $image_type = substr($image, $slash2, strpos($image, ';') - $slash2);

    if (file_exists($filename)) unlink($filename);

    header('Content-Type: image/' . $image_type);

    switch ($image_type) {
        case "gif":
            $successful = imagegif($image, "./$filename");
            break;
        case "jpeg":
        case "jpg":
            $successful = imagejpeg($image, "./$filename");
            break;
        case "png":
            $successful = imagepng($image, "./$filename");
            break;
    }

    if ($successful) {
        echo "Image written to '$filename'.";
    } else {
        echo "Could not write $image_type image to '$filename'.";
    }
    imagedestroy($image);
    echo "image destroyed.";
} else {
    echo "$filename is null.";
}

But still, I get the reply Could not write image to 't.jpg'.

EDIT 3: This is what I pass to the two parameters:

?filename=t.jpg&image=data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAEAAAAAAAD/7AARRHVja3kAAQAEAAAAPAAA/+0ALFBob3Rvc2hvcCAzLjAAOEJJTQQlAAAAAAAQAAAAAAAAAAAAAAAAAAAAAP/bAEMAAgEBAgEBAgICAgICAgIDBQMDAwMDBgQEAwUHBgcHBwYHBwgJCwkICAoIBwcKDQoKCwwMDAwHCQ4PDQwOCwwMDP/bAEMBAgICAwMDBgMDBgwIBwgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAAEAAQMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APA6KKK/qA/Cz//Z

EDIT 4: Modified the code according to suggestions of @delboy1978uk. Also, it is not correct that the passed filename includes the image file extension, as this should always correspond to the image type:

$filename = $_GET['filename'];

$image = $_GET['image'];

echo "file $filename = '$image'.";

// Only proceed if we got valid input
if ($filename !== null) {
    $slash = strpos($image, '/') + 1;

    $image_type = substr($image, $slash, strpos($image, ';') - $slash);
    $comma = strpos($image, ',') + 1;

    $image = substr($image, $comma);

    $decoded_image = base64_decode($image);

    $image = imagecreatefromstring($decoded_image);

    echo "The image type is '$image_type'.";

    if (file_exists($filename)) {
        unlink($filename);
        echo "Deleted file '$filename'.";
    }

    header('Content-Type: image/' . $image_type);
    $filename .= '.' . $image_type;

    switch ($image_type) {
        case "gif":
            $successful = imagegif($image, "./$filename");
            break;
        case "jpeg":
        case "jpg":
            $successful = imagejpeg($image, "./$filename");
            break;
        case "png":
            $successful = imagepng($image, "./$filename");
            break;
    }

    if ($successful) {
        echo "Image written to '$filename'.";
    } else {
        echo "Could not write $image_type image to '$filename'.";
    }

    if (imagedestroy($image) === true) {
        echo "Image destroyed.";
    }
} else {
    echo "$filename is null.";
}