i want upload image in php and rename it

Dani AI

Generated

Short, practical plan (builds on links and ’s question about viewing): validate the uploaded file, ensure it’s an image, generate a safe unique filename on the server, move the temp file into an upload folder, and store that new name (and the original name if needed) in the database for later display.

A minimal, safe upload+rename example (validate image, preserve extension, create unique name):

<?php
$allowed = ['jpg','jpeg','png','gif'];
if (!empty($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $tmp = $_FILES['image']['tmp_name'];

    // quick image check
    if (getimagesize($tmp) === false) exit('Not an image');

    // MIME check (safer than trusting $_FILES['image']['type'])
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime  = $finfo->file($tmp);
    if (!in_array($mime, ['image/jpeg','image/png','image/gif'])) exit('Invalid mime');

    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) exit('Bad extension');

    $base = function_exists('random_bytes') ? bin2hex(random_bytes(8)) : uniqid();
    $newname = $base . '.' . $ext;
    $dest = __DIR__ . '/uploads/' . $newname;

    if (!is_dir(dirname($dest))) mkdir(dirname($dest), 0755, true);
    if (move_uploaded_file($tmp, $dest)) {
        // store $newname in DB; use '/uploads/'.$newname in <img> tags
    } else exit('Upload failed');
}
?>

Key cautions and tips:

  • Do not trust the original filename. Always generate server-side names and whitelist extensions.
  • Check file size against application limits and php.ini (upload_max_filesize, post_max_size).
  • Prevent execution in the uploads folder (place uploads outside webroot or disable script execution via server config).
  • Guard against double extensions (e.g., image.php.jpg) by validating MIME/getimagesize and file extension.
  • Use the $_FILES['...']['error'] constant values to surface upload problems, and ensure the HTML form uses enctype="multipart/form-data".

If uploads silently fail, check form enctype, PHP error logs, directory write permissions, and PHP upload_max_filesize/post_max_size. This approach complements the pointers from and provides a secure, ready-to-use pattern for upload + rename.

Recommended Answers

All 4 Replies

so you want to upload image just or also want to view it

i want to upload and rename it

Google yourself. You'll see many tutorials. Also, check links.

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.