简体   繁体   中英

Making a success or error message after submitting image via form?

i'm really new to html and php. I'm trying to get a form working, which is used to upload pictures to a server.

<form class="myBtn" id="Upload" action="upload.php" method="post" enctype="multipart/form-data" style="visibility:hidden;"><br>
      Select template to upload:<br>
         <input type="file" name="fileToUpload" id="fileToUpload"><br>
         <input type="submit" value="Upload Image" name="submit">
</form>

This is my form in HTML.

<?php $target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$needheight = 355;
$needwidth = 275;

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "Checked: File is an image! - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "Checked: File is not an image!";
        $uploadOk = 0;
    }
}

if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 1048576) {
  echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
if($imageFileType != "png") {
    echo "Sorry, only .PNG is allowed.";
    $uploadOk = 0;
}

if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
}

else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "Your cape template". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your template. Try again.";
    }
}

?>

Here you can see my php code. I'm really sorry that its such a WoC (wall of code) but I dont really know which specific parts of the code you need to help me.

I got the php working which took me ages, but I did it. I can successfully upload templates to my server. But at the moment, after successfully submitting a template, I'll get redirected to another blank page showing: "Checked: File is an image! - image/png! Your cape template has been uploaded!"

Is there a way not to redirect to a blank page but show a success or error echo right on the main website?

Thank you alot, I'm stuck at the moment.

Remove action from your form so page will post on same page. And befoe your html <form> write the code from php which is currently in upload.php

<?php $target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$needheight = 355;
$needwidth = 275;

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "Checked: File is an image! - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "Checked: File is not an image!";
        $uploadOk = 0;
    }
}

if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 1048576) {
  echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
if($imageFileType != "png") {
    echo "Sorry, only .PNG is allowed.";
    $uploadOk = 0;
}

if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
}

else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "Your cape template". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your template. Try again.";
    }
}

?>

<form class="myBtn" id="Upload" action="" method="post" enctype="multipart/form-data" style="visibility:hidden;"><br>
      Select template to upload:<br>
         <input type="file" name="fileToUpload" id="fileToUpload"><br>
         <input type="submit" value="Upload Image" name="submit">
</form>

You could probably do something like this - keep all the code on one page and display the relevant message after the form has been submitted.

<?php


    $errors=array();
    $allowed=array('png');
    $message = false;

    /* A utility function to report actual error ( if any ) */
    function uploaderror( $code ){ 
        switch( $code ) { 
            case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
            case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
            case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
            case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
            case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
            case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
            case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
            default: return "Unknown upload error";
        }
    }


    /* Only process this if these condition are met */
    if( isset( $_POST['submit'], $_FILES['fileToUpload'] ) ) {

        /* Obtain reference to upload - Object notation is quicker/easier imo */
        $obj=(object)$_FILES['fileToUpload'];
        $name=$obj->name;
        $tmp=$obj->tmp_name;
        $size=$obj->size;
        $type=$obj->type;
        $error=$obj->error;

        /* configuration */
        $target_dir = $_SERVER['DOCUMENT_ROOT']."/uploads/";
        $target_file = $target_dir . $name;
        $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
        $needheight = 355;
        $needwidth = 275;




        if( $error == UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){
            /* Is it an image */
            $check = getimagesize( $tmp );
            if( !$check )$errors[]='Checked: File is not an image!';
            else{
                /* Find dimensions and other attributes */
                list( $width, $height, $type, $attr ) = $check;
                if( $width < $needwidth or $height < $needheight )$errors[]='Image is too small';
            }

            if( file_exists( $target_file ) )$errors[]='Sorry, that file already exists.';
            if( $size > 1048576 ) $errors[]='Sorry, your file is too large.';
            if( !in_array( $ext, $allowed ) ) $errors[]='Sorry, only images of type .'.strtoupper( implode( ', .',$allowed ) ).' '.(count($allowed)==1 ? 'is' : 'are').' allowed.';


            clearstatcache();


            if( empty( $errors ) ){
                $status = move_uploaded_file( $tmp, $target_file );
                $message = $status ? "Your cape template ". basename( $name ). " has been uploaded." : "Sorry, there was an error uploading your template. Try again.";
            }           

        } else {
            exit( uploaderror( $error ) );
        }
    }
?>
<!doctype html>
<html>
    <head>
        <title>File upload</title>
    </head>
    <body>
        <form class='myBtn' method='post' enctype='multipart/form-data'>
            Select template to upload:<br>
            <input type="file" name="fileToUpload" id="fileToUpload"><br>
            <input type="submit" value="Upload Image" name="submit">
        </form>
        <?php
            if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $message ) ){
                echo $message;
            }
            if( !empty( $errors ) ){
                foreach( $errors as $error ) echo $error . '<br />';
            }
        ?>
    </body>
</html>

Glad u completed the PHP part by urself. you have used two files one for HTML and for PHP make it as one file and make use of $_SERVER['PHP_SELF'].

<form class="myBtn" id="Upload" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"><br>
 <label>Select template to upload:</label><br>
     <input type="file" name="fileToUpload" id="fileToUpload"><br>
     <input type="submit" value="Upload Image" name="submit">
</form>

<?php 
$message = "";
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$target_dir = "/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$needheight = 355;
$needwidth = 275;
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo $message = "Checked: File is an image! - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo $message = "Checked: File is not an image!";
    $uploadOk = 0;
}
if (file_exists($target_file)) {
echo $message ="Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 1048576) {
echo $message ="Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "png") {
echo $message ="Sorry, only .PNG is allowed.";
$uploadOk = 0;
}

if ($uploadOk == 0) {
echo $message ="Sorry, your file was not uploaded.";
}

else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo $message ="Your cape template". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo $message ="Sorry, there was an error uploading your template. Try again.";
}
}
}
?>

<script>
var alert_msg = "<?php echo $message; ?>";
<?php if(strlen($message) > 1) { ?>
alert(alert_msg);
<?php } ?>
</script>

I used alert to show your status messages. Hope it works.

and please remove the hidden style in your form.( why did it come there).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM