Hiển thị các bài đăng có nhãn code Uploads ảnh. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn code Uploads ảnh. Hiển thị tất cả bài đăng

Thứ Sáu, 2 tháng 1, 2026

upload ảnh không resize ảnh

 ** HTML

<div class="file-upload">

    <input type="file" name="userfile" id="userfile" hidden>

    <label for="userfile" class="btn-upload">Choose file</label>

    <span id="file-name">No file chosen ( max < 15MB )</span>

</div>

<style type="text/css">

    .file-upload {

        display: flex;

        align-items: center;

        gap: 10px;

    }

    .btn-upload {

        padding: 8px 14px;

        background: #007bff;

        color: #fff;

        cursor: pointer;

        border-radius: 4px;

    }

    .btn-upload:hover {

        background: #0056b3;

    }

</style>


<script>

document.getElementById('userfile').addEventListener('change', function () {

    document.getElementById('file-name').textContent =

        this.files.length ? this.files[0].name : 'No file chosen';

});

</script>



** Code PHP

$upload_path = INCLUDE_PATH . '/uploads/sendemail';

$images = upload_file_contact('userfile', $upload_path);


if ($images != '') {

    $body .= '<p style="padding-left:30px">

        <b>File Images:</b>             

        <a href="'.$site_live.'uploads/sendemail/'.$images.'" download="'.$images.'" target="_blank">Download File</a>

    </p>';

}


** Function xử lý ảnh

function upload_file_contact($input_name, $upload_dir)

{

    $max_size = 15 * 1024 * 1024; // 15MB


    // 1. Không có file

    if (

        !isset($_FILES[$input_name]) ||

        $_FILES[$input_name]['error'] != 0

    ) {

        return '';

    }


    $file_tmp  = $_FILES[$input_name]['tmp_name'];

    $file_name = $_FILES[$input_name]['name'];

    $file_size = $_FILES[$input_name]['size'];


    // 2. Tách tên & đuôi file

    $pathinfo  = pathinfo($file_name);

    $ext       = strtolower($pathinfo['extension']);

    $basename  = $pathinfo['filename'];


    // 3. Danh sách đuôi cho phép (PHP 5.3)

    $allow_ext = array(

        'svg','eps','ai','psd','cdr',

        'tiff','tif','raw','pdf',

        'jpg','jpeg','png','gif','bmp',

        'doc','docx','xls','xlsx'

    );


    if (!in_array($ext, $allow_ext)) {

        info_exit("❌ Định dạng file không được phép");

    }


    // 4. Kiểm tra dung lượng

    if ($file_size > $max_size) {

        info_exit("❌ File vượt quá 15MB");

    }


    // 5. Tạo thư mục nếu chưa có

    if (!is_dir($upload_dir)) {

        mkdir($upload_dir, 0755, true);

    }


    // 6. Tránh trùng tên file

    $new_name = $file_name;

    $i = 1;

    while (file_exists($upload_dir.'/'.$new_name)) {

        $new_name = $basename.'('.$i.').'.$ext;

        $i++;

    }


    // 7. Upload file

    if (!move_uploaded_file($file_tmp, $upload_dir.'/'.$new_name)) {

        info_exit("❌ Upload file thất bại");

    }


    return $new_name;

}


Thứ Năm, 18 tháng 1, 2024

Upload and Add Watermark to Image using PHP

 File Upload Form

Create an HTML form that allows selecting a file to upload.

  • Make sure the <form> tag contains the following attributes.
    • method=”post”
    • enctype=”multipart/form-data”
  • Also, make sure <input> tag contains type="file" attribute
  • <form action="upload.php" method="post" enctype="multipart/form-data">
        Select Image File to Upload:
        <input type="file" name="file">
        <input type="submit" name="submit" value="Upload">
    </form>

Upload Image and Add Watermark with PHP (upload.php)

The upload.php file handles the image upload and watermark adding functionality.

  • Use PHP pathinfo() function to get the file extension and check whether the selected file type is within the allowed file format.
  • Upload file to server using move_uploaded_file() function in PHP.
  • Load and create a new stamp from the watermark image using imagecreatefrompng() function.
  • Load and create a new image from the uploaded image based on the file type.
  • Set the right and bottom margin for the watermark image.
  • Get the height and width of the watermark image.
  • Copy the watermark image onto the uploaded photo using imagecopy() function.
  • Use margin offsets and image width to calculate the positioning of the watermark.
  • Save image with watermark using imagepng() function.
  • Free memory associated with image resource using imagedestroy() function.
  • Display the watermarked image upload status.
<?php 
// Path configuration
$targetDir "uploads/";
$watermarkImagePath 'codexworld-logo.png';

$statusMsg '';
if(isset(
$_POST["submit"])){
    if(!empty(
$_FILES["file"]["name"])){
        
// File upload path
        
$fileName basename($_FILES["file"]["name"]);
        
$targetFilePath $targetDir $fileName;
        
$fileType pathinfo($targetFilePath,PATHINFO_EXTENSION);
        
        
// Allow certain file formats
        
$allowTypes = array('jpg','png','jpeg');
        if(
in_array($fileType$allowTypes)){
            
// Upload file to the server
            
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
                
// Load the stamp and the photo to apply the watermark to
                
$watermarkImg imagecreatefrompng($watermarkImagePath);
                switch(
$fileType){
                    case 
'jpg':
                        
$im imagecreatefromjpeg($targetFilePath);
                        break;
                    case 
'jpeg':
                        
$im imagecreatefromjpeg($targetFilePath);
                        break;
                    case 
'png':
                        
$im imagecreatefrompng($targetFilePath);
                        break;
                    default:
                        
$im imagecreatefromjpeg($targetFilePath);
                }
                
                
// Set the margins for the watermark
                
$marge_right 10;
                
$marge_bottom 10;
                
                
// Get the height/width of the watermark image
                
$sx imagesx($watermarkImg);
                
$sy imagesy($watermarkImg);
                
                
// Copy the watermark image onto our photo using the margin offsets and 
                // the photo width to calculate the positioning of the watermark.
                
imagecopy($im$watermarkImgimagesx($im) - $sx $marge_rightimagesy($im) - $sy $marge_bottom00imagesx($watermarkImg), imagesy($watermarkImg));
                
                
// Save image and free memory
                
imagepng($im$targetFilePath);
                
imagedestroy($im);
    
                if(
file_exists($targetFilePath)){
                    
$statusMsg "The image with watermark has been uploaded successfully.";
                }else{
                    
$statusMsg "Image upload failed, please try again.";
                } 
            }else{
                
$statusMsg "Sorry, there was an error uploading your file.";
            }
        }else{
            
$statusMsg 'Sorry, only JPG, JPEG, and PNG files are allowed to upload.';
        }
    }else{
        
$statusMsg 'Please select a file to upload.';
    }
}

// Display status message
echo $statusMsg;
Note:

Xem lại source khi đưa ảnh vào
$targetDir "../uploads/"; 
$watermarkImagePath '../admin/codexworld-logo.png';

Thứ Hai, 26 tháng 10, 2020

Đăng ảnh nhanh

 #### Code

if (is_uploaded_file($_FILES['userfile_little']['tmp_name'])) {

    $realname = $_FILES['userfile_little']['name'];

    $f_name = explode(".",$realname);

    $extension = strtolower($f_name[1]);

    $datakod = date(U);

    $ten_save = "".$datakod.".".$extension."";

    $res = copy($_FILES['userfile_little']['tmp_name'], "../uploads/pic/".$ten_save."");

}