0

This is the PHP part:→

<?php 
//upload.php

if (isset($_POST["image_url"])) {
    $message = '';
    $image = '';
    if (filter_var($_POST['image_url'], FILTER_VALIDATE_URL)) {
        $allowed_extension = array("jpg","png","jpeg","gif");
        $url_array = explode("/", $_POST["image_url"]);
        $image_name = end($url_array);
        $image_array = explode(".", $image_name);
        $extension = end($image_array);
        if (in_array($extension, $allowed_extension)) {
            $image_data = file_get_contents($_POST["image_url"]);
            $new_image_path = "upload/".rand().".".$extension;
            file_put_contents($new_image_path, $image_data);
            $message = 'Image Uploaded';
            $image = '<img src="'.$new_image_path.'" class="img-responsive img-thumbnail">';
        }else{
            $message = 'Image not Found';
        }
    }else{
        $message = 'Invalid URL';
    }
    $output = array(
        'message' => $message,
        'image'   => $image
    );
    echo json_encode($output);
}

Issue: No error messages, but yet image not getting uploaded.

This is the code on Index.php →

<!doctype html>
<html class="no-js" lang="">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    </head>
    <body>
        <div class="container box">
            <br>
            <br>
            <br>
            <h2 align="center">PHP upload an image file through URL.</h2>
            <br>

            <div class="form-group">
                <label>Enter Image URL</label>
                <input type="text" name="image_url" id="image_url" class="form-control">
            </div>
            <div class="form-group">
                <input type="button" name="upload" id="upload" value="upload" class="btn btn-info"> 
            </div>
            <br>            
        </div>
        <br>
        <br>
        <br>
        <div id="result">
            
        </div>
        <br>
        <br>
        <br>
     
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
    <script>
        $(document).ready(function(){
            $('#upload').click(function(){
                var image_url = $('#image_url').val();
                if (image_url === '') {
                    alert("Please enter image URL");
                    return false;

                } else {
                    $('#upload').attr("disabled","disabled");
                    $.ajax({
                        url:"upload.php",
                        method:"POST",
                        data:{image_url:image_url},
                        dataType:"JSON",
                        beforeSend:function(){
                            $('#upload').val("Processing...")
                        },
                        success:function(data){
                            $('#image_url').val('');
                            $('#upload').val('Upload');   
                            $('#image_url').attr('disabled',false);         
                            $('#result').html(data.image);  
                            alert(data.message);            
                        }
                    })
                }
            })
        })
    </script>
    </body>
</html>

Please let me know in case I need to provide more information.

desbest
  • 4,746
  • 11
  • 51
  • 84
  • Here is a related question https://stackoverflow.com/questions/8504080/using-post-and-enctype-multipart-form-data-form – desbest Oct 13 '20 at 03:28
  • What is the response you get from the ajax request? – Musa Oct 13 '20 at 03:35
  • I tested my localhost it's working . I just created upload folder only .. – Jack jdeoel Oct 13 '20 at 04:07
  • 1
    As you're new to Stack Overflow, I remind you to edit `php.ini` and set `display_errors` to be `On` instead of `Off`, otherwise php errors will not display. – desbest Oct 13 '20 at 12:34
  • Here is a good JSON validator for you to use. https://jsonformatter.curiousconcept.com – desbest Oct 13 '20 at 23:26

2 Answers2

-1

Maybe you can try with the global variable $_FILES and the "move_uploaded_file" method, here's an example that might help you:

if (isset($_POST['submit-file'])) {
    $file = $_FILES['file'];

    $fileName = $_FILES['file']['name'];
    $fileTmpName = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileError = $_FILES['file']['error'];
    $fileType = $_FILES['file']['type'];

    $fileExt = explode(".", $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', 'jpeg', 'png', 'pdf');

    if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
            if ($fileSize < 5000000) {
                $fileNewName = uniqid('', true). "." . $fileActualExt;
                $fileDestination = '../evidence/' . $fileNewName;
                move_uploaded_file($fileTmpName, $fileDestination);
                header("Location: index.php?action=fileUploaded");
            } else {
                echo "Your file is too big.";
                exit();
            }
        } else {
            echo "There was an error.";
            exit();
        }

    } else {
        header("Location: index.php?error=invalidFile");
        exit();
    }

}

PS: I recommend to you to use "header" and "Location: " to redirect properly when an error occur

Here some useful docs:

https://www.php.net/manual/en/reserved.variables.files.php https://www.php.net/manual/en/function.move-uploaded-file.php

Diego Duarte
  • 79
  • 1
  • 6
-1

That is not how you upload files using ajax in jquery. To understand why, you have to understand how uploading works without ajax.

When you are uploading files with a HTML form without ajax, the <form> tag needs the enctype="multipart/form-data" attribute, otherwise the files won't upload. Changing the enctype changes the format of the HTTP request or XMLHttpRequest (a XMLHttpRequest is a http request made with ajax) by submitting a HTTP header.

As you are using jquery to submit your form with ajax, obviously that <form> attribute won't work. Instead you have to add the following lines to your $.ajax() function.

contentType: false,
processData: false,

Also part of your code isn't valid javascript.

data:{image_url:image_url},

At first look, {image_url: image_url} looks like valid JSON, but all JSON can begin with a [ and end with a ]. It can also have the [ and ] and begin with { "keyname": [ and end with ] }

However it is not clear to the javascript interpreter what part of that line is a string, and what part is a variable.

It has to be changed to this.

data: "{image_url:"+image_url+"}",

And image_url has to be defined as a variable before the $.ajax function like so.

image_url = $("#image_url").val();

I have tested using ajax in jquery to upload files just now and got it to work. For more information, click this link.

desbest
  • 4,746
  • 11
  • 51
  • 84