0

Hi! my first time to post here.
I have a program which asks for user input(img upload and text) then process it using imagecreatefromjpeg. I my uploader, it checks for an array of errors, including if there is no file upload. i want to change it and allow the process to continue.if there is no file upload, it will just use the deafult image. i tried to use something like

if (!is_uploaded_file($_FILES[$fieldname]['tmp_name']))  {

but it's not working. i think there are other codes that shoul be deleted. i've been working on it for hours now.hope u can help me sort it out. thank you!

// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

// make a note of the directory that will recieve the uploaded files //i made it as the same directory where the .php file is
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self;

// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'index.php';

// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';

// name of the fieldname used for the file in the HTML form
$fieldname = 'file';

// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded', 
                2 => 'html form max file size exceeded', 
                3 => 'file upload was only partial', 
                4 => 'no file was attached');

// check the upload form was actually submitted else print form
isset($_POST['submit'])
    or error('the upload form is neaded', $uploadForm);

// check for standard uploading errors
($_FILES[$fieldname]['error'] == 0)
    or error($errors[$_FILES[$fieldname]['error']], $uploadForm);

// check that the file we are working on really was an HTTP upload
@is_uploaded_file($_FILES[$fieldname]['tmp_name'])
    or error('not an HTTP upload', $uploadForm);

// validation... since this is an image upload script we 
// should run a check to make sure the upload is an image
@getimagesize($_FILES[$fieldname]['tmp_name'])
    or error('only image uploads are allowed', $uploadForm);

// make a unique filename for the uploaded file and check it is 
// not taken... if it is keep trying until we find a vacant one
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
    $now++;
}

// now let's move the file to its final and allocate it with the new filename
@move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
    or error('receiving directory insuffiecient permission', $uploadForm);

  //get values
$name = $_POST['name'];
$email = $_POST['email'];
$office_id = $_POST['office_id'];

$get_title = $_POST['title'];
$title = strtoupper ($get_title);
$namehere = "Super Story By " .$_POST['name'];
$story = $_POST['story'];

header('Content-Type: image/jpeg');

$upload = $uploadFilename;
$im = imagecreatefromjpeg("bg.jpg");
$img2 = imagecreatefromjpeg($upload);
$black = imagecolorallocate($im, 0, 0, 0);
$font = 'arialbi.ttf';
$font2 = 'ariali.ttf';

imagettftext($im, 24, 0, 50, 280, $black, $font, $title);
imagettftext($im, 10, 0, 320, 362, $black, $font, $namehere);

imagecopymerge($im, $img2, 30, 350, 0, 0, imagesx($img2), imagesy($img2), 100);

$date_created = date("YmdHis");//get date created
$img_name = "-img_entry.jpg"; //the file name of the generated image
$img_newname = $date_created . $img_name; //datecreated+name
$img_dir =dirname($_SERVER['SCRIPT_FILENAME']) ."/". $img_newname; //the location to save the image 
imagejpeg($im, $img_dir , 80); //function to save the image with the name and quality

$newpath = "/home3/site/public/Amats/image_entry/";
$newdir = $newpath.$img_newname;
copy ($img_dir, $newdir); //copy to new folder para mas madaling iretrieve

$http_dir = 'http://site.com/Amats/image_entry/';
$post_link = $http_dir . $img_newname;

imagedestroy($im);



