PHP - Upload Images To Imageshack Using Curl
I am trying to upload images to Imageshack directly form my site with Imageshack API, using the code bellow:
index.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form action="curl-form.php" method="post" enctype='multipart/form-data'> <input type="file" id="foto" name="foto" /> <input type="submit" value="Enviar" /> </form> </body> </html> img.php <?php $data = array(); $data['fileupload'] = '@' . $_FILES["foto"]['tmp_name']; $data['key'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; $data['email'] = 'email@email.com'; $data['rembar'] = 'yes'; $data['optsize'] = '96x96'; $data['xml'] = 'yes'; $post_str = ''; foreach($data as $key=>$val) { $post_str .= $key.'='.urlencode($val).'&'; } $post_str = substr($post_str, 0, -1); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://www.imageshack.us/upload_api.php'); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_TIMEOUT, 240); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($ch ); curl_close($ch ); if (strpos ( $response, '<' . '?xml version="1.0" encoding="iso-8859-1"?>' ) === false) { return NULL; } else { $xml = new SimpleXMLElement ( $response ); return array ( "image" => $xml->image_link, "thumb" => $xml->thumb_link ); } ?> When I upload an image, the following error occurs: "Sorry, but we've detected that unexpected data is received. Required parameter 'fileupload' is missing or your post is not multipart/form-data" What is wrong with the code? How can I send enctype='multipart/form-data' with cURL? Similar TutorialsI have code written for image uploading, but it doesn't allow multiple images on a single upload, and doesn't re-size. Anyone willing to share a good upload script that will do the following?: -Allow multiple image uploads (10+ per submission), -Re-size images on upload, and -Rename images. Thanks Brett
i have php at server side and c++ at client side.what i am trying to do is to constantly look for files on server in folder on server if there’s a file in folder then download it on client side and delete it from server folder Hello All, I have a simple upload form which I am using to upload files to Box.net using PHP Curl. It works fine for small files, but times out for larger files. Anyone have any suggestions for this? Thanks, Pete Here is the code: Code: [Select] <html> <body bgcolor="black"> <div align="center"> <img src="Homepage_02.jpg" border="0" /> <br> <br> <font color="#f1ca63"; font face="Arial"; font size="5">Upload</font> <br> <br> <?php if (isset($_POST['upload'])) { if (!empty($_FILES['new_file_1']['name'])) { $allowedExtensions = array("txt","csv","xml","css","doc", "docx","xls","xlsx","rtf","ppt","pdf","swf","flv","avi","wmv","mov","jpg","jpeg","gif","png"); foreach ($_FILES as $file) { if ($file['tmp_name'] > '') { if (!in_array(end(explode(".", strtolower($file['name']))),$allowedExtensions)) { echo $file['name'].' is an invalid file type!<br/>'; } else { $temp_name = $_FILES['new_file_1']['name']; $localfile = $_FILES['new_file_1']['tmp_name']; $file = fopen($localfile,'r'); $request_url = 'https://upload.box.net/api/1.0/upload/[Token Here]/[Folder ID]'; $post_params['check_name_conflict_folder_option'] = urlencode('1'); $post_params['new_file_1'] = "@$localfile"; $post_params['description'] = urlencode($_POST['description']); $post_params['uploader_email'] = urlencode($_POST['uploader_email']); $post_params['upload'] = urlencode('upload'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params); curl_setopt($ch, CURLOPT_TIMEOUT, 300); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); curl_close($ch); $resultArray = explode(' ',$result); if($resultArray[5] != '') { $fileID = substr($resultArray[5],4,-1); $shareName = $temp_name; $link = 'http://www.box.net/shared/'.$shareName; } $renameurl = addslashes("https://www.box.net/api/1.0/rest?action=rename&api_key=[API KEY]&auth_token=[TOKEN Here]&target=file&target_id=".$fileID."&new_name=".$shareName); $renameResult = file_get_contents($renameurl); echo '<font color="white">Upload Successful</font>'; } } } } else { echo '<font color="white">Please select a file</font>'; } } ?> <hr width=600 color=grey> <br> <div align="center"> <form action="box_upload_curl.php" enctype="multipart/form-data" method="post"> <input type="hidden" name="check_name_conflict_folder_option" value="1"/> <table> <tr> <td class="field" style="color: #f1ca63; font-family: Arial; font-size: 14px" width="50%">Choose File to Upload: </td> <td class="input"><input type="file" name="new_file_1" /></td> </tr> <tr> <td class="field field_top" style="color: #f1ca63; font-family: Arial; font-size: 14px" ><br/> Description (optional):</td> <td class="input"><br/><textarea name="description"></textarea></td> </tr> <tr> <td class="field field_top" style="color:#f1ca63; font-family: Arial; font-size: 14px" > <br/> Your e-mail <font color="red">*</font>: </td> <td class="input field_top" style="color: #f1ca63; font-family: Arial; font-size: 14px" > <br/> <input type="text" name="uploader_email" id="email_input"></input> </td> </tr> <tr> <td colspan="2" class="submit" align="center"> <br /> <input type="submit" name="upload" value="Upload" /> </td> </tr> </table> </form> <hr width=600 color="grey"> </div> Hi, This is the code I made to show the problem: $useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 ( .NET CLR 3.5.30729)"; $timeout = 10 ; $cookie = tempnam ("/tmp", "CURLCOOKIE"); $post = array('_method'=>"put", 'authenticity_token'=>' zcvcxfsdfvxcv', 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg" ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_USERAGENT, $useragent); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch, CURLOPT_URL, "http://localhost/test.php"); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); curl_setopt( $ch, CURLOPT_ENCODING, "" ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_AUTOREFERER, true ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $html = curl_exec($ch); curl_close($ch); Now this link used above: http://localhost/test.php has this code: print_r($_POST); print_r($_FILES); It simply prints whats in post and files. So the above code displays this on screen: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image] => Array ( [name] => Array ( [a] => Girl-Next-Door-movie-f01.jpg ) [type] => Array ( [a] => image/jpeg ) [tmp_name] => Array ( [a] => /tmp/phppLJPQV ) [error] => Array ( [a] => 0 ) [size] => Array ( [a] => 55377 ) ) ) but we need to modify the code so that it should display this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) Meaning, it is taking this(profile_image[a]) as an array when we are defining $post because that's how curl recognizes that we want to upload only a file or an array of files on server by http post. So, basically the problem is the name of the input field that is defined as an array (profile_image[a]) on the web page that we are trying to mock. If this(profile_image[a]) was this (profile_image_a)(without []) on that webpage, then it would not have been a problem. So, if you understand, this is basically a syntax problem. I do not know how stop curl from reading 'profile_image[a]' as an array here 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg. I need curl to read 'profile_image[a]' as an string and not array. I have to use [], otherwise I will not be able to mock the webpage as the name will change. It will give error. I hope I explained the problem and also gave you a way to test if you have a solution. Again, if your code starts displaying this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) ,then we have a solution. Thanks for helping in advance. Regards, Manoj $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. I am practicing php with a local server running and I created a class that uses curl to open pages, fetch the html, put it into a DOMDocument, parse it, etc...I began following links and downloading images and checking their mime types so I know how to handle it. There isn't really much information about doing it with video files though like mpeg, mov, etc...When I try simply following the link and downloading it locally it works, but I get no mime type, or a wierd mime type that doesn't make sense and it will only store a blank file (but it all downloads ok) I just can't play it. Anybody know anything about doing video stuff with php? this script saves the image from a url to the folder were this script is saved, how can i make this code save images into specific folder such as "/image/poster_image/" <?php $img[]='http://images.rottentomatoescdn.com/images/redesign/poster_default.gif'; foreach($img as $i){ echo $i; save_image($i); // if(getimagesize(basename($i))){ // echo '<h3 style="color: green;">Image ' . basename($i) . ' Downloaded OK</h3>'; // }else{ // echo '<h3 style="color: red;">Image ' . basename($i) . ' Download Failed</h3>'; // } } //Alternative Image Saving Using cURL seeing as allow_url_fopen is disabled - bummer function save_image($img,$fullpath='basename'){ if($fullpath=='basename'){ $fullpath = basename($img); } $ch = curl_init ($img); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec($ch); curl_close ($ch); if(file_exists($fullpath)){ unlink($fullpath); } $fp = fopen($fullpath,'x'); fwrite($fp, $rawdata); fclose($fp); } ?> Hi there, I need a little help...
I have simple form/code for upload image and insert it into db, and its working.
<form name="unos" action="" method="post" enctype="multipart/form-data"> <select name="kategorija"> <option value="1">Album</option> </select> <input type="file" name="uploaded_file[]" id="file" > </form> <?PHP include "config.php"; $uploads_dir = 'slike'; foreach ($_FILES["uploaded_file"]["error"] as $key => $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["uploaded_file"]["tmp_name"][$key]; $name = $_FILES["uploaded_file"]["name"][$key]; move_uploaded_file($tmp_name, "$uploads_dir/$name"); } } $sql="INSERT INTO galerija_slike (kategorija_id, url_slike) VALUES ('".$_POST['kategorija']."', '".$_FILES['uploaded_file']['name'][$key]."')"; if (mysql_query($sql)) { echo "success"; } else { echo "error" . mysql_error(); } ?>How can I store more image url's from input fields? When I add more input fields..... move_uploaded_file(): uploads all images, but I don't know how to also add them in db? I need something like this: <input type="file" name="uploaded_file[]" id="file" > <input type="file" name="uploaded_file[]" id="file" > <input type="file" name="uploaded_file[]" id="file" > <input type="file" name="uploaded_file[]" id="file" > <input type="file" name="uploaded_file[]" id="file" >Thanks Edited by Hrvoje, 02 February 2015 - 12:17 AM. Hello... I have some simple code but no ideas for upload another image?? PHP stores image name in database but there is no second picture uploaded in the images/ folder. Pls help. Thanks if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "<strong>Slika:</strong> " . $_FILES["file"]["name"] . "<br />"; echo "<strong>Format slike:</strong> " . $_FILES["file"]["type"] . "<br />"; echo "<strong>Velicina:</strong> " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "<strong>Temp file:</strong> " . $_FILES["file"]["tmp_name"] . "<br />"; // here is mistake??? move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . $_FILES["file"]["name"]); // $sql="INSERT INTO test (name, something, slika, slika2) VALUES ('".$_POST['name']."', '".$_POST['something']."', '".$_FILES['file']['name']."', '".$_FILES['slika1']['name']."')"; if (mysql_query($sql)) { echo "Sucess"; } else { echo "Error" . mysql_error(); } } } else { echo "Invalid file"; } ?> Hi All Been desperate to crack this nut for a few years now, but seem to be failing epically! I have been building a property/real estate web site for a long time, but I have no training and have been learning as I go. I have a script written that allows me to upload data and store it in my database, what I was looking to do was add a section that allows me to upload multiple images at the same time, and store the location to another table in the same database. So what I was looking to do was remove all the...lets say rubbish to be nice...and see where it takes us. I apologize in advance for the lack of santized code...I am coding locally only, in an admin area, and will rectify before launching the site...just trying to get the bones of the script in place. Ok, first we have my form as shown here, warts and all. <?php /** * Create Listing */ ?> <div id="admin" class="intern"> <div class="banner"> <div class="logbanner">CREATE LISTING</div> </div> <div class="padding"> <form action="adminprocess.php" method="POST" enctype="multipart/form-data"> <table border="0" cellpadding="2" cellspacing="2" width="700"> <tr> <td align="right"><label class="text">Property Title: </label></td> <td><input type="text" name="property_title" maxlength="50" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Selling Agent: </label></td> <td><input type="text" name="agent" maxlength="30" value="<?php echo $session->username; ?>"></td> </tr> <tr> <td align="right"><label class="text">Style: </label></td> <td> <select id="property_type" name="property_type"> <option value="Not Selected" selected>Not Selected</option> <option value="Detached">Detached</option> <option value="Semi-Deatched">Semi-Detached</option> <option value="End Terrace">End Terrace</option> <option value="Mid Terrace">Mid Terrace</option> <option value="Flat">Flat</option> <option value="Ground Floor Flat">Ground Floor Flat</option> <option value="4 in a Block">4 in a Block</option> <option value="Bungalow">Bungalow</option> <option value="Apartment">Apartment</option> <option value="Studio">Studio</option> <option value="Maisonette">Maisonette</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Address: </label></td> <td><input type="text" name="address_one" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Address: </label></td> <td><input type="text" name="address_two" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Town: </label></td> <td><input type="text" name="town" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">County: </label></td> <td> <select id="county" name="county"> <option value="Fife" selected>Fife</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Post Code: </label></td> <td><input type="text" name="postcode" maxlength="30" value="" size="15"></td> </tr> <tr> <td align="right"><label class="text">Price: </label></td> <td> <select id="price_cond" name="price_cond"> <option value="Not Selected" selected>Not Selected</option> <option value="Offers Over">Offers Over</option> <option value="Fixed Price">Fixed Price</option> </select> <input type="text" name="price" maxlength="30" value="" size="32"> </td> </tr> <tr> <td align="right"><label class="text">Property Status: </label></td> <td> <select id="status" name="status"> <option value="Not Selected" selected>Not Selected</option> <option value="Offers Over">For Sale</option> <option value="Fixed Price">Sold Subject to Signed Missives</option> <option value="Fixed Price">Sold Subject to Survey</option> <option value="Fixed Price">Price Reduced</option> <option value="Fixed Price">Sold</option> <option value="Fixed Price">Re-Listed</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Description Header: </label></td> <td><input type="text" name="deschead" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Description: </label></td> <td><textarea cols="40" rows="8" type="text" name="desc" maxlength="1000" value=""></textarea></td> </tr> <!-- I want the images to be added here --> <tr> <td align="right"><label class="text">Reception Rooms: </label></td> <td> <select id="recrooms" name="recrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Bedrooms: </label></td> <td> <select id="bedrooms" name="bedrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Bathrooms: </label></td> <td> <select id="bathrooms" name="bathrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Garden: </label></td> <td> <select id="garden" name="garden"> <option value="Not Selected" selected>Not Selected</option> <option value="Yes">Yes</option> <option value="No">No</option> <option value="Shared">Shared</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Garage: </label></td> <td> <select id="garage" name="garage"> <option value="Not Selected" selected>Not Selected</option> <option value="Yes">Yes</option> <option value="No">No</option> <option value="Shared">Shared</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Additional Info: <br />** Not seen by site users **</label></td> <td><textarea cols="40" rows="8" type="text" name="addinfo" maxlength="1000" value=""></textarea></td> </tr> <tr> <td align="right"><label class="text"> </label></td> <td> <input type="hidden" name="subcreatelisting" value="1"> <input type="submit" value="Create Listing"> </td> </tr> </table> </form> <?php echo $form->error("creListing"); ?> </div> </div> next I have my process page which has the following function included... function procCreateListing(){ global $session, $database, $form; $q = "INSERT INTO ".TBL_PROP."(prop_id, prop_agent, prop_type, prop_add_1, prop_add_2, prop_town, prop_county, prop_pc, prop_price, prop_price_cond, prop_rec_rooms, prop_bedrooms, prop_bathrooms, prop_status, prop_garden, prop_garage, prop_description_header, prop_description, prop_add_info, prop_add_date) VALUES ('".$_POST['property_title']."', '".$_POST['agent']."', '".$_POST['property_type']."', '".$_POST['address_one']."', '".$_POST['address_two']."', '".$_POST['town']."', '".$_POST['county']."', '".$_POST['postcode']."', '".$_POST['price']."', '".$_POST['price_cond']."', '".$_POST['recrooms']."', '".$_POST['bedrooms']."', '".$_POST['bathrooms']."', '".$_POST['status']."', '".$_POST['garden']."', '".$_POST['garage']."', '".$_POST['deschead']."', '".$_POST['desc']."', '".$_POST['addinfo']."', '".$_POST['date']."')"; $database->query($q); } and I have 2 tables in mysql prop_listing and imagebin Code: [Select] CREATE TABLE `kea_userclass`.`prop_listing` ( `prop_id` INT( 10 ) NOT NULL AUTO_INCREMENT , `prop_agent` VARCHAR( 40 ) NOT NULL , `prop_type` VARCHAR( 20 ) NOT NULL , `prop_add_1` VARCHAR( 50 ) NOT NULL , `prop_add_2` VARCHAR( 50 ) NOT NULL , `prop_town` VARCHAR( 30 ) NOT NULL , `prop_county` VARCHAR( 25 ) NOT NULL , `prop_pc` VARCHAR( 8 ) NOT NULL , `prop_price` INT( 10 ) NOT NULL , `prop_price_cond` VARCHAR( 20 ) NOT NULL , `prop_rec_rooms` INT( 2 ) NOT NULL , `prop_bedrooms` INT( 3 ) NOT NULL , `prop_bathrooms` INT( 2 ) NOT NULL , `prop_status` VARCHAR( 20 ) NOT NULL , `prop_garage` INT( 1 ) NOT NULL , `prop_garden` INT( 1 ) NOT NULL , `prop_description_header` VARCHAR( 50 ) NOT NULL , `prop_description` VARCHAR( 2000 ) NOT NULL , `prop_add_info` VARCHAR( 2000 ) NOT NULL , `prop_add_date` DATE NOT NULL , PRIMARY KEY ( `prop_id` ) ) ENGINE = MYISAM ; CREATE TABLE `imagebin` ( `id` int( 11 ) NOT NULL AUTO_INCREMENT , `item_id` int( 11 ) NOT NULL , `image` varchar( 255 ) NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM DEFAULT CHARSET = latin1; first of all thanks for getting this far, I know it is a lot of reading, and a lot to ask for, but now I am stuck... I need a section on my form that would allow me to upload 8 images, and store them in a directory folder I need the location saved into my imagebin table thats it just now Many thanks for reading, and I hope someone can take me under their wing and help me passed this hurdle Hi I am trying to resize images as they are uploaded. The problem I have is that the image is uploading and adding to the database, but is not resizing. The code I am using is below Code: [Select] <?php include("config.inc.php"); include('../includes/connect_inc.php'); // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by add-photos.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); //resize photos to maximum height or width //define parameters - maximum height & width for new images $image_max_width=599; $image_max_height=599; $max_dimension=800; // Grab the width and height of the image. list($width,$height) = getimagesize($_FILES['photo_filename']); // If the max width input is greater than max height we base the new image off of that, otherwise we // use the max height input. // We get the other dimension by multiplying the quotient of the new width or height divided by // the old width or height. if($image_max_width > $image_max_height){ if($image_max_width > $max_dimension){ $newwidth = $max_dimension; } else { $newwidth = $image_max_width; } $newheight = ($newwidth / $width) * $height; } else { if($image_max_height > $max_dimension){ $newheight = $max_dimension; } else { $newheight = $image_max_height; } $newwidth = ($newheight / $height) * $width; } // Create temporary image file. $tmp = imagecreatetruecolor($newwidth,$newheight); // Copy the image to one with the new width and height. imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height); //end of resizing // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) { $thumbnail_width = 100; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(100 * $size[0] / $size[1]); $thumbnail_height = 100; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } header('Location: add-photos.php'); // Print Result echo <<<__HTML_END <html> <head> <title>Photos uploaded</title> </head> <body> $result_final </body> </html> __HTML_END; ?> Any help would be appreciated. One image is displaying but when i choose image 2 it overlaps image 1..
gallery.php 8.77KB
7 downloads
I currently have a file upload form that uploads images to a folder on my server called "attachments". This is the directory path: www.mysite.com/docs/attachments/ However, I want the images to upload to www.mysite.com/data/attachments/ instead. I have included the relevant part of the PHP below. I have tried changing this: $cur_dir = $cur_dir."/".$dir; to this: $cur_dir = $cur_dir."www.mysite.com/data/attachments/".$dir; and changing this: $dirs = explode("/","attachments//"); to this: $dirs = explode("www.mysite.com/data/","attachments//"); and also changing this: $_values[$file[0]."_real-name"] = "attachments/".date("YmdHis")."_".$_FILES[$file[0]]["name"]."_secure"; to this: $_values[$file[0]."_real-name"] = "www.mysite.com/data/attachments/".date("YmdHis")."_".$_FILES[$file[0]]["name"]."_secure"; But nothing has worked so far. Any suggestions would be appreciated. foreach($files[$form] as $file){ $str = $file[1]; if (eval("if($str){return true;}")) { $_values[$file[0]] = $_FILES[$file[0]]["name"]; $dirs = explode("/","attachments//"); $cur_dir ="."; foreach($dirs as $dir){ $cur_dir = $cur_dir."/".$dir; if (!@opendir($cur_dir)) { mkdir($cur_dir, 0777);}} $_values[$file[0]."_real-name"] = "attachments/".date("YmdHis")."_".$_FILES[$file[0]]["name"]."_secure"; copy($_FILES[$file[0]]["tmp_name"],$_values[$file[0]."_real-name"]); @unlink($_FILES[$file[0]]["tmp_name"]); }else{ $flag=true; if ($_isdisplay) { //$ExtFltr = $file[2]; //$FileSize = $file[4]; if (!eval("if($file[2]){return true;}")){echo $file[3];} if (!eval("if($file[4]){return true;}")){echo $file[5];} $_ErrorList[] = $file[0]; } } } In the past, whenever I write an image upload script in php that needs to generate a thumbnail or resized version, I have had to make sure the image is a reasonable size before uploading otherwise you get the old 'allowed memory bytes exceeded' thing. What are my options if I want people to be able to upload a full size image from their camera i.e. a 15-20mb 4000x3000px image and then have a thumbnail and something like 500px wide version for displaying on the site? The large unaltered original needs to be stored as well as it will be used for prints. Is this just not possible with PHP? Or is it down to needing a dedicated server? Hi
I am developing a website for fun to play around with, like a little fun project and am trying to work out how to upload multiple images that stores the filename in the database and the actual file on the server
I have managed to get it working if I upload just one image but can't work it out for multiple images
Can anyone point me in the right direction or advise where I need to adjust for multiple images upload
I know on the html form on the input tag needs to have multiple and then the name in the input tag be image[] but is as far as I get, it's the PHP I get stuck on
The html for the form is below
<form action="private-add-insert.php" method="post" enctype="multipart/form-data"> Car Make: <input type="text" name="make"> Car Model: <input type="text" name="model"> Exterior Colour: <input type="text" name="exteriorcolour"> Engine Size: <input type="text" name="enginesize"> Fuel Type: <input type="text" name="fueltype"> Year Registered: <input type="text" name="yearregistered"> Transmission: <input type="text" name="transmission"> Mileage: <input type="text" name="mileage"> Number of Doors: <input type="text" name="nodoors"> Body Style: <input type="text" name="bodystyle"> Price: <input type="text" name="price"> <br> <label>Upload Images</label> <input type="file" name="image[]" multiple/> <br /> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> <br /> <input type="submit" value="Submit Listing"> </form>Below is the PHP coding that processes the html form <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); ?> <?php // Start a session for error reporting session_start(); // Call our connection file require("includes/conn.php"); // 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", "image/png"); 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 = "private-listing-images/"; // Get our POSTed variables $make = $_POST['make']; $model = $_POST['model']; $exteriorcolour = $_POST['exteriorcolour']; $enginesize = $_POST['enginesize']; $fueltype = $_POST['fueltype']; $yearregistered = $_POST['yearregistered']; $transmission = $_POST['transmission']; $mileage = $_POST['mileage']; $nodoors = $_POST['nodoors']; $bodystyle = $_POST['bodystyle']; $price = $_POST['price']; $image = $_FILES['image']; // Sanitize our inputs $make = mysql_real_escape_string($make); $model = mysql_real_escape_string($model); $exteriorcolour = mysql_real_escape_string($exteriorcolour); $enginesize = mysql_real_escape_string($enginesize); $fueltype = mysql_real_escape_string($fueltype); $yearregistered = mysql_real_escape_string($yearregistered); $transmission = mysql_real_escape_string($transmission); $mileage = mysql_real_escape_string($mileage); $nodoors = mysql_real_escape_string($nodoors); $bodystyle = mysql_real_escape_string($bodystyle); $price = mysql_real_escape_string($price); $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved do // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // 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, bmp or png"; header("Location: private-add-listing.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 privatelistings (make, model, exteriorcolour, enginesize, fueltype, yearregistered, transmission, mileage, nodoors, bodystyle, price, filename) values ('$make', '$model', '$exteriorcolour', '$enginesize', '$fueltype', '$yearregistered', '$transmission', '$mileage', '$nodoors', '$bodystyle', '$price', '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: private-add-listing-successfully.php?msg=Listing Added successfully"); 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: private-add-listing.php"); exit; } ?>I know the coding needs updating to mysqli and prevent sql injections but want to get it working first and then will do them parts Thank you in advance Kind regards Ian Hello all, I am having an issue. I have read many articles and help forums, but I cannot find a specific way to help me. My issue is this. I have a php upload form for visitors to upload an image. Now, I would like to know how to get the uploaded images to show up after the upload. Someone suggested to me to call the images. However, I am not sure how to do this. Below is the script for the image upload, which works great for uploading. <?php /* This script can send an email and/or make an entry in a log file There are two variables below - one for an email address and one for a log file Set both variables to the values you want to use If you do not want either an email or log entry, comment out the respective line For example, if you do not want an email sent, put a // in front of the $emailAddress line - same for the $logFile line */ $logFile = $_SERVER['DOCUMENT_ROOT'].'/upload.log'; // full path to your log file $emailaddress = "email@gmail.com"; $home_page = "index.html"; // used for a link to return $uploaddir = "uploads/"; // the directory where files are to be uploaded - include the trailing slash $fileTypeArray = array(".jpg",".gif",".txt"); // enter in all lower case, the script will handle a match with upper case $maxSize = 500000; // maximum file size that can be uploaded - in bytes $maxFileSpace = 50000000; // maximum space that can be used by files matching the $fileTypeArray array in the upload directory - in bytes putenv('TZ=EST5EDT'); // eastern time // change nothing below this line $maxDisplay = $maxSize / 1000; ?> <html><head></head><body> <div style="text-align: center; margin: 100px auto; border: 1px black solid; width:400px;"> <?php // print_r($_FILES); // can be used for debugging $file_name = $_FILES['file']['name']; $file_size = $_FILES['file']['size']; $file_tmp_name = $_FILES['file']['tmp_name']; if (!empty($file_name)) { unset($error); echo "<br>File Name: $file_name<br><br>"; echo "File Size: $file_size bytes<br><br>"; // file size test if ($file_size == 0 ) $error .= "<span style='color: red;'>Invalid file</span><br>"; if ($file_size > $maxSize ) $error .= "<span style='color: red;'>Your file exceeds $maxDisplay K.</span><br>"; // file type test if (!in_array(strtolower(strrchr($file_name,'.')),$fileTypeArray) ) $error .= "<span style='color: red;'>Your file is not a valid file type.</span><br>"; // max directory size test foreach(scandir($uploaddir) as $file_select) if (in_array(strtolower(strstr($file_select,'.')),$fileTypeArray)) $total_size = $total_size + filesize($uploaddir.$file_select); if (($total_size + $file_size) >= $maxFileSpace) $error .= "<span style='color: red;'>Total file space limits have been exceeded.</span><br>"; // scrub characters in the file name $file_name = stripslashes($file_name); $file_name = preg_replace("#[ ]#","_",$file_name); // change spaces to underscore $file_name = preg_replace('#[^()\.\-,\w]#','_',$file_name); //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore $file_name = preg_replace('#(_)+#','_',$file_name); //eliminate duplicate underscore // check for file already exists if (file_exists($uploaddir.$file_name)) $error .= "<span style='color: red;'>File already exists.</span><br>"; // if all is valid, do the upload if (empty($error)) { if (move_uploaded_file($file_tmp_name,$uploaddir.$file_name)) { chmod($uploaddir.$file_name,0644); echo "<span style='color: green;'>Your file was successfully uploaded!</span>"; if (isset($emailAddress)) { $message = $file_name . " was uploaded by".$_SERVER['REMOTE_ADDR']."at".date('Y-m-d H:i:s'); mail($emailaddress,"You have a file upload",$message,"From: Website <>"); } if (isset($logFile)) { $logData = $file_name."||".$_SERVER['REMOTE_ADDR']."||".date('Y-m-d H:i:s')."\r\n"; @file_put_contents($logFile,$logData,FILE_APPEND|LOCK_EX); } } else { echo "<span style='color: red;'>Your file could not be uploaded.</span>"; } } echo "$error<hr>"; } ?> <p>Upload a <span style="color: blue;"> <?php foreach($fileTypeArray as $fileType) echo $fileType; ?> </span> file to our server<br> Maximum file size is <?php echo $maxDisplay; ?>K</p> <form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" enctype="multipart/form-data"> File: <input type="file" name="file" style="width: 250px;"><br> <input type="submit" name="submit" value="Upload File"></form> <a href="<?php echo $home_page; ?>">Return to the Home Page</a> </div> What is the method or process to get the images to show up or to pull the images from the folder to a webpage? I have a PHP script that uploads images to a folder on my server (attachments folder). Currently the folder sits within my webroot and is publicly accessible (I have to use chmod 777 due to permissions issue). So, I created the "attachments" folder outside of my webroot (so that it is not publicly accessible), but I do not know how to set the path in the PHP code to upload it to that "attachments" folder outside of the webroot. As you see in the snippet of PHP code below, the code currently uploads the the "attachments" folder within the www (webroot) directory. How do I make it upload to the "attachments" folder OUTSIDE of the www (webroot) directory? foreach($files[$form] as $file){ $str = $file[1]; if (eval("if($str){return true;}")) { $_values[$file[0]] = $_FILES[$file[0]]["name"]; $dirs = explode("/","attachments//"); $cur_dir ="."; foreach($dirs as $dir){ $cur_dir = $cur_dir."/".$dir; if (!@opendir($cur_dir)) { mkdir($cur_dir, 0777);}} $_values[$file[0]."_real-name"] = "attachments/".date("YmdHis")."_".$_FILES[$file[0]]["name"]."_secure"; copy($_FILES[$file[0]]["tmp_name"],$_values[$file[0]."_real-name"]); @unlink($_FILES[$file[0]]["tmp_name"]); }else{ $flag=true; if ($_isdisplay) { //$ExtFltr = $file[2]; //$FileSize = $file[4]; if (!eval("if($file[2]){return true;}")){echo $file[3];} if (!eval("if($file[4]){return true;}")){echo $file[5];} $_ErrorList[] = $file[0]; } } } Thanks I have a form that will be used to edit various fields including images. Everything works on this form except the images. When I choose the image i want to replace and upload the new image the location of the others get erased on the MySQL database and I'm just left with the one I replaced. How can I just change the image I pick to replace without erasing the location of the others? Is there a way just to tell the script to only replace the image that corresponds with the image selected? Thank You The Form Code: [Select] <!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=utf-8" /> <title>FormListing </title> </head> <body>\<?php session_start(); if(empty($_SESSION['myusername'])){ // send them back to login header('location: index.php'); } $_SESSION['id']; $_SESSION['$myusername']; $id = (int)$_GET['id']; $id = substr($id, 0,5); if($id < 1 || $id > 99999) exit; $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name=""; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // get value of id that sent from address bar $id=$_GET['id']; // Retrieve data from database $sql="SELECT * FROM $tbl_name WHERE id='$id'"; $result=mysql_query($sql); $rows=mysql_fetch_array($result); ?> <form method="post" action="aptmodifyform.php" enctype="multipart/form-data"/> <input type="hidden" name="id" id="id" value="<?php echo $id; ?>" /> <table width="914" height="1234" border="0"> <tr> <td width="636" height="68"><div align="right"><span style="color: #F00">*</span>Title</div></td> <td width="11"><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="title"></label> <div align="left"><span id="sprytextfield1"> <input name="title" type="text" value="<? echo $rows['title']; ?>" id="title" size="50" maxlength="50"/> </span></div></td> </tr> <tr> <td><div align="right">County</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="county"></label> <select name="county" id="county"> <option selected="selected" <?=($rows['county'] == 'Bronx') ? 'selected="selected"' : ''?>>Bronx</option> <option <?=($rows['county'] == 'Brooklyn') ? 'selected="selected"' : ''?>>Brooklyn</option> <option <?=($rows['county'] == 'Manhattan') ? 'selected="selected"' : ''?>>Manhattan</option> <option <?=($rows['county'] == 'Queens') ? 'selected="selected"' : ''?>>Queens</option> <option <?=($rows['county'] == 'Staten Island') ? 'selected="selected"' : ''?>>Staten Island</option> <option>-----------------</option> <option <?=($rows['county'] == 'Nassau') ? 'selected="selected"' : ''?>>Nassau</option> <option <?=($rows['county'] == 'Suffolk') ? 'selected="selected"' : ''?>>Suffolk</option> </select></td> </tr> <tr> <td><div align="right">Town</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="town"></label> <input name="town" type="text" value="<? echo $rows['town']; ?>" id="town" size="50" maxlength="30"/></td> </tr> <tr> <td><div align="right">Description<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> </div></td> <td><div align="center"> <p>:<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> </p> </div></td> <td colspan="3" style="text-align: left"><label for="description"></label> <textarea name="description" cols="70" rows="25" id="description"><?php echo $rows['description']; ?></textarea></td> </tr> <tr> <td style="text-align: right; color: #000;">Service</td> <td style="text-align: center">:</td> <td colspan="3" style="text-align: left"><label for="service"></label> <select name="service" size="1" id="service"> <option <?=($rows['service'] == 'Landlord') ? 'selected="selected"' : ''?>>Lanlord</option> <option <?=($rows['service'] == 'Property Mangement') ? 'selected="selected"' : ''?>>Property Mangement</option> <option <?=($rows['service'] == 'Realtor') ? 'selected="selected"' : ''?>>Realtor</option> </select></td> </tr> <tr> <td><div align="right">Service Fees</div></td> <td>:</td> <td colspan="3" style="text-align: left"><select name="feeornofee" id="feeornofee"> <option <?=($rows['feeornofee'] == 'Broker Fees + Other Fees') ? 'selected="selected"' : ''?>>Broker Fees + Other Fees</option> <option <?=($rows['feeornofee'] == 'Broker Fees') ? 'selected="selected"' : ''?>>Broker Fees</option> <option <?=($rows['feeornofee'] == 'Other Fees - No Broker Fee') ? 'selected="selected"' : ''?>>Other Fees - No Broker Fee</option> <option <?=($rows['feeornofee'] == 'No Fees') ? 'selected="selected"' : ''?>>No Fees</option> </select></td> </tr> <tr> <td><div align="right">Lease Type</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="lease"></label> <select name="lease" id="lease"> <option <?=($rows['lease'] == 'Rent Stabilized ') ? 'selected="selected"' : ''?>>Rent Stabilized </option> <option <?=($rows['lease'] == 'Prime, non-stabilized lease') ? 'selected="selected"' : ''?>>Prime, non-stabilized lease</option> <option <?=($rows['lease'] == 'Coop (sub) Lease') ? 'selected="selected"' : ''?>>Coop (sub) Lease</option> <option <?=($rows['lease'] == 'Condo Lease') ? 'selected="selected"' : ''?>>Condo Lease</option> <option <?=($rows['lease'] == 'Commercial Lease') ? 'selected="selected"' : ''?>>Commercial Lease</option> <option <?=($rows['lease'] == 'Other') ? 'selected="selected"' : ''?>>Other</option> </select></td> </tr> > <tr> <td><div align="right">Contact's Name</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="contact"></label> <input name="contact" type="text" value="<? echo $rows['contact']; ?>" id="contact" size="40" maxlength="40" /></td> </tr> <tr> <td><div align="right">Name of Office</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="office"></label> <input name="office" type="text" value="<? echo $rows['office']; ?>" id="office" size="40" maxlength="40" /></td> </tr> <tr> <td><div align="right">Pets</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="pets"></label> <select name="pets" id="pets"> <option <?=($rows['pets'] == 'Pets Allowed') ? 'selected="selected"' : ''?>>Pets Allowed</option> <option <?=($rows['pets'] == 'No Pets') ? 'selected="selected"' : ''?>>No Pets</option> <option <?=($rows['pets'] == 'Pets Allowed - Small pets') ? 'selected="selected"' : ''?>>Pets Allowed - Small pets</option> </select></td> </tr> <tr> <td><div align="right">Phone<br /> </div> <br /></td> <td><div align="center">:<br /> <br /> </div></td> <td colspan="3" style="text-align: left"><label for="phone"></label> <span id="rental_phone"> <input type="text" name="phone" value="<? echo $rows['phone']; ?>"id="phone" /> <span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span><br /> <span style="font-style: italic; font-size: 14px; font-weight: bold;">ex. (123) 456-7890 - Please keep this format.</span></td> </tr> <tr> <td style="text-align: right"><p>Location<br /> </p> <p><br /> <br /> <br /> </p></td> <td style="text-align: center">:<br /> <br /> <br /> <br /> <br /></td> <td colspan="3" style="text-align: left"><label for="cross_streets"></label> <input name="cross_streets" type="text" value="<? echo $rows['cross_streets']; ?>" id="cross_streets" size="80" maxlength="100" /> <br /> <span style="color: #F00">Please insert here the intersecting streets. Make sure you add the word "and" <br /> between streets <br /> OR<br /> You can put the property's full address. <br /> e.g. 193rd Street AND Jamaica Avenue, Jamaica, NY </span></td> </tr> <tr> <td style="text-align: right">Zip Code</td> <td style="text-align: center">:</td> <td colspan="3" style="text-align: left"><input name="zipcode" type="text" id="zipcode" value="<? echo $rows['zipcode']; ?>" size="9" maxlength="5" /></td> </tr> <tr> <td style="text-align: right"><span style="color: #000">Email </span><br /> <br /></td> <td style="text-align: center">:<br /> <br /></td> <td colspan="3" style="text-align: left"><label for="email"></label> <input name="email" type="text" value="<? echo $rows['email']; ?>" id="email" size="60" maxlength="60" /> <br /> <span style="font-size: 12px; font-style: italic;">This field is optional. It will be viewable to users.</span></td> </tr> <tr> <td><div align="right">Rooms</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="rooms"></label> <select name="rooms" id="rooms"> <option <?=($rows['rooms'] == '0') ? 'selected="selected"' : ''?>>0</option> <option <?=($rows['rooms'] == '1') ? 'selected="selected"' : ''?>>1</option> <option <?=($rows['rooms'] == '1.5') ? 'selected="selected"' : ''?>>1.5</option> <option <?=($rows['rooms'] == '2') ? 'selected="selected"' : ''?>>2</option> <option <?=($rows['rooms'] == '2.5') ? 'selected="selected"' : ''?>>2.5</option> <option <?=($rows['rooms'] == '3') ? 'selected="selected"' : ''?>>3</option> <option <?=($rows['rooms'] == '3.5') ? 'selected="selected"' : ''?>>3.5</option> <option <?=($rows['rooms'] == '4') ? 'selected="selected"' : ''?>>4</option> <option <?=($rows['rooms'] == '4.5') ? 'selected="selected"' : ''?>>4.5</option> <option <?=($rows['rooms'] == '5') ? 'selected="selected"' : ''?>>5</option> <option <?=($rows['rooms'] == '5.5') ? 'selected="selected"' : ''?>>5.5</option> <option <?=($rows['rooms'] == '6') ? 'selected="selected"' : ''?>>6</option> </select> 0 = Studio, 1 = 1 Bedroom, etc.</td> </tr> <tr> <td><div align="right">Bath</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="bath"></label> <select name="bath" id="bath"> <option <?=($rows['bath'] == '0') ? 'selected="selected"' : ''?>>0</option> <option <?=($rows['bath'] == '1') ? 'selected="selected"' : ''?>>1</option> <option <?=($rows['bath'] == '1.5') ? 'selected="selected"' : ''?>>1.5</option> <option <?=($rows['bath'] == '2') ? 'selected="selected"' : ''?>>2</option> <option <?=($rows['bath'] == '2.5') ? 'selected="selected"' : ''?>>2.5</option> <option <?=($rows['bath'] == '3') ? 'selected="selected"' : ''?>>3</option> <option <?=($rows['bath'] == '3.5') ? 'selected="selected"' : ''?>>3.5</option> <option <?=($rows['bath'] == '4') ? 'selected="selected"' : ''?>>4</option> </select></td> </tr> <tr> <td><div align="right">Square ft.</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="square"></label> <input name="square" type="text" value="<? echo $rows['square']; ?>" id="square" size="6" maxlength="6" /></td> </tr> <tr> <td><div align="right"><span style="color: #F00">*</span>Rent</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="rent"> $ <input name="rent" type="text" value="<? echo $rows['rent']; ?>" id="rent" size="10" maxlength="10" /> </label></td> </tr> <tr> <td><div align="right"><span style="color: #F00">*</span>Fees </div></td> <td><div align="center"> <p>: </p> </div></td> <td colspan="3" style="text-align: left"><label for="fees"></label> <span id="sprytextfield3"> <input name="fees" type="text" id="fees" value="<? echo $rows['fees']; ?>" size="90" /> </span></td> </tr> <tr> <td colspan="5" style="text-align: center; font-weight: bold; font-size: 18px; color: #F00;"> Video Link</td> </tr> <tr> <td><div align="right">URL</div></td> <td><div align="center">:</div></td> <td colspan="3"><p> </p> <p> <input name="url" type="text" id="url" value="<? echo $rows['url']; ?>"size="80" /> </td> </tr> <tr> <td><div align="center" style="color: #F00"> <div align="right">Name Your Video Link</div> </div></td> <td><div align="center"> <p>: </p> </div></td> <td colspan="3"><br /> <p> <input name="videotitle" type="text" id="videotitle" value="<? echo $rows['videotitle']; ?>"size="80" /> <br /> <span style="color: #E62E00">If you posted a URL for your video you must give it a title to give it a link.</span></p></td> </tr> <tr> <td colspan="2" style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl1']; ?>" width="200" /><br /></td> <td width="213" style="text-align: center"><img src="<? echo $rows['imageurl2']; ?>" width="200" /></td> <td width="180" style="text-align: center"><img src="<? echo $rows['imageurl3']; ?>" width="200" /></td> <td width="188" style="text-align: center"><img src="<? echo $rows['imageurl4']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><div align="center"> <input id="image3" type="file" name="image1" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image3" type="file" name="image2" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image3" type="file" name="image3" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image4" type="file" name="image4" /> </div></td> </tr> <tr> <td colspan="5" style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl5']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl6']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl7']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl8']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><input id="image5" type="file" name="image5" /></td> <td style="text-align: center"><input id="image6" type="file" name="image6" /></td> <td style="text-align: center"><input id="image7" type="file" name="image7" /></td> <td style="text-align: center"><input id="image8" type="file" name="image8" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl9']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl10']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl11']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl12']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><input id="image9" type="file" name="image9" /></td> <td style="text-align: center"><input id="image10" type="file" name="image10" /></td> <td style="text-align: center"><input id="image11" type="file" name="image11" /></td> <td style="text-align: center"><input id="image12" type="file" name="image12" /></td> </tr> <tr> <td colspan="5" style="text-align: center"> </td> </tr> <tr> <td colspan="5" style="text-align: center"><span style="color: #F00">*</span> REQUIRED FIELDS </td> </tr> <tr> <td colspan="5" style="text-align: center"> PRESS SUBMIT ONCE!!!</td> </tr> <tr> <td colspan="5" style="text-align: center"><input type="submit" name="button" id="button" value="Submit Changes" /> <input type="reset" name="button" id="button" value="Reset" /></td> </tr> </table> </form> </body> </html> The Script Code: [Select] <?php session_start(); include('SimpleImage.php'); $image = new SimpleImage(); //error_reporting(E_ALL); // image upload folder $image_folder = 'images/classified/'; // fieldnames in form $all_file_fields = array('image1', 'image2' ,'image3', 'image4', 'image5', 'image6', 'image7', 'image8', 'image9', 'image10', 'image11', 'image12'); // allowed filetypes $file_types = array('jpg','gif','png'); // max filesize 5mb $max_size = 5000000; //echo'<pre>';print_r($_FILES);exit; $time = time(); $count = 1; foreach($all_file_fields as $fieldname){ if($_FILES[$fieldname]['name'] != ''){ $type = substr($_FILES[$fieldname]['name'], -3, 3); // check filetype if(in_array(strtolower($type), $file_types)){ //check filesize if($_FILES[$fieldname]['size']>$max_size){ $error = "File too big. Max filesize is ".$max_size." MB"; }else{ // new filename $filename = str_replace(' ','',$myusername).'_'.$time.'_'.$count.'.'.$type; // move/upload file $image->load($_FILES[$fieldname]['tmp_name']); if($image->getWidth() > 150) { //if the image is larger that 150. $image->resizeToWidth(500); //resize to 500. } $target_path = $image_folder.basename($filename); //image path. $image->save($target_path); //save image to a directory. //save array with filenames $images[$count] = $image_folder.$filename; $count = $count+1; }//end if }else{ $error = "Please use jpg, gif, png files"; }//end if }//end if }//end foreach if($error != ''){ echo $error; }else{ //error_reporting(E_ALL); //ini_set('display_errors','On'); $id = $_POST['id']; $id = substr($id, 0,5); if($id < 1 || $id > 99999) exit; $servername = "localhost"; $username = ""; $password = ""; if(!$_POST["title"] || !$_POST["rent"] || !$_POST["fees"]){ header('location: fields.php'); }else if (!(preg_match('#^\d+(\.(\d{2}))?$#',($_POST["rent"])))){ header('location: rent.php'); }else{ $conn = mysql_connect($servername,$username,$password)or die(mysql_error()); mysql_select_db("genesis_apts",$conn); // validate id belongs to user $sql_check = "SELECT * FROM apartments WHERE id = '".$id."' AND username = '".$myusername."'"; $res = mysql_query($sql_check,$conn) or die(mysql_error()); $count = mysql_num_rows($res); if ($count > 0){ $sql = "UPDATE apartments SET title = '".mysql_real_escape_string($_POST['title'])."', description = '".mysql_real_escape_string($_POST['description'])."', cross_streets = '".mysql_real_escape_string($_POST['cross_streets'])."', county = '".mysql_real_escape_string($_POST['county'])."', town = '".mysql_real_escape_string($_POST['town'])."', service = '".mysql_real_escape_string($_POST['service'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', contact = '".mysql_real_escape_string($_POST['contact'])."', office = '".mysql_real_escape_string($_POST['office'])."', pets = '".mysql_real_escape_string($_POST['pets'])."', email = '".mysql_real_escape_string($_POST['email'])."', rooms = '".mysql_real_escape_string($_POST['rooms'])."', bath = '".mysql_real_escape_string($_POST['bath'])."', square = '".mysql_real_escape_string($_POST['square'])."', rent = '".mysql_real_escape_string($_POST['rent'])."', fees = '".mysql_real_escape_string($_POST['fees'])."', service = '".mysql_real_escape_string($_POST['service'])."', feeornofee = '".mysql_real_escape_string($_POST['feeornofee'])."', lease = '".mysql_real_escape_string($_POST['lease'])."', url = '".mysql_real_escape_string($_POST['url'])."', zipcode = '".mysql_real_escape_string($_POST['zipcode'])."', videotitle = '".mysql_real_escape_string($_POST['videotitle'])."', imageurl1 = '".mysql_real_escape_string($images[1])."', imageurl2 = '".mysql_real_escape_string($images[2])."', imageurl3 = '".mysql_real_escape_string($images[3])."', imageurl4 ='".mysql_real_escape_string($images[4])."', imageurl5 = '".mysql_real_escape_string($images[5])."', imageurl6 = '".mysql_real_escape_string($images[6])."', imageurl7 = '".mysql_real_escape_string($images[7])."', imageurl8 = '".mysql_real_escape_string($images[8])."', imageurl9 = '".mysql_real_escape_string($images[9])."', imageurl10 = '".mysql_real_escape_string($images[10])."', imageurl11 = '".mysql_real_escape_string($images[11])."', imageurl12 = '".mysql_real_escape_string($images[12])."' WHERE id = '".$id."'"; //replace info with the table name above $result = mysql_query($sql,$conn) or die(mysql_error()); header('location: apartments.php'); }else{ header('location: wrong.php'); } } } ?> I created scripting to upload multiple images simultaneously. The files sizes allowed for upload are 2 MB (or larger) and are then resized to approx 300kb each. In testing, I have discovered that the uploading terminated after 20 images. Is there a variable that needs to be re-defined in order to easily allow uploads of several hundred images? PS: I've seen several conflicting examples for defining max_file_size. What is the correct math to define this parameter? I want people to be able to post images on to my page but i want them to be able to add a caption when they post their image
This is the format I want the image and caption to be posted like
<div class="spacer"> </div> <div class="jokestary-img" title="Siri will screw up your relationship"> <img src="uploads/Siri will screw up your relationship.jpg" /> <div class="caption"><div>Siri will screw up your relationship.</div></div></div>The code for the upload form also wont work The page says "Upload complete!" before i even choose a file and doesnt send to my database ?php // properties of the uploaded file $name = $_FILES ["myfile"] ["name"]; $type = $_FILES ["myfile"] ["type"]; $size = $_FILES ["myfile"] ["size"]; $temp = $_FILES ["myfile"] ["tmp_name"]; $error= $_FILES ["myfile"] ["error"]; if ($error > 0) die ("Error uploading file! code $error."); else { if ($type== "video/av/png || $size 1000000") //conditions for file { die("That format is not allowed or file size too big"); } else move_uploaded_file($temp,"uploads/".$name); echo "Upload complete!"; } ?> |