The function does not generate an image, but it will display the one that is

It looks like there may be an issue within the function that is preventing the image from being created, or possibly in the script itself which is not passing the image to the function properly.

Below is the upload script (please note: this script is injected into AJAX)

    $path = "cache/";

    $valid_formats = array("jpg", "png", "gif", "jpeg");
    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
        {
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];

        if(strlen($name))
                {
                ist($txt, $ext) = explode(".", $name);
                if(in_array($ext,$valid_formats))
                {
                if($size<(2024*2024))
                    {
                    $new_file = "header.".$ext;
                    $tmp = $_FILES['photoimg']['tmp_name'];
                    if(move_uploaded_file($tmp, $path.$new_file))
                    {

            echo "<img src='cache/".$new_file."?".time()."'  class='preview'>";

               createHeader($new_file);                                 
                    }

                    else
                    echo "failed";
                    }

                    else
                    echo "Image file size max 1 MB";                    
                    }
                    else
                echo "Invalid file format..";   
                }

            else
                echo "Please select image..!";

            exit;
        }

And here is the function:

function createHeader($new_file) {

$path = "uploads/";
$image = "cache/";
$width = 800;

    if(preg_match('/[.](jpg)|(jpeg)$/', $new_file)) {  

        $im = imagecreatefromjpeg($image . $new_file); 

    } else if (preg_match('/[.](gif)$/', $new_file)) {  

        $im = imagecreatefromgif($image . $new_file);   
        imagecolortransparent($im, black);      

    } else if (preg_match('/[.](png)$/', $new_file)) {  

        $im = imagecreatefrompng($image . $new_file);   
    }  

    imagealphablending($im, false);
    imagesavealpha($im, true);  

    $ox = imagesx($im);  
    $oy = imagesy($im);  

    $nx = $width;  
    $ny = floor($oy * ($width / $ox) ); 

    imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);      
    imagealphablending($im, true);  
    if(!file_exists($path)) {  
      if(!mkdir($path)) {  
           die("There was a problem. Please try again!");  
      }  
       }  

    imagejpeg($nm, $path . $new_file, 100);

    imagedestroy($im);
    imagedestroy($nm);

}

The intention of the code is for users logged in to my CMS to be able to change the header on their page by clicking an icon, triggering a jQuery call to edit.php with the necessary query string. The user can then upload a new image, which will overwrite the original as 'header.jpg'

'header.jpg' should be uploaded to the 'uploads/' directory while a copy of the original image in 'cache/' should be unlinked once the function successfully creates a copy and places it in 'uploads/'.

The issue appears to be that the first script uploads the file correctly to the cache/ directory, but the function is failing to work and does nothing for the uploads/ directory.

Any clues about what might be going wrong or what I could be missing to solve this frustrating problem?

Answer №1

$path = "cache/";