function error($error, $location, $seconds = 5)
{
    header("Refresh: $seconds; URL=\"$location\"");
    echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
    '"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
    '<html lang="en">'."\n".
    '   <head>'."\n".
    '       <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
    '       <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
    '   <title>Upload error</title>'."\n\n".
    '   </head>'."\n\n".
    '   <body>'."\n\n".
    '   <div id="Upload">'."\n\n".
    '       <h1>Upload failure</h1>'."\n\n".
    '       <p>An error has occured: '."\n\n".
    '       <span class="red">' . $error . '...</span>'."\n\n".
    '       The upload form is reloading</p>'."\n\n".
    '    </div>'."\n\n".
    '</html>';
    exit;

Edited by pritaeas: Moved to PHP

4
Contributors
9
Replies
31
Views
3 Years
Discussion Span
Last Post by karen.frias0316
0

Just wrap your code in an if statement and if there is a file it will run the image processing, otherwise it will just ignore it (then load your default image on the front end)

 if (!empty($_FILES)) {

 }

In fact this should replace your current if statement

0

Poster above me has the right idea but to clarify--

Lines 1-49 in your code are only relevant if the user uploaded a file. And the problem is that in that section of code, there are four image-upload related places where the script will exit if there are any issues with the file upload, such as it not occuring. To fix this so file upload is optional, wrap lines 1-49 in an if statement that will only run if the user uploaded a file(see above post) and then change this section:

$upload = $uploadFilename;
$im = imagecreatefromjpeg("bg.jpg");
$img2 = imagecreatefromjpeg($upload);

Consider definining $upload inside your file upload if statement talked about above, then add an else statement that sets $upload to the path+name of your default image so that if the user didn't upload an image, it'll automatically get set to the default.

Overview draft example:

if(!empty($_FILES)) {
    // Lines 1-49 of your code here
    $imageName = $uploadFilename;
}
else {
    $imageName = 'defaultImage.jpg';
}

// Lines 51-64 here
$img2 = imagecreatefromjpeg($imageName);

Edited by Lsmjudoka

0

Hi Simplypixie,

thanks for answering. i tried using

if(file_exists($uploadFilename))

but i think the problem is in the line of codes 16-32 and 94-111. i believe it forces the user to upload a file. what do you think? thanks again

0

hi Lsmjudoka,

thanks for your answer. i tried it. but i it's returning an error if i dont upload a file. i think lines 16-28 has something to do with it. and 92-111 also? i tried deleting line20 but im getting server error. hope you can help me further. thank you :)

0

I didn't tell you to use if(file_exists($uploadFilename)) I said use if (!empty($_FILES))

So all you should need to do to allow the form to be submitted without an image is change your if statement if (!is_uploaded_file($_FILES[$fieldname]['tmp_name'])) to if (!empty($_FILES)) and inside the if statement run all your checks on image type, reformatting and resizing etc and just ensure that the rest of the form posted data and your insert / update is outside of this if statement.

Your code could actually be much more simple as well and I was going to post what I use but at the moment I combine it with jquery and ajax so would just confuse you more, however a quick search gave me this page which might help you

0

Lines 16-28 should now be enclosed within an if statement that only executes if a file was uploaded. If you're getting an error from there relating to a file not being uploaded, something is wrong with your condition. Probably related to simplypixie's post above this one.

0

Hi Simplypixie and Lsmjudoka. i came up with this code. but now, it's not even uploading the image. please help me further. i am desperate to solve this. thank you.

if(isset($_POST['submit'])){
    if(!empty($_FILES['file']['tmp_name'])){

        $allowedExts = array("jpeg", "jpg");
        $temp = explode(".", $_FILES['file']['name']);
        $extension = end($temp);

        $notallowedExts = array("png", "gif", "pdf", "doc", "docx", "txt", "html", "xlsx", "mov");
        $nottemp = explode(".", $_FILES['file']['name']);
        $notextension = end($nottemp);



        if ((($_FILES['file']['type'] == "image/jpeg")
        || ($_FILES['file']['type'] == "image/jpg"))
        && ($_FILES['file']['size'] < 1300000)
        && in_array($extension, $allowedExts))  {       

          $now = time();
          while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
          {
              $now++;
          }
          move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename);

          $imagename = $uploadFilename;
        }
        elseif(($_FILES['file']['size'] > 1300000)||(in_array($notextension, $notallowedExts))){
                echo '<script type="text/javascript">'; 
                echo 'alert("Invalid file upload. Please check your input.");'; 
                echo 'window.location.href = "index.php";';
                echo '</script>';
                die();
            }
    }
        else{
            $imagename = 'def_img.jpg';
            }
    }


$name = $_POST['name'];
$email = $_POST['email'];
$office_id = $_POST['office_id'];
$var_title = $_POST['title'];
$var_story = $_POST['story'];
$var_task = $_POST['task'];
$var_power = $_POST['power'];
$var_solve = $_POST['solve'];
$var_result = $_POST['result'];



$get_title = $_POST['title'];
$title = strtoupper ($get_title);
$namehere = "Super Story By " .$_POST['name'];
$story = "My super story begins with " . $_POST['story'] . " My task was " . $_POST['task'] ." With the super power of ". $_POST['power'] ." I solved it by ". $_POST['solve'] ." The result was ". $_POST['result'];

if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {


header('Content-Type: image/jpeg');


$imagename = $uploadFilename;
$im = imagecreatefromjpeg("bg.jpg");
$img2 = imagecreatefromjpeg($imagename);

some more codes here
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.