• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 367
  • Last Modified:

Create alert message with PHP

I have a php script I am modifying to upload images... a portion of it pushes a success message if all the qualifications are satisfied. On success the following scripts diverts to a new page...


// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';

...


header('Location: ' . $uploadSuccess);


I want to push a message to an alert box or something on the same page instead of going to a new one. How can I do this?
0
pixelscape
Asked:
pixelscape
  • 10
  • 7
  • 3
  • +2
1 Solution
 
4e4enCommented:
you can pass mesage to show with redirection.

header('Location: ' . $uploadSuccess . '?msg=Sucess!' );

Open in new window


and in upload.success.php:
if( isset($_REQUEST['msg']) ) {
    echo $_REQUEST['msg'];
}

Open in new window


P.S. Code requires msg data validation..
0
 
brutaldevCommented:
Don't use the header function, that is what is making it redirect to the new page.

Insert some Javascript in it's place to just call the alertfunction instead which pops up a basic dialog box.

EG:
...
echo "<script type='text/javascript'>";
echo "alert('Upload was successful!');";
echo "</script>";
...

Open in new window


More info on alert can be found here: http://www.w3schools.com/js/js_popup.asp
0
 
pixelscapeAuthor Commented:
That alert script works great, now however it displays on a blank page... I guess the script page upload.processor.php. However I want this to show up on the previous page I submitted the form on... awards4_engraving.php... here's the upload.processor.php script.

<?php  

// filename: upload.processor.php

// first let's set some variables

// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

// make a note of the directory that will recieve the uploaded files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';

// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'awards4_engraving.php';

// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'awards4_engraving.php';

// name of the fieldname used for the file in the HTML form
$fieldname = 'file';



// Now let's deal with the upload

// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
                2 => 'html form max file size exceeded',
                3 => 'file upload was only partial',
                4 => 'no file was attached');

// check the upload form was actually submitted else print form
isset($_POST['submit'])
      or error('the upload form is neaded', $uploadForm);

// check for standard uploading errors
($_FILES[$fieldname]['error'] == 0)
      or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
      
// check that the file we are working on really was an HTTP upload
@is_uploaded_file($_FILES[$fieldname]['tmp_name'])
      or error('not an HTTP upload', $uploadForm);
      
// validation... since this is an image upload script we
// should run a check to make sure the upload is an image
@getimagesize($_FILES[$fieldname]['tmp_name'])
      or error('only image uploads are allowed', $uploadForm);
      
// make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
      $now++;
}

// now let's move the file to its final and allocate it with the new filename
@move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
      or error('receiving directory insuffiecient permission', $uploadForm);
      
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to the success page.
echo "<script type='text/javascript'>";
echo "alert('Upload was successful!');";
echo "</script>";

// make an error handler which will be used if the upload fails
function error($error, $location, $seconds = 5)
{
echo "<script type='text/javascript'>";
echo "alert('Upload Failed!');";
echo "alert(". $error .");";
echo "</script>";
} // end error handler

?>
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
4e4enCommented:
because you need to show message ONLY if request method is post and file upload and file saving has been suceeded?
0
 
Ray PaseurCommented:
Here is an example of how to upload files and test for success.  See the part from line 166 to the end.  That is where you might put the alert. But if it were my app I would just write a web page instead of using a Javascript alert.
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php


// PHP 5.1+  SEE http://us3.php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'RAY_junk';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8192000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME SCRIPT
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    //    echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code    = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file = getcwd() . '/' . $uploads . '/' . $f_name . '.' . $f_type;
        $my_file     =                  $uploads . '/' . $f_name . '.' . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

0
 
pixelscapeAuthor Commented:
Thanks Ray, that script works excellent. I made some modifications to work within my application... problem I am having is when I go to the page with the upload script on it... the script processes and says Results: File Upload already.
0
 
Ray PaseurCommented:
Please post a URL where I can test your script, thanks.
0
 
pixelscapeAuthor Commented:
Loads fine here on it's own page: http://www.gochampion.net/express/uploadscript.php

Have the same thing at the bottom of this page... http://www.gochampion.net/express/awards4_engraving.php

If you just open this page it loads fine... apparently something I pass along is interfering... if you start from the beginning you'll see what I mean... http://www.gochampion.net/express

thx
0
 
pixelscapeAuthor Commented:
I know what the problem is... I posted data to this page from the previous... can I reset the $_POST variable?
0
 