$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
    {
    $name = $_FILES['photoimg']['name'];
    $size = $_FILES['photoimg']['size'];

    if(strlen($name))
            {
            list($txt, $ext) = explode(".", $name);
            if(in_array($ext,$valid_formats))
            {
            if($size<(2024*2024))
                {
                $new_file = "header.".$ext;
                $tmp = $_FILES['photoimg']['tmp_name'];
                if(move_uploaded_file($tmp, $path.$new_file))
                {

           // The following code will be executed prior to displaying the image tag
           createHeader($new_file);                                 

        echo "<img src='cache/".$new_file."?".time()."'  class='preview'>";
                }

                else
                echo "upload failed";
                }

                else
                echo "Image file size exceeds maximum limit of 1 MB";                    
                }
                else
            echo "Invalid file format..";   
            }

        else
            echo "Please select an image..!";

        exit;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The main menu items in jQuery do not display the child sub menu upon clicking

I'm currently in the process of creating a unique mobile menu for my Wordpress website, but I'm facing some challenges when it comes to displaying and hiding the sub-menu items. I've assigned the class name .menu-item-has-children as my sele ...

Updating the background image with Jquery is resulting in a distracting flicker effect

Here is a snippet of the script I'm using to create a slider that changes the background image for each image object in a specified time cycle. #Sliderimg - height set to 500px, $("#Sliderimg").css({ "background-image": "url(../Images/" + SliderIma ...

How to Conceal Attributes on a Global Scale When Converting Arrays or JSON in Laravel?

At times, you might want to restrict certain attributes from being included in your model's array or JSON representation, such as passwords. In order to achieve this, you can add a hidden property definition to your model: class User extends Model { ...

Verifying if checkboxes are selected in PHP using JavaScript

echo '<div class="col-lg-10 col-lg-offset-1 panel">' . "<table id='data' class='table'> <tr> <th></th> <th>Document No</th> <th>AWB NO</th> ...

Phalcon's Swift_SmtpTransport is a powerful email transport tool

When attempting to integrate SwiftMailer with Phalcon 3 using the Dependency Injector, an error related to the Swift_transporter Service is encountered. Error: Service '\Swift_SmtpTransport' not found in the dependency injection container ...

Adding a class to an element can be easily achieved when both input fields have values

Is it possible to apply the "active" class to the element go_back_right only when both inputs with classes search_box_name and search_box_id have content in them? I've tried looking for solutions on this platform, but being new to JavaScript, I couldn ...

Error encountered in Django due to repeated AJAX calls causing a closed socket issue: [WinError 10053] The established connection was abruptly terminated by the software running on your host machine

Trying to integrate live search functionality using the Select2 jQuery plugin in my Django 1.11.4 project has led to some server-related issues. Upon entering text into the search box, the server seems unable to handle the volume of requests and ends up sh ...

Randomly, an AJAX request sent from Internet Explorer 11 to a node.js server operating behind an Apache proxy may abruptly terminate

When using angular on a webpage, a get request is initiated to retrieve json data after a user action. The issue arises when attempting this request on Internet Explorer 11, as it fails randomly while working smoothly on Firefox. Below is a screenshot of t ...

Display information in an HTML table using JQuery AJAX and JSON data

As a new member and beginner learner, I have encountered some issues while trying to execute a certain task. Despite looking at similar questions, I couldn't find a solution that worked for me. What I am attempting to do is query my database to retrie ...

Resetting passwords in Laravel 5.2: Sending password reset emails using usernames

My argument is that a single user email can be linked to multiple accounts, meaning one email can have multiple usernames associated with it. Currently, my code functions for sending an email directly. However, I want to send an email based on the usernam ...

"After executing a loop in JavaScript using jquery.ajax, the success function does not perform

Having trouble passing values from a PHP file to another function in Javascript. Even after a successful FOR LOOP, nothing seems to work within the SUCCESS block. Any suggestions? url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php'; $ ...

Utilizing the power of $.ajax() to parse through an XML document

I have a query about working with a large XML file containing 1000 nodes. Here is the code snippet I am using: $.ajax({ type: "GET", cache: false, url: "someFile.xml", ...

Sending data from a server using Node.js, Express, and JQuery through a POST request

As someone new to web development, I'm experimenting with Node.js, Express, and EJS to create a weather application that displays the temperature based on a zipcode. So far, retrieving and showing the temperature has been successful. However, I want t ...

Challenges with Laravel and dompdf

I am currently working on developing a web application using Laravel. To generate PDF documents, I have opted to utilize the DOMPDF class created by BarryVDH. You can find more information about this class at this link. However, I encountered an issue in ...

Storing multiple rows of data from a PHP variable into a MySQL table can be achieved

I have a large table with over 750 rows of data that I need to insert into my database efficiently. Currently, I am copying the data as a single string variable and passing it through an AJAX request to be inserted in one line using INSERT INTO query. if( ...

When a specific condition is met, Jquery can automatically execute a function contained

I am trying to slowly reveal the h1 tag using jQuery for demonstration purposes. The scroll function is working when I manually click to initiate it, but I am having trouble triggering it automatically. I feel like I might be missing something simple and ...

Utilizing the foreach loop in PHP to display JSON data from the CoinMarket API

I am having trouble printing JSON data in a PHP foreach loop. I have tried multiple methods but nothing seems to work. The data is coming from the CoinMarket API and I am currently using the following code to print it, however, I am unable to access each v ...

Sending notifications from a PHP server to an Android application using Firebase Cloud Messaging (FCM)

As a novice in PHP, I am attempting to create a program that can send a basic notification (consisting of a title and message) from a localhost using PHP to an Android application through Firebase. While I have successfully sent notifications from FCM to A ...

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

Error in Jquery click event not detecting the correct value

My function is designed to add or remove items from a SQL database upon click. I use a condition to differentiate between adding and removing, but while the add function works perfectly, the remove function does not, even though they share the same code. ...