PHP - Php4 Image Upload Script No Longer Works In Php5
So this script did work in previous versions oh php but in php5 I get the error, "Sorry, uploaded images must be of type jpg or jpeg, (not )."
So it looks like it's not recognizing my file as a jpeg?? Any contributions towards a fix are GREATLY appreciated!!! If there are clean, nice (EASY) php5 scripts available for this simple image uploading and thumbnail creation I would consider starting this over. //Listing page code: echo "<form name=\"addCat\" enctype=\"multipart/form-data\" action=\"preview.php\" method=\"post\">"; <INPUT type="file" name="pic1" size="50" value=""> <INPUT type="file" name="pic2" size="50" value=""> <INPUT type="file" name="pic3" size="50" value=""> <INPUT type="file" name="pic4" size="50" value=""> <input type="submit" value="Upload Images"> //preview.php page code: $pic1 = $_FILES['pic1']; $pic2 = $_FILES['pic2']; $pic3 = $_FILES['pic3']; $pic4 = $_FILES['pic4']; function ResizeImage($im,$maxwidth,$maxheight,$name){ $width = imagesx($im); $height = imagesy($im); if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){ if($maxwidth && $width > $maxwidth){ $widthratio = $maxwidth/$width; $RESIZEWIDTH=true; } if($maxheight && $height > $maxheight){ $heightratio = $maxheight/$height; $RESIZEHEIGHT=true; } if($RESIZEWIDTH && $RESIZEHEIGHT){ if($widthratio < $heightratio){ $ratio = $widthratio; }else{ $ratio = $heightratio; } }elseif($RESIZEWIDTH){ $ratio = $widthratio; }elseif($RESIZEHEIGHT){ $ratio = $heightratio; } $newwidth = $width * $ratio; $newheight = $height * $ratio; if(function_exists("imagecopyresampled")){ $newim = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); }else{ $newim = imagecreate($newwidth, $newheight); imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); } ImageJpeg (($newim),$name . ".jpg"); ImageDestroy ($newim); }else{ ImageJpeg ($im,$name . ".jpg"); } } // Set up some variables flush(); set_time_limit(210); // set process page limit to 3.5 minutes $maxfilesize = "102400"; //# individual file size limit - in bytes (102400 bytes = 100KB) $path="2012images"; $thumbpath="thumbs"; // two data pulls to rename images - would be easier to have a permanent counter...fix later $mysql[getpicname] = mysql_query("select pic from picname"); $z = mysql_fetch_array($mysql[getpicname]); $new_filename=$z[pic]; $new_z[pic]=$z[pic]+$total_pics; if(@mysql_query("UPDATE picname SET pic = '$new_z[pic]' ")) echo ""; // Create thumbnail from imgurl and store in thumbs // Height to reszie image to (in pixels) $RESIZEHEIGHT=200; // Width to reszie image to (in pixels) $RESIZEWIDTH=200; //thumbnail to thumbs folder, named same as 1st image $FILENAME=$thumbpath."/".$new_filename; $thumb_name=$thumbpath."/".$new_filename.".jpg"; // create a thumbnail from the first image only $im = imagecreatefromjpeg($_FILES['pic1']['tmp_name']); if($im) { if(file_exists("$pic_1.jpg")) { unlink("$pic_1.jpg"); } if (ResizeImage($im,$RESIZEWIDTH,$RESIZEHEIGHT,$FILENAME)) ImageDestroy ($im); } //now upload the images..... for ($i=1;$i<5;$i++) { //check if blank or image $xpic="pic".$i; if (($$xpic<>"none") and ($$xpic<>"")) { // check if jpg $cert1 = "image/pjpeg"; //jpg $cert2 = "image/jpeg"; //jpg (for MAC) $xtype =$HTTP_POST_FILES[$xpic]['type']; $xsize =$HTTP_POST_FILES[$xpic]['size']; if (($xtype <> $cert1) AND ($xtype <> $cert2)) { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Missing or Invalid Information</DIV><br>"; echo "<DIV class=\"requiredtext\">Sorry, uploaded images must be of type jpg or jpeg, (not $xtype).</DIV><BR>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } if ($xsize > $maxfilesize) { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Missing or Invalid Information</DIV><br>"; echo "<DIV class=\"requiredtext\">Sorry, uploaded images must be under the maximum size requirements.</DIV><BR>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } else { // upload to server $dest=$path."/".$new_filename.".jpg"; If (move_uploaded_file($$xpic, $dest)) { $photo[$i]=$dest; $new_filename+=1; } else { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Upload Failed!</DIV><br>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } // upload sucessful } // end type check } // end check if blank } Similar TutorialsI'm sure there is a very simple fix to this problem. I have an image uploader in the backend of my site. Since moving hosts this no longer works. The PHP is if((!empty($_FILES["indeximage"]))) { $indeximagename = basename($_FILES['indeximage']['name']); $indeximagenew = $_SERVER['DOCUMENT_ROOT'] . '/images/uploaded/index/' . $indeximagename; if (!file_exists($indeximagenew)) { if ((move_uploaded_file($_FILES['indeximage']['tmp_name'], $indeximagenew)) === true) { echo $indeximagename; echo ' was successfully uploaded.'; }else { echo 'Unable to move'; echo $indeximagename; echo ' into the right folder.'; } }else { echo 'You did not upload an index image.'; } } I'm guessing the problem is with the document root part. $indeximagenew echos /var/www/vhosts/webaddress.co.uk/httpdocs/images/uploaded/index/imagename.jpg The actual actual address of the image, when on the site, is http://www.webaddress.co.uk/images/uploaded/index/imagename.jpg Any help would be great! I have an application that was written back in PHP4 days and has ceased development ever since. PHP 4 is basically gone, i can't get it to install on any of my machines now and what i use on my windows boxes (XAMPP) doesn't include PHP4 anymore. When i set everything up, i get ~50 of these: Deprecated: Assigning the return value of new by reference is deprecated in.... and on every line it looks like: $var =& _____ or $var = &something... yada-yada and removing the & symbol removes the error message. Using editplus i removed all the "=&" and "= &" and just replaced the & with space, i had read on google PHP5 doesn't need it anymore so that should've worked. But as my luck would have it, the server errors out with 500 code until i replace all the &'s back, and then the errors show up yet again. Is there anyway to force php5 to run this program despite having php4 things in it? I have a small php upload/download script, it always worked on older php4 -5 but not on php5.3 ,gobal varitables must be on , I dont know to much about php and was hoping someone will look at at and let me know what to change to make it work on php5.3 or higher..............................THANKS! for any help in fixing this issue
<body link="#FFFF00" vlink="#FF0000" alink="#FFFF00"><? $extlimit = "yes"; //Do you want to limit the extensions of files uploaded $limitedext = array(".zip",".sim",".car",".jpg",".gif"); //Extensions you want files uploaded limited to. $sizelimit = "no"; //Do you want a size limit, yes or no? $sizebytes = "30033000"; //size limit in bytes $dl = "xxxxxxxxxxx"; //url where files are uploaded $absolute_path = "xxxxxxxxxxx"; //Absolute path to where files are uploaded $websiteurl = "xxxxxxxx"; //Url to you website $websitename = "Car File Manger"; if (!isset($action)) { $action = ""; } switch($action) { default: echo" <html> <head> <title>Upload Or Download</title> </head> <body> <a href=$PHP_SELF?action=upload>Upload</a> | <a href=$PHP_SELF?action=download>Download</a> | <a href=$websiteurl>Return to $websitename</a> <br><br> </body> </html>"; break; case "download": echo " <html> <head> <title>File Download</title> </head> <body><a href=$PHP_SELF?action=upload>Upload File</a> | <a href=$websiteurl>Return to $websitename</a>"; $list = "<table width=500 border=0 bordercolor=#000000 style=\"border-collapse: collapse\">"; $list .= "<tr><td width=500><center><b>Click To Download</b></center></td></tr>"; $dir = opendir($absolute_path); while($file = readdir($dir)) { if (($file != "..") and ($file != ".")) { //Download files with spaces fix by Kokesh $list .= "<tr><td width=700><a href='$dl/$file'>$file</a></center></td></tr>"; } } $list .= "</table>"; echo $list; echo" <br><br> </body> </html>"; break; case "upload": echo" <html> <head> <title>File Upload</title> </head> <body> <form method=POST action=$PHP_SELF?action=doupload enctype=multipart/form-data> <p>File to upload:<br> <input type=file name=file size=30> <p><button name=submit type=submit> Upload </button> </form> <br><br> </body> </html>"; break; //File Upload case "doupload": $dir = "dir"; if ($file != "") { if (file_exists("$absolute_path/$file_name")) { die("File already exists"); } if (($sizelimit == "yes") && ($file_size > $sizebytes)) { die("File is to big. It must be $sizebytes bytes or less."); } $ext = strrchr($file_name,'.'); if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { die("The file you are uploading doesn't have the correct extension."); } @copy($file, "$absolute_path/$file_name") or die("The file you are trying to upload couldn't be copied to the server"); } else { die("Must select file to upload"); } echo " <html> <head> <title>File Uploaded</title> </head> <body>"; echo $file_name." was uploaded"; echo "<br> <a href=$PHP_SELF?action=upload>Upload </a> | <a href=$PHP_SELF?action=download> Download </a> | <a href=$websiteurl> Return to $websitename</a><br><br> </body> </html>"; break; } ?> Edited by Ch0cu3r, 01 September 2014 - 06:05 AM. Hi... I could really do with some help, I have some form code I have been using for a very long time. how every my server company will not install php4 anymore Can someone have a look at this code and let me know why its not php5 compatible. Thanks <?php /* $sendto is the email where form results are sent to */ $sendto = "........"; /* $ccto is the email where form results can be carbon copied to */ $ccto = "..........."; /* O P T I O N A L V A R I A B L E S */ /* TO POST PHP ERRORS TO PAGE FOR DEBUGING SET: $report_errors = "ALL"; TO REMOVE PHP ERRORS FROM POSTING TO THE PAGE FOR USE SET: $report_errors = "NONE"; */ $report_errors = "NONE"; $setokurl = "1"; $okurls = "http://www.dwcontractors.com"; if ($report_errors == "NONE") { error_reporting(0); }else{ error_reporting(E_ALL); } /* --- I F S E T O K U R L = 1 ----- */ if ($setokurl == "1"){ $found_url = "0"; $referer =$_SERVER["HTTP_REFERER"]; $referer = str_replace("://", "[CS]", $referer); $referer_sp = explode("/", $referer); $referer = "$referer_sp[0]"; $referer .= "/"; $referer = str_replace("[CS]", "://", $referer); $referer = strtolower($referer); $okurls = split(",", $okurls); foreach ($okurls as $myokurls) { $myokurls = strtolower($myokurls); if ($referer == strtolower($myokurls)) { $found_url = "1"; } } if ($found_url == "0") { $ERROR_action = "bad_okurl"; include("$PATH_error$PAGE_error"); } } /* --- E N D I F S E T O K U R L = 1 --- */ /* check to see if posted */ if ($HTTP_GET_VARS || ! $HTTP_POST_VARS || $_GET || ! $_POST) { include("nverror.php4"); no_pst(); }else{ /* IF OLDER VERSION OF PHP CONVERT TO NEWER VARIABLES */ if (! $_POST) { $_POST = "$HTTP_POST_VARS"; } if (! $_SERVER) { $_SERVER = "$HTTP_SERVER_VARS"; } $year = date("Y"); $month = date("m"); $day = date("d"); $hour = date("h"); $min = date("i"); $tod = date("a"); $ip=$_SERVER["REMOTE_ADDR"]; $SEND_prnt = "The form below was submited by " . $_POST{"email"} . " from Ip address: $ip on $monthnameactual $month/$day/$year at $hour:$min $tod \n"; $SEND_prnt .= "--- DW Contractors ---\n\n"; /* CHECK TO SEE IF $_POST{"required"} IS SET */ if ($_POST{"required"}){ $post_required = $_POST{"required"}; $required = split(",", $post_required); $reqnum = count($required); for ($req=0; $req < $reqnum; $req++) { $REQ_name = $required[$req]; $REQ_value = $POST{"$REQ_name"}; if ($REQ_name == "email") { $goodem = ereg("^[^@ ]+@[^@ ]+\.[^@ \.]+$", $_POST{"email"}, $trashed); if (! $goodem) { include("nverror.php4"); msng_email(); } /* end ! $goodem */ } elseif (! $_POST{"$REQ_name"}) { $isreqe = "1"; $REQ_error .= "<li> $REQ_name "; } /* end ! req val */ } /* end REQ for loop */ /* IF THERE ARE ANY REQUIRED FIELDS NOT FILLED IN */ if ($isreqe == "1") { include("nverror.php4"); msng_required(); } } /* END CHECK TO SEE IF $_POST{"required"} IS SET */ /* END IF THERE ARE ANY REQUIRED FIELDS NOT FILLED IN */ /* GET POSTED VARIABLES */ foreach ($_POST as $NVPOST_name => $NVPOST_value) { $NVPOST_value = str_replace("\n", "", $NVPOST_value); $NVPOST_value = str_replace("\r", "", $NVPOST_value); $NVPOST_value = preg_replace("'\cc:'si", "Cc ", $NVPOST_value); $NVPOST_value = preg_replace("'\bcc:'si", "bcc ", $NVPOST_value); $NVPOST_value = preg_replace("'\to:'si", "to ", $NVPOST_value); $NVPOST_value = preg_replace("'\bc:'si", "bc ", $NVPOST_value); if (strtolower($NVPOST_name) == "subject") { $NVPOST_value = str_replace(":", ";", $NVPOST_value); } /* G E T E M A I L */ if (strtolower($NVPOST_name) == "email") { $SEND_email = "$NVPOST_value"; $SEND_email = str_replace(":", "", $SEND_email); $SEND_email = str_replace(" ", "", $SEND_email); } /* END GET LEADS EMAIL */ if (! $_POST{"sort"}) { /* CHECK TO SEE IF CONFIG FIELD */ if ($NVPOST_name == "subject" || $NVPOST_name == "sort" || $NVPOST_name == "required" || $NVPOST_name == "success_page"){}else{ $SEND_prnt .= "$NVPOST_name: $NVPOST_value \n\n"; } } /* end ! sort */ } /* end foreach */ /* END GET POSTED VARIABLES */ if ($_POST{"sort"}) { /* SORT VARIABLES */ $sortvars = split(",", $_POST{"sort"}); $sortnum = count($sortvars); for ($num=0; $num < $sortnum; $num++) { $SEND_prnt .= "$sortvars[$num]: " . $_POST{"$sortvars[$num]"} . " \n\n"; } } /* END SORT VARIABLES */ /* send mail */ if (! $ccto) { $header = "From: $SEND_email\r\nReply-to: $SEND_email"; }else{ $header = "From: $SEND_email\r\nReply-to: $SEND_email\r\nCc: $ccto"; } mail($sendto, $_POST{"subject"}, $SEND_prnt, $header); /* END sendmail */ /* CHECK TO SEE IF FORM SPECIFYS A SUCCESS PAGE */ if (! $_POST{"success_page"}) { include("nverror.php4"); default_success(); }else{ $successpage=$_POST{"success_page"}; header("Location: $successpage"); /* redirect */ exit; } } /* END IF POSTED */ ?> I just finished (or so I thought) a project. But my client's server runs PHP4, so I need to adapt my code. Here's what stopped working: Code: [Select] $localClasses = new DOMDocument; $localClasses -> load("file.xml"); $localClasses -> get_elements_by_tagname('Title') -> item(0) -> firstChild -> nodeValue Here's my petty attempt at trying to adapt this code to run in PHP4: Code: [Select] $file = file_get_contents("localClasses.xml"); $localClasses = new DOMDocument($file); $test = $localClasses -> get_elements_by_tagname('Title'); $testText = $test -> item[0] -> firstChild -> nodeValue; print $testText; This doesn't give me any errors, but nothing shows up. Any help would be appreciated. Thanks for reading! I am trying to convert a php4 app to php5 and am getting this error (Fatal error: Cannot re-assign $this in ) when I call this class. $this = $this->createUnique($new); is the line that generates the error. I try to rename $this to $_this but it does not help. I think I lose the reference to the object later on in the code. Then I will get an error like (Fatal error: Call to a member function createUnique() on a non-object in) Is there another way to reference the current instance of an object in php5? Any help appreciated... Code Example: Code: [Select] class imageobject{ var $handle; var $height=0; var $width=0; var $directory; var $filename; //constructor function imageobject($directory,$filename,$width=0,$height=0,$color="FFFFFF") { $this->directory = $directory; $this->filename = $filename; if ($filename=="" && $width>0 && $height>0){ $new = $this->createImage($width,$height); $this = $this->createUnique($new); }elseif (file_exists($directory.$filename)){ $size = GetImageSize($directory.$filename); if ($size) $this->handle = $this->getHandle($directory.$filename,$size[2]); $this->width = $size[0]; $this->height = $size[1]; } function createUnique($imgnew) { $this->type = substr($this->output,0,3); $unique_str = $this->uniqueName(); switch ($this->type){ case "png": imagepng($imgnew,RES_DIR.$unique_str); break; default: imagejpeg($imgnew,RES_DIR.$unique_str,$this->quality); break; } $this->handle && imagedestroy($this->handle); $newobject = new imageobject(RES_DIR,$unique_str,$this->type); return $newobject; } )//end class I have had a problem with some scripts I wrote (Screenscrapers) that worked great in PHP4, but stopped working the minute I upgraded to PHP5. I can change all of my filenames to have the .PHP4 extension and this solves the problem, but since this encompasses a number of sites, internal links and hundreds of files, this is not my first choice solution. Here is the scraper, what it does, is it takes items from the zazzle Results Page by category, strips out the formatting, adds my affiliate ID and then I can present these items on my page. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Test of scrape</title> <link rel="stylesheet" type="text/css" href="/css/scraper.css" /> <script type='text/javascript' src='http://www.zazzle.com/js/logging/omniture/s_code.zjs/r-52.78223/site-zazzle.js'></script> </head> <body> <div class="gridCell " id="page_productsGrid_assetCell1"> <?php $page = file_get_contents("http://www.zazzle.com/cool+smiley+gifts"); //comment out the <span> tags completely $page = preg_replace('/<span/', "<!-- <span", $page); $page = preg_replace('/<\/span>/', "<\/span> -->", $page); $page = preg_replace('/<a /', "<a rel=\"nofollow\" ", $page); $rf_id="238219236805025733"; // Regular expression to parse "&rf=" and the $rf_id into the existing link $page=preg_replace("/(.*?)(href\s*=+\s*[\"\'])(.*?)([\"\'])(.*?)/is","$1$2$3?rf=$rf_id$4$5",$page); $test = explode('<div style="position:relative" class="clearfix">',$page); for($t=1;$t<=count($test)-2;$t++){ print "<div class=\"gridCellInfo\" id=\"page_products\">"; print $test[$t]; } ?> </body> </html> This works find in PHP4; not at all in PHP5. My ideal solution would be an .htaccess file that I could put in any directory under PHP5 to make it default to php4. I have tried this, to no avail (.htaccess): Code: [Select] <IfModule mod_rewrite.c> RewriteEngine On AddType text/html .php4 AddHandler php4-script .php .html php5 </IfModule> I have also tried a few alternatives... this appears to be a common problem and I have scoured the web and found no solution. Here are the two pages in PHP4 and PHP5: php4: http://www.killersmiley.com/test/cool-smiley.php4 php5: http://www.killersmiley.com/test/cool-smiley.php Hi, I have tried to merge two queries into one however a piece of code keeps coming up with an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource. It relates to this. I cant see it doesn't work and I have tried around 10 different options but this is the nearest I can get. Can anyone advise me what the problem is and why this no longer works please? while($row = mysql_fetch_assoc($myQuery)) <?php ini_set('display_errors', 1); error_reporting(-1); if( isSet($_GET['description'])) $description = $_GET['description']; if(isSet($_GET['price'])) $price = explode('-',$_GET['price']); $low = (int)$price[0]; $high = (int)$price[1]; ($myQuery = "SELECT * FROM productfeed WHERE 1 . if(isset($description)) ' AND if description = '. $description; if(isset($price)) ' AND if price = '. $price; . "); while($row = mysql_fetch_assoc($myQuery)) { $id = $row['id']; $image = $row['awImage']; $link = $row['link']; $description = $row['description']; $fulldescription = $row['fulldescription']; $price = $row['price']; $fulldescription = substr("$fulldescription", 0, 400); echo "<div class='productdisplayshell'> <div class='productdisplayoutline'> <div class='productborder'><center> <a href='$link' target='_blank'><img src='$image' width=\"95%\" /></a> </center> </div></div> <div class='productdescriptionoutline'> <div class='productdescriptionbox'> <a href='$link' target='_blank' >$description</a> </div> <div class='productfulldescriptionbox'>$fulldescription</div> </div> <div class='productpriceoutline'> <div class='productpricebox'> <center>&#163; $price</center> </div> <div class='productbuybutton'> <center><a href='$link' target='_blank' ><img src=/images/buybutton.png /></a></center> </div> </div> </div>"; } Well the subject line is pretty explicit. I found this script that uploads a picture onto a folder on the server called images, then inserts the the path of the image on the images folder onto a VACHAR field in a database table. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> The script seems to work fine because I managed to upload a picture which was successfully inserted into my images folder and into the database. Now the problem is, I can't figure out exactly how to write the script that displays the image on an html page. I used the following script which didn't work. Code: [Select] //authenticate user //Start session session_start(); //Connect to database require ('config.php'); $sql = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($sql); $imagebytes = $row['image']; header("Content-type: image/jpeg"); print $imagebytes; Seems to me like I need to alter some variables to match the variables used in the insert script, just can't figure out which. Can anyone help?? $account="54646456456464"; $station= "12345"; $options="11-1"; $image="C:/Desktop/Sample Images/usco1.jpg"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://dfdgfsfs.com/kgdfgd.php"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'image' => '@'.$image, 'account' => $account, 'station' => $station, 'options' => $options)); $postResult = curl_exec($ch); curl_close ($ch); $xmlobj = simplexml_load_string($postResult); echo (string)$xmlobj->ID->attributes()->value; echo (string)$xmlobj->FullName->attributes()->value;All, I have spend days trying to figure this out without any luck. I am now in crisis mode. I need to get this working asap. The following code works perfect on my local xampp machine. As soon as I upload it to my web server, I don't get any data back. I have narrowed it down to the image i am trying to send is not being received properly. Thanks in advance. hello i am adding an image upload script, so users can upload a image with the recipe they are adding, but my script seems to not work, these are the files. add_recipe.php <?php // Start_session, check if user is logged in or not, and connect to the database all in one included file include_once("scripts/checkuserlog.php"); // Include the class files for auto making links out of full URLs and for Time Ago date formatting include_once("wi_class_files/autoMakeLinks.php"); include_once ("wi_class_files/agoTimeFormat.php"); // Create the two objects before we can use them below in this script $activeLinkObject = new autoActiveLink; $myObject = new convertToAgo; ?> <?php // Include this script for random member display on home page include_once "scripts/homePage_randomMembers.php"; ?> <?php $sql_blabs = mysql_query("SELECT id, mem_id, the_blab, blab_date FROM blabbing ORDER BY blab_date DESC LIMIT 30"); $blabberDisplayList = ""; // Initialize the variable here while($row = mysql_fetch_array($sql_blabs)){ $blabid = $row["id"]; $uid = $row["mem_id"]; $the_blab = $row["the_blab"]; $notokinarray = array("fag", "gay", "shit", "fuck", "stupid", "idiot", "asshole", "cunt", "douche"); $okinarray = array("sorcerer", "grey", "shug", "farg", "smart", "awesome guy", "asshole", "cake", "dude"); $the_blab = str_replace($notokinarray, $okinarray, $the_blab); $the_blab = ($activeLinkObject -> makeActiveLink($the_blab)); $blab_date = $row["blab_date"]; $convertedTime = ($myObject -> convert_datetime($blab_date)); $whenBlab = ($myObject -> makeAgo($convertedTime)); //$blab_date = strftime("%b %d, %Y %I:%M:%S %p", strtotime($blab_date)); // Inner sql query $sql_mem_data = mysql_query("SELECT id, username, firstname, lastname FROM myMembers WHERE id='$uid' LIMIT 1"); while($row = mysql_fetch_array($sql_mem_data)){ $uid = $row["id"]; $username = $row["username"]; $firstname = $row["firstname"]; if ($firstname != "") {$username = $firstname; } // (I added usernames late in my system, this line is not needed for you) /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $ucheck_pic = "members/$uid/image01.jpg"; $udefault_pic = "members/0/image01.jpg"; if (file_exists($ucheck_pic)) { $blabber_pic = '<div style="overflow:hidden; width:40px; height:40px;"><img src="' . $ucheck_pic . '" width="40px" border="0" /></div>'; // forces picture to be 100px wide and no more } else { $blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" height=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more } $blabberDisplayList .= ' <table width="100%" align="center" cellpadding="4" bgcolor="#CCCCCC"> <tr> <td width="7%" bgcolor="#FFFFFF" valign="top"><a href="profile.php?id=' . $uid . '">' . $blabber_pic . '</a> </td> <td width="93%" bgcolor="#EFEFEF" style="line-height:1.5em;" valign="top"><span class="greenColor textsize10">' . $whenBlab . ' <a href="profile.php?id=' . $uid . '">' . $username . '</a> said: </span><br /> ' . $the_blab . '</td> </tr> </table>'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta name="Description" content="Web Intersect is a deft combination of powerful free open source software for social networking, mixed with insider guidance and tutorials as to how it is made at its core for maximum adaptability. The goal is to give you a free website system that has a network or community integrated into it to allow people to join and interact with your website when you have the need." /> <meta name="Keywords" content="web intersect, how to build community, build social network, how to build website, learn free online, php and mysql, internet crossroads, directory, friend, business, update, profile, connect, all, website, blog, social network, connecting people, youtube, myspace, facebook, twitter, dynamic, portal, community, technical, expert, professional, personal, find, school, build, join, combine, marketing, optimization, spider, search, engine, seo, script" /> <title>CookBookers</title> <link href="style/main.css" rel="stylesheet" type="text/css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <style type="text/css"> #Layer1 { height:210px; } body { background-color: #3c60a4; } .style4 {font-size: 36px} </style> </head> <body> <p> <?php include_once "header_template.php"; ?> </head> <body style="margin:0px;"> <center> </p> <p> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td width="124" valign="top"> <td width="776" colspan="2" align="left" valign="top" style="background-color:#EFEFEF; border:#999 0px; padding:10px;"> <table border="0" cellpadding="6"> </table> <table width="574" border="0"> <form enctype="multipart/form-data" action="include/recipe.php" method="post"> <span class="style4">Add Recipie</span> <tr> <th width="232" scope="col"></th> <th width="332" scope="col"> </th> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Public:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="Pub" value="1" type="checkbox" id="Pub"/> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Title:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="title" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Prep time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="prep" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Cooking time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="cook" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Makes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="make" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Ingrediants:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="ingr" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Method: </span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="desc" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Notes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="note" cols="40"></textarea> </span></td> </tr> <tr> <td><input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> Choose a picture to upload: <input name="uploaded_file" type="file" /></td> </tr> <tr> <td><input name="submit" type="submit" style="padding:5px 10px;" value="Submit" /></td> </tr> <tr> <td> </td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> recipe.php (upload form script) <?php //include("session.php"); include("database.php"); @session_start(); $user = $_SESSION['username']; mysql_real_escape_string($user); //die($user); $Pub=$_POST['Pub']; $title=$_POST['title']; $prep=$_POST['prep']; $cook=$_POST['cook']; $make=$_POST['make']; $ingr=$_POST['ingr']; $desc=$_POST['desc']; $note=$_POST['note']; //if($user=="Guest"||$user==""){ //header("Location: ../index.php"); //} //else{ $database->AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc,$note); $uploaded_file=$_POST['files']['uploaded_file'] //Сheck that we have a file if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/upload/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "It's done! The file has been saved as: ".$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 350Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } header("Location: ../recipe_added.php"); //} ?> Hi All Not so much help as here is a handy class for uploading images Please feel free to find security bugs and let me know. Also feel free to use it if you want. http://onlyican.com/test_samples/bl_upload_img.phps To use the class, simply use the following require_once('bl_upload_img.php'); $objUploadImg = new UploadImg(); //Set values here if you wish such as $objUploadImg->setFormField('myFormField'); // The Name from <input type="file" name="myFormField" /> $objUploadImg->setSaveDirMain($_SERVER['DOCUMENT_ROOT'].'/MyImageFolder'; //Make sure to set the permissions //You can change most settings, just look at the function setDetaultValues() to get the function name //Now upload the image if($objUploadImg->uploadImage()){ $strFileName = $objUploadImg->getFileNameMain(); }else{ echo 'Error uploading Image<br />'.$objUploadImg->getErrorMessage(); } Hey guys!! i'm after a bit of help with a script i am using for simple image upload to server. At the moment the script works fine and will allow upload of JPG files, i want to extend on this to allow GIF and PNG files to be uploaded aswell. This is the script i am using... <?php //?heck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 600Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 600000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/uploads/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "Upload Complete! You can use the following link in the IMS:" .$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 600Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } // $sessionid=session_id() //$newname=$_SESSION['session_name'] header( 'Location: success.php?newname1='.$filename ) ; ?> Any help would be appriciated!! ta!! jonny Hi all! I have a problem with an image uploading script and at the moment it keeps the image name the same, obviously people don't have very adventurous names for their images "image1" and they are over writing each other. How do I put a random 5 digit number on the end to make them all unique? Thanks. Code: [Select] $image1 = mysql_real_escape_string("$idir" . $_FILES['fupload2']['name']); $image2 = mysql_real_escape_string("$idir" . $_FILES['fupload3']['name']); $image3 = mysql_real_escape_string("$idir" . $_FILES['fupload4']['name']); $logo = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $idir = "uploads/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], "$idir" . $_FILES['fupload']['name']); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload2'])){ //upload the image to tmp directory $url = $_FILES['fupload2']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload2']['type'] == "image/jpg" || $_FILES['fupload2']['type'] == "image/jpeg" || $_FILES['fupload2']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload2']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload2']['tmp_name'], "$idir" . $_FILES['fupload2']['name']); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload3'])){ //upload the image to tmp directory $url = $_FILES['fupload3']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload3']['type'] == "image/jpg" || $_FILES['fupload3']['type'] == "image/jpeg" || $_FILES['fupload3']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload3']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload3']['tmp_name'], "$idir" . $_FILES['fupload3']['name']); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload4'])){ //upload the image to tmp directory $url = $_FILES['fupload4']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload4']['type'] == "image/jpg" || $_FILES['fupload4']['type'] == "image/jpeg" || $_FILES['fupload4']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload4']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload4']['tmp_name'], "$idir" . $_FILES['fupload4']['name']); // Move Image From Temporary Location To Permanent Location } } Hello, My upload script is working for the most part and while I know that I need a couple of little fixes and will need help with those I also wouldn't mind some tips on how I could have written it better in the first place. The 2 problems I am having. 1. If the copy image fails the script doesn't and still creates a database entry. I would like to stop it from doing that but can't seem to work it out. 2. My mate is getting file type errors even though he is trying to upload small .jpg files. I can't seem to recreate the problem. Maybe someone can see something that might be problematic?? Code: [Select] <? $idir = "../rosysartworks/gallery/"; // Path To Images Directory $tdir = "../rosysartworks/gallery/thumbs/"; // Path To Thumbnails Directory $iwidth = "600"; // Maximum Width For Thumbnail Images $iheight = "600"; // Maximum Height For Thumbnail Images $twidth = "233"; // Maximum Width For Thumbnail Images $theight = "178"; // Maximum Height For Thumbnail Images ?> <? // Catching the inputs $title = Trim(stripslashes($_POST['title'])); $paypal = Trim(stripslashes($_POST['paypal'])); // Check if the form has been submitted. if (isset ($_POST['submit'])) { $problems = FALSE; // No problems so far. // Check for each value. if (empty ($title)) { $problem = TRUE; $problems = 'You forgot to enter a title!<br />'; } if (empty ($paypal)) { $problem = TRUE; $problems = 'You forgot to enter a paypal link!<br />'; } if (!$problem) { // If there are no problems... // Uploading/Resizing Script $url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/JPG") { $file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $_FILES['imagefile']['name']); // Move Image From Temporary Location To Permanent Location if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location // Resize for preview image. $simg = imagecreatefromjpeg("$idir" . $url); // Make A New Temporary Image To Create The Thumbanil From $currwidth = imagesx($simg); // Current Image Width $currheight = imagesy($simg); // Current Image Height if ($currwidth > $iwidth && $currheight > $iheight) { $newwidth = $iwidth; $newheight = $newwidth * $currheight / $currwidth; if ($newheight > $iheight) { $newheight = $iheight; $newwidth = $newheight * $currwidth / $currheight; } $dimg = imagecreatetruecolor($newwidth, $newheight); // Make New Image For Preview imagetruecolortopalette($simg, false, 256); // Create New Color Pallete $palsize = ImageColorsTotal($simg); for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image $colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use } imagecopyresampled($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It) $success = imagejpeg($dimg, "$idir" . $url, 100); // Saving The Image imagedestroy($simg); // Destroying The Temporary Image imagedestroy($dimg); // Destroying The Other Temporary Image if ($success) { print 'Preview image '.$url.' width: '.$newwidth.' height: '.$newheight.' created successfully.<br />'; // Resize successful for preview image unset($success); } } else { unset($simg, $currwidth, $currheight); } // Resize for thumbnail $simg = imagecreatefromjpeg("$idir" . $url); // Make A New Temporary Image To Create The Thumbanil From $currwidth = imagesx($simg); // Current Image Width $currheight = imagesy($simg); // Current Image Height $newwidth = $twidth; $newheight = $newwidth * $currheight / $currwidth; if ($newheight > $theight) { $newheight = $theight; $newwidth = $newheight * $currwidth / $currheight; } // maxWidth: mw, maxHeight: mh, oldHeight: oh, oldWidth: ow, newHeight: nh, newWidth: nw. // nw = mw; nh = nw * oh / ow; // if (nh > mh) { nh = mh; nw = nh * ow / oh } $dimg = imagecreatetruecolor($newwidth, $newheight); // Make New Image For Thumbnail imagetruecolortopalette($simg, false, 256); // Create New Color Pallete $palsize = ImageColorsTotal($simg); for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image $colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use } imagecopyresampled($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It) $success = imagejpeg($dimg, "$tdir" . $url, 100); // Saving The Image imagedestroy($simg); // Destroying The Temporary Image imagedestroy($dimg); // Destroying The Other Temporary Image if ($success) { print 'Image thumbnail '.$url.' width: '.$newwidth.' height: '.$newheight.' created successfully.'; // Thumbnail created successfully } } else { print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed } // End upload at copy failure } else { print 'Failed to copy image to temp location.'; } } else { print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong print $file_ext; // Show The Invalid File's Extention print '.</font>'; } // End upload script // Define the query. $add_new_session = $sql = "INSERT INTO `gallery` ( `id` , `title` , `image` , `thumb` , `width` , `height` , `paypal` , `date_entered` ) VALUES ( 0, '".mysql_real_escape_string(($title))."', '".mysql_real_escape_string(($url))."', '".mysql_real_escape_string(($url))."', '".mysql_real_escape_string(($newwidth))."', '".mysql_real_escape_string(($newheight))."', '".mysql_real_escape_string(($paypal))."', NOW() )"; // execute the query. if (@mysql_query ($add_new_session)) { print "<p>The new gallery image $url has been added.</p>"; unset($sessionName, $maxAttendees, $newwidth, $newheight); $hidden = 'hidden'; } else{ print '<a name="formTop"></a>'.'<p class="error">Your session has failed to upload. Please contact website support.</p>'; echo $add_new_session; } } else { // Forgot a field. // print '<p>Please try again!</p>'; $problems .= '<a name="formTop"></a>'.'Please try again!<br />'; if ($problem) { print '<p class="error">' . $problems . '</p>'; } } // End of handle form IF // Display the form print '<h2>Upload New Image</h2>' . '<p>Please only try uploading .jpg images</p>' . '<form method="post" action="index.php" enctype="multipart/form-data">' . '<label>Title:</label>' . '<input type="text" name="title" class="form">' . '<br />' . '<label>Image:</label>' . '<input type="file" name="imagefile" class="form">' . '<br />' . '<label>Paypal Link:</label>' . '<input type="text" name="paypal" class="form" size="50">' . '<br /><br />' . '<input name="submit" type="submit" value="Sumbit" class="form">' . '<input type="reset" value="Clear" class="form">' . '</form>'; ?> Hi guys, I've got an image uploader based on Uploadify, first let me set out what I want the script to do and what it currently does/doesn't do: Upload files of various types into folders named with the Order ID - OK Process the files by checking the file type and acting accordingly - OK Create thumbnails of the images in the /thumbs subdirectory - OK If the file is a PDF, create JPEG images of all pages and subsequent thumbnails - OK If the file is a ZIP, unzip and re-process the contents based on the above rules - FAIL As you can see I'm nearly at the end of my wishlist with this script, currently when it receives a ZIP file is unzip's it correctly placing the contents in the parent (Order-ID) directory however I'm then left with the same situation I have at the very beginning of the script, for example: File in -> "What kind of file are you?" -> Process file based on the answer. What I need to do is: File in -> "What kind of file are you? Oh! a Zip File, let's unzip and ask the same question of the contents!" -> Process contents. So basically I need to ask the same question twice, once of the zip and once of the contents of the unzipped file. This is where I'm struggling, someone told me to use a function which I tried but it kept breaking and I wasn't sure why. Therefore I have attached 2 files. 1 which currently works 99% except for "asking the question again" and one which doesn't work but I was told is the right way to do it File 1: Works 99%. Code: [Select] <?php /* TomBigFile v2.0 Based on Uploadify v2.1.4 Automatic folder creation dependant on order number with a thumbnail subdirectory. All files in are subject to a process which determines their type and acts accordingly. PDF's are automatically converted on the fly to 2 sets of JPEG's and stored accordingly to be accessed by Customer Accounts and Sales Order details area. Revised May 2011 */ // RECEIVE THE DATA FROM THE UPLOAD AND ASSIGN THE VARIABLES if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name']; // $fileTypes = str_replace('*.','',$_REQUEST['fileext']); // $fileTypes = str_replace(';','|',$fileTypes); // $typesArray = split('\|',$fileTypes); // $fileParts = pathinfo($_FILES['Filedata']['name']); // if (in_array($fileParts['extension'],$typesArray)) { // CREATE THE PARENT DIRECTORY BASED ON ORDER ID AND THE THUMBS SUBDIRECTORY mkdir(str_replace('//','/',$targetPath), 0755, true); mkdir($targetPath . "thumbs", 0755, true); // create thumbs dir move_uploaded_file($tempFile,$targetFile); echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile); // } else { // echo 'Invalid file type.'; // } } // BEGIN CHECKING THE IMAGE LOOKING AT THE FILE TYPE AND ACTING ACCORDINGLY $imgsize = getimagesize($targetFile); switch(strtolower(substr($targetFile, -3))){ case "pdf": $large = substr_replace($targetFile , 'jpg', strrpos($targetFile , '.') +1); $thumbnail = dirname($large).'/thumbs/'.basename(substr($large, 0, -4)."_thumb".strtolower(substr($large, -4))); $cmd = "$targetFile -write $large -thumbnail 64x64 $thumbnail "; exec("convert $cmd "); exit; break; case "jpg": $image = imagecreatefromjpeg($targetFile); break; case "png": $image = imagecreatefrompng($targetFile); break; case "gif": $image = imagecreatefromgif($targetFile); break; case "zip": $zip = new ZipArchive(); $zip->open($targetFile); $zip->extractTo($targetPath); $zip->close(); break; default: exit; break; } $width = 60; //New width of image $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions $src_w = $imgsize[0]; $src_h = $imgsize[1]; $picture = imagecreatetruecolor($width, $height); imagealphablending($picture, false); imagesavealpha($picture, true); $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); // SAVE THE IMAGE(S) if($bool){ switch(strtolower(substr($targetFile, -3))){ case "jpg": //header("Content-Type: image/jpeg"); $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "png": //header("Content-Type: image/png"); imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "gif": //header("Content-Type: image/gif"); imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; } } imagedestroy($picture); imagedestroy($image); echo '1'; // Important so upload will work on OSX ?> File 2: Doesn't work for me but I was told is correct method(s). Code: [Select] <?php /* TomBigFile v2.0 Based on Uploadify v2.1.4 Automatic folder creation dependant on order number with a thumbnail subdirectory. All files in are subject to a process which determines their type and acts accordingly. PDF's are automatically converted on the fly to 2 sets of JPEG's and stored accordingly to be accessed by Customer Accounts and Sales Order details area. Revised May 2011 */ if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name']; // $fileTypes = str_replace('*.','',$_REQUEST['fileext']); // $fileTypes = str_replace(';','|',$fileTypes); // $typesArray = split('\|',$fileTypes); // $fileParts = pathinfo($_FILES['Filedata']['name']); // if (in_array($fileParts['extension'],$typesArray)) { // Uncomment the following line if you want to make the directory if it doesn't exist mkdir(str_replace('//','/',$targetPath), 0755, true); mkdir($targetPath . "thumbs", 0755, true); // create thumbs dir move_uploaded_file($tempFile,$targetFile); echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile); // } else { // echo 'Invalid file type.'; // } } // start again here after ZIP!!!! function fileScanner($targetFile, $targetPath) { $imgsize = getimagesize($targetFile); $width = 60; //New width of image $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions $src_w = $imgsize[0]; $src_h = $imgsize[1]; $picture = imagecreatetruecolor($width, $height); imagealphablending($picture, false); imagesavealpha($picture, true); $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); if($bool){ switch(strtolower(substr($targetFile, -3))){ case "jpg": //header("Content-Type: image/jpeg"); $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "png": //header("Content-Type: image/png"); imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "gif": //header("Content-Type: image/gif"); imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; } } imagedestroy($picture); imagedestroy($image); } $imgsize = getimagesize($targetFile); switch(strtolower(substr($targetFile, -3))){ case "pdf": $large = substr_replace($targetFile , 'jpg', strrpos($targetFile , '.') +1); $thumbnail = dirname($large).'/thumbs/'.basename(substr($large, 0, -4)."_thumb".strtolower(substr($large, -4))); $cmd = "$targetFile -write $large -thumbnail 64x64 $thumbnail "; exec("convert $cmd "); exit; break; case "jpg": $image = imagecreatefromjpeg($targetFile); break; case "png": $image = imagecreatefrompng($targetFile); break; case "gif": $image = imagecreatefromgif($targetFile); break; case "zip": $zip = new ZipArchive(); $zip->open($targetFile); $zip->extractTo($targetPath); $zip->close(); fileScanner($targetFile, $targetPath); break; default: exit; break; } fileScanner($targetFile, $targetPath); // $width = 60; //New width of image // $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions // // $src_w = $imgsize[0]; // $src_h = $imgsize[1]; // // // $picture = imagecreatetruecolor($width, $height); // imagealphablending($picture, false); // imagesavealpha($picture, true); // $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); // // if($bool){ // switch(strtolower(substr($targetFile, -3))){ // case "jpg": // //header("Content-Type: image/jpeg"); // $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // case "png": // //header("Content-Type: image/png"); // imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // case "gif": // //header("Content-Type: image/gif"); // imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // } // } // // imagedestroy($picture); // imagedestroy($image); echo '1'; // Important so upload will work on OSX ?> If anyone could help me with this I'd greatly appreciate it, I've been reading so many guides on functions and arguments my brain is fried and I fear I've strayed from the subject of what I want to do! Many thanks. I'm new to programming so take it easy on me but I wrote this script for php and it's not complete yet but I could use some advice on file upload security. Besides recreating the image, checking token/request and setting apache settings what else can I do to secure this application. Here's my code:
header('Content-Type: application/json'); $uploaded = array(); if(!empty($_FILES['file']['name'][0])) { $allowedExts = array("gif", "jpeg", "pjpeg", "x-png", "jpg", "png"); foreach ($_FILES['file']['tmp_name'] as $k => $v) { $name = $_FILES['file']['name'][$k]; $type = $_FILES['file']['type'][$k]; $error = $_FILES["file"]["error"][$k]; $size = $_FILES["file"]["size"][$k]; $tempDir = $_FILES["file"]["tmp_name"][$k]; $lowerName = strtolower($name); $temp = explode(".", $lowerName); $extension = end($temp); if ((($type == "image/gif") || ($type == "image/jpeg") || ($type == "image/jpg") || ($type == "image/pjpeg") || ($type == "image/x-png") || ($type == "image/png")) && ($size < 20000) && in_array($extension, $allowedExts)) { if ($error > 0) { echo "Return Code: " . $error . "<br>"; } else { $imageInfo = getimagesize($tempDir); if($imageInfo['mime'] != 'image/gif' && $imageInfo['mime'] != 'image/jpeg' && $imageInfo['mime'] != 'image/jpg' && $imageInfo['mime'] != 'image/pjpeg' && $imageInfo['mime'] != 'image/x-png' && $imageInfo['mime'] != 'image/png') { echo 'Sorry we only accept GIF, JPEG, JPG, PJPEG, X-PNG, PNG image files!'; }else { switch($type) { case 'image/gif': $newName = md5(uniqid()). '.' .time(). '.gif'; break; case 'image/jpeg': $newName = md5(uniqid()). '.' .time(). '.jpeg'; break; case 'image/jpg': $newName = md5(uniqid()). '.' .time(). '.jpg'; break; case 'image/pjpeg': $newName = md5(uniqid()). '.' .time(). '.pjpeg'; break; case 'image/x-png': $newName = md5(uniqid()). '.' .time(). '.x-png'; break; case 'image/png': $newName = md5(uniqid()). '.' .time(). '.png'; break; } if (file_exists('images/' .Session::get(Config::get('session/session_name')). '/' .$newName)) { echo escape($name) . " already exists. "; } else { if(move_uploaded_file($tempDir, 'images/' .Session::get(Config::get('session/session_name')). '/' .$newName)) { $uploaded[] = array( 'name' => $name, 'file' => 'images/' .Session::get(Config::get('session/session_name')). '/' .$newName ); } } } } } else { echo 'Sorry we only accept GIF, JPEG, JPG, PJPEG, X-PNG, PNG image files!'; } } }I've been researching apache Mod_mime but can't find enough info to wrap my mind around it. Edited by Millertime1, 12 August 2014 - 01:00 PM. Hi
Ultimate Aim: To upload multiple images using ajax using a PHP script which will be fired once an image is selected and then return the resulting URL for use in rest of my JS http://peter-gosling...hooseimage.html simple form posts to http://peter-gosling...d/saveimage.php This PHP script below currently gets the posted image and assigns it a random number file name and echos this <?php header("Access-Control-Allow-Origin: *"); $uploaddir = '/home/petergos/public_html/testupload/images/'; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); $urlpath = "http://www.peter-gosling.co.uk/testupload/images/"; $temp = explode(".",$_FILES["userfile"]["name"]); $newfilename = rand(1,999999999) . '.' .end($temp); $newuploadfile = $uploaddir . $newfilename; echo "<p>"; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newuploadfile)) { $urlfile = $urlpath . $newfilename; echo $urlfile; } else { echo "Upload failed"; } ?>What I want to do is post my image via ajax but return the value back to my js file I'm not certain on the CORS issue Here's my first attempt http://peter-gosling.com/testupload/ HTML <!DOCTYPE html> <html> <head> </head> <body> <input type="file" accept="image/*;capture=camera" name="taskoutputfile"></input> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $("input[name=taskoutputfile]").on("change", function (){ var fileName = $(this).val(); console.log(fileName); get_image_url(fileName) }); //UPLOAD IMAGE RETURN URL function get_image_url(imageurl) { var dataString = "url="+imageurl; //datastring = $("input[name=sessiontitle]").val(); //AJAX code to submit form. $.ajax({ type: "POST", url: "http://www.peter-gosling.co.uk/testupload/saveimage2.php", data: dataString, cache: false, success: function(html) { alert(html); } }); } </script> </body> </html>PHP <?php header("Access-Control-Allow-Origin: *"); $uploaddir = '/home/petergos/public_html/testupload/images/'; $uploadfile = $uploaddir . basename($_POST['url']); $urlpath = "http://www.peter-gosling.co.uk/testupload/images/"; $temp = explode(".",$_POST['url']); $newfilename = rand(1,999999999) . '.' .end($temp); $newuploadfile = $uploaddir . $newfilename; echo "<p>"; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newuploadfile)) { $urlfile = $urlpath . $newfilename; return $urlfile; } else { echo "Upload failed"; } /* echo "</p>"; echo '<pre>'; echo 'Here is some more debugging info:'; print_r($_FILES); print "</pre>"; */ ?>Have attached all files Any help would be really appreciated Thankyou |