haloexpertsexchangeCommented:
Is it possible to get the rest of the awards4_engraving.php page. I feel like what you are showing is missing information. For instance what is different about when you go directly to the page that allows you to then get to the upload logo vs when you get to that same page after following the ordering process through.
The only superficial difference that I can see without seeing code is the fact that after you have gone through the ordering process the url is this http://www.gochampion.net/express/awards4_engraving.php# instead of this http://www.gochampion.net/express/awards4_engraving.php
0
 
haloexpertsexchangeCommented:
Not really, it is best if you need information still to set a session variable or cookie and store things that way.
0
 
haloexpertsexchangeCommented:
If you must use post information make a form with hidden variables that gets posted when the page gets posted back to itself.
0
 
pixelscapeAuthor Commented:
got it resolved changed...

if (empty($_POST))

to

if (empty($_POST['logo']))
0
 
pixelscapeAuthor Commented:
Actually that prevents me from uploading... I think I am on the right track. Perhaps I could use
$_SESSION instead? Ray, your thoughts?
0
 
Ray PaseurCommented:
We may need to see the script as you have adapted it.  I just tested it and the upload worked fine.
0
 
pixelscapeAuthor Commented:
Hi Ray, I am back to your original script. Looking at what you wrote the if (empty($_POST))
is satisfied when I run the script because I posted to this page from the previous one. So can $_POST be reset or we use something else to determine whether to start that if (empty($_POST)) ??
0
 
Ray PaseurCommented:
Why speculate about the code?  Let me try this one again, "We may need to see the script as you have adapted it."
0
 
pixelscapeAuthor Commented:
<?php 
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php


// PHP 5.1+  SEE http://us3.php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploaded_files';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 15 MB
$max_file_size = '15728640';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 1;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST['logo'])) <<< This is what is allowing the code to run when I post from previous page
{
    ?>
    <span id="engrave_logoplace"><strong>Add your logo?</strong></span> Setup fee $35.00

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME SCRIPT
    -->

    <form name="Uploadlogo" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    1. Select file on your computer
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<label class=\"cabinet\"><input name=\"userfile$n\" type=\"file\" class=\"file\" size=\"80\" /></label>\n";
    }
    ?>
    
    <script type="text/javascript" language="javascript">
		SI.Files.stylizeAll();
	</script>


   	<input autocomplete="off" type="checkbox" name="overwrite" /><span class="logo_overwrite">Overwrite existing logo.</span><br/><br/>
    2. Click to 
    <input type="submit" value="Upload Logo" />
    </form>

    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<span id='engrave_logoplace'><strong>Logo Uploaded</strong></span>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    //    echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code    = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file = getcwd() . '/' . $uploads . '/' . $f_name . '.' . $f_type;
        $my_file     =                  $uploads . '/' . $f_name . '.' . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            // echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><img src=\"$my_file\" width='' height='120px' alt=''>";
            
            //session_register('orientation');
            //$_SESSION['orientation'] = $_POST['orientation'];
            
            //session_register('orientation');
            //$_SESSION['orientation'] = $_POST['orientation'];
            
            
            
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

?>

Open in new window

0
 
Ray PaseurCommented:
OK, I think I am understanding this.  Let me see if I can paraphrase...

You have a "form script" that is a separate file from this script that is the "action script" (named in the action= attribute of the <form> tag).  Is that right?

If so, you can remove the form-generation part of this script, lines 50-90.  If you encounter any errors, you can issue error messages, and if you had any errors, you might present a link to the client showing them the way back to the form.
0
 
pixelscapeAuthor Commented:
Close... this application is a series of forms basically and I post variables to each subsequent page. So awards3_engraving posts form information to awards4_engraving.php which I pick up with sessions at the top.

Problem is your script uses if (empty($_POST)) which ends up being true everytime someone goes to the page by clicking next due to the above.

I like how your form generates dynamically and then shows results automatically. Everything works fine. Just is there a way to make this if (empty($_SESSION['logo'])) or something. I have been playing around with it and when I make that change the prompt to upload appears but no actual upload occurs. Thanks for your help Ray! I really appreciate it.
0
 
Ray PaseurCommented:
OK, I think I understand your design pattern a little better now.  Here is how I would go about that.

Create a list of pages that must be processed.  It would be an ordered array of the page URLs.  Store this in the session.  Each page in this list would contain its own form script and its own action script, together in one script file.

Have each page handle all its own information collection, filtering and error messages.  When successful the page will write its information into the data base.

Have each page present a link to the client that says something like "next step" or have a small table with some kind of red star indicator for steps that are no complete yet.

0
 
pixelscapeAuthor Commented:
I ended up putting Ray's script on a modal window on the same page and everything works fine. Thanks for your help!
0
 
Ray PaseurCommented:
Thanks for the points - it's a great question, ~Ray
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 10
  • 7
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now