Joesphine
Joesphine

Reputation: 13

Javascript code does not execute while php redirect

I have two PHP files.

index.php allows users to upload an image. The uploaded data is sent to another page i.e. upload.php, where I check certain conditions for example if the uploaded image is really an image and not some other file and if the image already exists on the server etc;

I want to see that my upload.php page redirects back to the index.php page in false conditions. I have seen many of the posts on redirecting, e.g., by using header, which I did. Well, It does redirect. However, there is some part of javascript code, which does not execute. I want to see that alert box on my upload.php page, which upon user interaction redirects to index.php.

Alert box does not appear at the moment, but the page does redirect

My question might be very trivial, but I am a PHP newbie.

index.php

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

upload.php

$target_dir = "uploads/";
$file_name=basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $file_name;
$uploadOk = 1;

if (file_exists($target_file)) {
    $uploadOk = 0;
    echo "<script language='javascript'>
            alert('Sorry, file already exists.Consider Renaming or upload new file');
            </script>";
    header("Location: http://xx.yyy.zz");
    exit;
}

Upvotes: 0

Views: 340

Answers (1)

Tycho
Tycho

Reputation: 248

You can replace the 'HTTP header redirect' with a redirection done in javascript.

Remove the code

header("Location: http://xx.yyy.zz");

And replace the echo command with

echo "<script language='javascript'>
        alert('Sorry, file already exists.Consider Renaming or upload new file');
        window.location = "http://xx.yyy.zz";
        </script>";

Upvotes: 1

Related Questions