2

I am using a code to upload a cropped image using Ajax and PHP.

Everything works except for the fact that the destination of the uploaded image is in the same folder as the files. Anyone knows how to change the directory?

Code

if (isset($_POST["image"])) {
    $data = $_POST["image"];
    $image_array_1 = explode(";", $data);
    $image_array_2 = explode(",", $image_array_1[1]);
    $data = base64_decode($image_array_2[1]);
    $imageName = time() . '.png';

    file_put_contents($imageName, $data);

    echo '<img src="' . $imageName . '" class="img-thumbnail" />';
}
Community
  • 1
  • 1

1 Answers1

2

It may not be the best idea to change that.

However, if you wish/have to change it, you probably need to change the first variable of your file_put_content($filename, $data);.

if (isset($_POST["image"])) {
    $data = $_POST["image"];
    $image_array_1 = explode(";", $data);
    $image_array_2 = explode(",", $image_array_1[1]);
    $data = base64_decode($image_array_2[1]);
    $imageName = time() . '.png';

    $filename = 'new/path/to/image/' . $imageName;
    file_put_contents($filename, $data);
}

Then, this echo most likely will not work:

echo '<img src="' . $imageName . '" class="img-thumbnail" />';

You may have few options, which this one might be the best: Since you have base64 images, you may follow this post to display it using your $data variable.

It would probably look like, not so sure:

echo '<img src="data:image/png;base64,' . $data . ';" class="img-thumbnail" />';

Output

I'm not sure about this, you may check and debug it:

if (isset($_POST["image"])) {
    $data = $_POST["image"];
    $image_array_1 = explode(";", $data);
    $image_array_2 = explode(",", $image_array_1[1]);
    $data = base64_decode($image_array_2[1]);
    $imageName = time() . '.png';

    $filename = 'new/path/to/image/' . $imageName;
    file_put_contents($filename, $data);

    echo '<img src="data:image/png;base64,' . $data . ';" class="img-thumbnail" />';

}

In this post you may read about advantages and disadvantages of base64 images.

Emma
  • 27,428
  • 11
  • 44
  • 69