Skip to content
Advertisement

How to validate dimensions and format of an image URL in PHP?

My system does not host images on my server, I am using the one APIfrom imgurso it is only valid that the imput field where I insert the image URL is not empty:

$CoverPage = $_POST["cover_page"];


if (empty($_POST['cover_page'])) {
        echo json_encode(['status'=> false, 'message'=> ["cover_page" =>"Image requiere"]]);
        exit;
    }

But I need to validate that path of that image, which has minimum dimensions 400x400may be more but it cannot be less, image formats allowed png, jpe, svg,among others, this is in case another URLwrong path was added .

Image URL:

https://i.imgur.com/UkvbM34.jpg

It is important that in the image validation only allow the URL to be from imgur

Javascript imgur ,,,,,

(function (root, factory) {
    "use strict";
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.Imgur = factory();
    }
}(this, function () {
    "use strict";
    var Imgur = function (options) {
        if (!this || !(this instanceof Imgur)) {
            return new Imgur(options);
        }

        if (!options) {
            options = {};
        }

        if (!options.clientid) {
            throw 'Provide a valid Client Id here: https://api.imgur.com/';
        }

        this.clientid = options.clientid;
        this.endpoint = 'https://api.imgur.com/3/image';
        this.callback = options.callback || undefined;
        this.dropzone = document.querySelectorAll('.dropzone');
        this.info = document.querySelectorAll('.info');

        this.run();
    };

    Imgur.prototype = {
        createEls: function (name, props, text) {
            var el = document.createElement(name), p;
            for (p in props) {
                if (props.hasOwnProperty(p)) {
                    el[p] = props[p];
                }
            }
            if (text) {
                el.appendChild(document.createTextNode(text));
            }
            return el;
        },
        insertAfter: function (referenceNode, newNode) {
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
        },
        post: function (path, data, callback) {
            var xhttp = new XMLHttpRequest();

            xhttp.open('POST', path, true);
            xhttp.setRequestHeader('Authorization', 'Client-ID ' + this.clientid);
            xhttp.onreadystatechange = function () {
                if (this.readyState === 4) {
                    if (this.status >= 200 && this.status < 300) {
                        var response = '';
                        try {
                            response = JSON.parse(this.responseText);
                        } catch (err) {
                            response = this.responseText;
                        }
                        callback.call(window, response);
                    } else {
                        throw new Error(this.status + " - " + this.statusText);
                    }
                }
            };
            xhttp.send(data);
            xhttp = null;
        },
        createDragZone: function () {
            var p1, p2, input;
            //Dejar archivo de imagen aquí
            //O haga clic aquí para seleccionar la imagen
            p1 = this.createEls('p', {}, 'Leave image file here');
            p2 = this.createEls('p', {}, 'Or click here to select the image');
            input = this.createEls('input', {type: 'file', className: 'input', accept: 'image/*'}); //name: 'cover_page', 

            Array.prototype.forEach.call(this.info, function (zone) {
                zone.appendChild(p1);
                zone.appendChild(p2);
            }.bind(this));
            Array.prototype.forEach.call(this.dropzone, function (zone) {
                zone.appendChild(input);
                this.status(zone);
                this.upload(zone);
            }.bind(this));
        },
        loading: function () {
            var div, table, img;

            div = this.createEls('div', {className: 'loading-modal'});
            table = this.createEls('table', {className: 'loading-table'});
            img = this.createEls('img', {className: 'loading-image', src: 'imgur/api/css/loading-spin.svg'});

            div.appendChild(table);
            table.appendChild(img);
            document.body.appendChild(div);
        },
        status: function (el) {
            var div = this.createEls('div', {className: 'status'});

            this.insertAfter(el, div);
        },
        matchFiles: function (file, zone) {
            var status = zone.nextSibling;

            if (file.type.match(/image/) && file.type !== 'image/svg+xml') {
                document.body.classList.add('loading');
                status.classList.remove('bg-success', 'bg-danger');
                status.innerHTML = '';

                var fd = new FormData();
                fd.append('image', file);
                fd.append('type', 'URL');

                this.post(this.endpoint, fd, function (data) {
                    document.body.classList.remove('loading');
                    typeof this.callback === 'function' && this.callback.call(this, data);
                }.bind(this));
            } else {
                status.classList.remove('bg-success');
                status.classList.add('bg-danger');
                status.innerHTML = 'Invalid archive';
            }
        },
        upload: function (zone) {
            var events = ['dragenter', 'dragleave', 'dragover', 'drop'],
                file, target, i, len;

            zone.addEventListener('change', function (e) {
                if (e.target && e.target.nodeName === 'INPUT' && e.target.type === 'file') {
                    target = e.target.files;

                    for (i = 0, len = target.length; i < len; i += 1) {
                        file = target[i];
                        this.matchFiles(file, zone);
                    }
                }
            }.bind(this), false);

            events.map(function (event) {
                zone.addEventListener(event, function (e) {
                    if (e.target && e.target.nodeName === 'INPUT' && e.target.type === 'file') {
                        if (event === 'dragleave' || event === 'drop') {
                            e.target.parentNode.classList.remove('dropzone-dragging');
                        } else {
                            e.target.parentNode.classList.add('dropzone-dragging');
                        }
                    }
                }, false);
            });
        },
        run: function () {
            var loadingModal = document.querySelector('.loading-modal');

            if (!loadingModal) {
                this.loading();
            }
            this.createDragZone();
        }
    };

    return Imgur;
}));

var feedback = function(res) {
    if (res.success === true) {
        var get_link = res.data.link.replace(/^http:///i, 'https://');
        document.querySelector('.status').classList.add('bg-success');
        //document.querySelector('.status').innerHTML = 'Image : ';
        //document.querySelector('.loading-image').src = res.data.link;
        $('.urlimg').val(res.data.link);
    }
};

new Imgur({
    clientid: 'f048780ea2fd4cd', //You can change this ClientID
    callback: feedback
});
,,,,,

Advertisement

Answer

You can send the image directly from the client-side to the imgur API, via JS, or send to your PHP app server (server-side validation), which will validate and send the image to the imgur.

I recommend you using the server-side validation. In this case the image will be uploaded to your app server and get stored in a temporary directory, where you can access it with PHP, like this:

if ( ! empty( $_FILES ) ) {
    foreach( $_FILES as $file ) {
        $size = getimagesize( $file['tmp_name'] );
    }
}

To get the image size with JS, just do the following before submitting the image:

var img = document.getElementById( 'imageid' ); 
if ( img.clientWidth > 400 && img.clientHeight > 400 ) {
    // Send the image to imgUr
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement