Froala Editor v4.2.0 is Here LEARN MORE

Skip to content

Server Side Integration

File Upload with PHP

The following example illustrates how to handle file upload on your server using PHP as a server-side language. For step by step explanation see file upload concept.

First, you need to pass to the Froala WYSIWYG HTML Editor, upon initialization, the URL where to upload the files. In our case it would be '/upload_file.php'.

  $(function() {
      // Set the file upload URL.
      fileUploadURL: '/upload_file.php',

      fileUploadParams: {
        id: 'my_editor'

Next, you have to store the file on your PHP server and return a JSON with a link field that contains the URL to the uploaded file. This is a basic example of how the "upload_file.php" file may look like. Please note that you may also need to create the uploads folder and set the right permissions to access it.

    // Allowed extentions.
    $allowedExts = array("txt", "pdf", "doc");

    // Get filename.
    $temp = explode(".", $_FILES["file"]["name"]);

    // Get extension.
    $extension = end($temp);

    // Validate uploaded files.
    // Do not use $_FILES["file"]["type"] as it can be easily forged.
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);

    if ((($mime == "text/plain")
    || ($mime == "application/msword")
    || ($mime == "application/x-pdf")
    || ($mime == "application/pdf"))
    && in_array($extension, $allowedExts)) {
        // Generate new random name.
        $name = sha1(microtime()) . "." . $extension;

        // Save file in the uploads folder.
        move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "/uploads/" . $name);

        // Generate response.
        $response = new StdClass;
        $response->link = "/uploads/" . $name;
        echo stripslashes(json_encode($response));