PHP - Pdf Upload
Hey Im trying to upload a pdf file into a blob in a database. This script worked to insert images and I made a few minor changes so that it could do the same for pdf files. Only when i run the script in a browser it says error unknown file format. I dont understand this because I do list pdf as a valid file format. The txt and the doc possible file uploads are just there to take up spots where jpeg and gif were in the picture script i have no intention of actually uploading those. The file i tested was yes a pdf so that cant be the issue. Heres the script.
Code: [Select] <?php $db_host = 'localhost'; // don't forget to change $db_user = 'root'; $db_pwd = 'dbpassword'; $database = 'mydbname'; $table = 'lit_gallery'; // use the same name as SQL table $password = '123'; // simple upload restriction, // to disallow uploading to everyone if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s){ if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s);} // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST'){ // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(empty title)'; // use (empty title) string if ($_POST['password'] != $password)// cheking passwors $msg = 'Error: wrong upload password'; else { if (isset($_FILES['book'])) { @list(, , $ftype, ) = getimagesize($_FILES['book']['tmp_name']); // Get file type. // We use @ to omit errors if ($ftype == 3) // cheking image type $ext="pdf"; // to use it later in HTTP header elseif ($ftype == 2) $ext="txt"; elseif ($imtype == 1) $ext="doc"; else $msg = 'Error: unknown file format'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['book']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: pdf uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded'; // to make sure we've using // upload form, not form // for deletion if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form' $id = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE id=$id"); $msg = 'Book deleted'; } } } elseif (isset($_GET['show'])){ $id = intval($_GET['show']); $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(book_time), data FROM {$table} WHERE id=$id LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $book_time, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $book_time)) // and grater than $send_304 = true; // image_time } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing Last-Modified header header('Last-Modified: '.gmdate('D, d M Y H:i:s', $book_time).' GMT', true, 200); // Set expiration time +1 year // We do not have any photo re-uploading // so, browser may cache this photo for quite a long time header('Expires: '.gmdate('D, d M Y H:i:s', $book_time + 86400*365).' GMT', true, 200); // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: application/{$ext}"); // outputing book echo $data; exit(); } ?> <head> <title>MySQL Blob Image Gallery Example</title> <link rel="stylesheet" type="text/css" href="test.css"/> </head> <html> <body> <?php if (isset($msg)) // this is special section for // outputing message { ?> <p style="font-weight: bold;"><?=$msg?><br><a href="<?=$PHP_SELF?>">reload page</a><!-- I've added reloading link, because refreshing POST queries is not good idea --></p> <?php } ?> <h1>Blob image gallery</h1> <h2>Uploaded images:</h2> <form action="<?=$PHP_SELF?>" method="post"> <!-- This form is used for image deletion --> <?php $result = mysql_query("SELECT id, book_time, title FROM {$table} ORDER BY id DESC"); if (mysql_num_rows($result) == 0) // table is empty echo '<ul><li>No images loaded</li></ul>'; else{ echo '<ul>'; while(list($id, $book_time, $title) = mysql_fetch_row($result)) { // outputing list echo "<li><input type='radio' name='del' value='{$id}'>"; echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – "; echo "<small>{$book_time}</small></li>"; } echo '</ul>'; echo '<label for="password">Password:</label><br>'; echo '<input type="password" name="password" id="password"><br><br>'; echo '<input type="submit" value="Delete selected">'; } ?> <html> <body> </form><h2>Upload new image:</h2><form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"> <label for="title">Title:</label><br><input type="text" name="title" id="title" size="64"><br> <br> <label for="book">Book:</label><br><input type="file" name="book" id="book"><br> <br> <label for="password">Password:</label><br><input type="password" name="password" id="password"><br> <br><input type="submit" value="upload"></form> </body> </html> Similar TutorialsHi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks I 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 files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
I have made this script to upload to an ftp server. How do I get the script to try to restart the upload if it fails? (if if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) returns false) Code: [Select] <?php $file = 'file.wmv'; $remote_file = 'file.wmv'; // set up basic connection $conn_id = ftp_connect('ftp.eu.filesonic.com'); $ftp_user_name='username'; $ftp_user_pass='password'; // login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // upload a file if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) { echo "successfully uploaded $file\n"; } else { echo "There was a problem while uploading $file\n"; } // close the connection ftp_close($conn_id); ?> Can someone Help me I made a code for uploading files to database.. but how can i retrieve it? Is it possible to open the pdf file in browser? Im using XAMPP MySql.. SOMEONE HELP ME PLS. Hi there We are hosting a web server that requires large files (100MB+) to be uploaded to it. We are using PHP upload scripts, and it is working, but we are getting complaints that the uploads are unreliable (some files fail to upload, with no error messages). I have been reading on various forums that FTP should rather be used for larger files, rather than HTTP. But from what I can see, there are some limitations, and I was wondering if there are any ways around these: - Using cURL would mean that the files would first be uploaded to a temp folder on the web server via HTTP, and then only sent via FTP. This defeats the purpose, because if it is already on the Web Server (which is hosted locally), then I might just as well move the file. - Using the built in FTP functionality of PHP, it appears that ones needs to know the full path of the source file. The users who are uploading files are accessing the Web server via a form in a browser, which will not give the PHP script the full path of the file to be uploaded. All we want is to have a reliable means for an end-user to access a site with a browser, fill in a form, choose a file to upload, and submit it. Additional functionality, like a progress bar, the ability to select multiple files and a resume option for failed uploads, would all be very nice. But the main concern is that the transfers be more reliable. Thanks for any advice. Mills 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. When i use the following script to upload and resize an image, it throws out errors (see after script) <?php $image = $_FILES['image']['name']; $uploaddir = "./images/$gender/"; $pext = getExtension($image); $pext = strtolower($pext); if (($pext != "jpg") && ($pext != "jpeg") && ($pext != "gif")) { print "<h1>ERROR</h1>Image Extension Unknown.<br>"; print "<p>Please upload only an image with the extension .jpg or .jpeg or .gif ONLY<br><br>"; print "The file you uploaded had the following extension: $pext</p>\n"; unlink($imgfile); exit(); } $imgsize = GetImageSize($image); /*== check size 0=width, 1=height ==*/ if (($imgsize[0] > 460) || ($imgsize[1] > 345)) { $tmpimg = tempnam("/tmp", "MKUP"); system("djpeg $image >$tmpimg"); system("pnmscale -xy 250 200 $tmpimg | cjpeg -smoo 10 -qual 50 >$imgfile"); unlink($tmpimg); } $rand = rand(0,9999999); $date = DATE("d.m.y"); $image_name=$date.$id.$rand.'.'.$extension; $final_filename = str_replace(" ", "_", $image_name); $newfile = $uploaddir . "/$final_filename"; if (is_uploaded_file($image)) { if (!copy($imgfile,"$newfile")) { print "Error Uploading File."; exit(); } } unlink($image); print("<img src=\"$newfile\">"); ?> errors: Quote Warning: getimagesize((R)Photo-0027.jpg) [function.getimagesize]: failed to open stream: No such file or directory in /home/bumwarsc/public_html/images.php on line 77 Warning: unlink((R)Photo-0027.jpg) [function.unlink]: No such file or directory in /home/bumwarsc/public_html/images.php on line 126 Has anyone had any success doing this? I'm not sure if I should try to write this myself or use some kind of framework. I found the Zend Gdata framework (http://framework.zend.com/manual/en/zend.gdata.html) and tried it out but I kept getting error: Warning: include_once() [function.include]: Failed opening '1' for inclusion (include_path='.:/usr/share/pear') I'm assuming it needs to find PEAR which I don't have installed but no where in the Zend docs does it say that it requires PEAR so I'm a little confused. I've never used any of the Zend frameworks so I have no idea if it needs PEAR or not. Anyone have any other methods for doing this? thanks. Hi, i have in my script the following : $pid = mysql_insert_id(); //place image in the folder $newname = "$pid.jpg"; move_uploaded_file($_FILES['fileField']['tmp_name'],"../inventory_images/$newname"); header("location: inventory_list.php"); exit(); but i can't figure out how to upload more than one image. Thanks! This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=310954.0 I am beginner in PHP and i tried to find a tutorial on this subject across the web, but all i found was one tutorial how to store image like blob and a lot of scripts (which at the moment I don't understand). I want to create form to upload image to specific folder and then to insert image name and path into DB. If you know some tutorial on this subject please let me know, or if someone can help to write it it would be great . Hi Guys, I'm sure my logic is off somewhere in my code, basicaly i resize an uploaded image and move to it's location depending on whether it came from the US or UK site: Resize Function: function resize_image($uploadDirectory, $newFileName, $us = false) { $original_image = $uploadDirectory; $ext = substr($original_image, strrpos($original_image, '.') + 1); $canvas_width = 65; $canvas_height = 65; $canvas = imagecreatetruecolor($canvas_width, $canvas_height); $white_background = imagecolorallocate($canvas, 255, 255, 255); imagefill($canvas, 0, 0, $white_background); list($image_width, $image_height) = getimagesize($uploadDirectory); $ratio = $image_width / $image_height; if ($ratio > 1) { $new_image_width = 65; $new_image_height = 65 / $ratio; } //$ratio > 1 else { $new_image_width = (float) 65 * $ratio; $new_image_height = 65; } if ($ext == "jpg") { $original_image = imagecreatefromjpeg($original_image); } //$ext == "jpg" if ($ext == "gif") { $original_image = imagecreatefromgif($original_image); } //$ext == "gif" imagecopyresampled($canvas, $original_image, 0, 0, 0, 0, $new_image_width, $new_image_height, $image_width, $image_height); $new_thumbnail_name = "thumb-$newFileName"; if ($ext == "jpg") { if ($us) { imagejpeg($canvas, "../../site.com/imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } else { imagejpeg($canvas, "../imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } } //$ext == "jpg" if ($ext == "gif") { if ($us) { imagegif($canvas, "../../first-site.com/imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } else { imagegif($canvas, "../imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } } //$ext == "gif" imagedestroy($original_image); imagedestroy($canvas); } Upload Code: <?php if (isset($_POST['submit-add-product'])) { $productNM = ucwords($_POST['txt-product-name']); $productDS = escape_data($_POST['txt-product-description'], 1); $productPM = $_POST['txt-product-p-medicine']; $productCT = $_POST['txt-product-category']; $productPR = $_POST['txt-product-price']; $productST = $_POST['txtSite']; $fileName = $_FILES['txt-product-image']['name']; $fileTemp = $_FILES['txt-product-image']['tmp_name']; $fileType = $_FILES['txt-product-image']['type']; $fileSize = $_FILES['txt-product-image']['size']; /*if (!empty($_FILES['txt-product-image-2']['name'])) { $fileName2nd = $_FILES['txt-product-image-2']['name']; $fileTemp2nd = $_FILES['txt-product-image-2']['tmp_name']; $fileType2nd = $_FILES['txt-product-image-2']['type']; $fileSize2nd = $_FILES['txt-product-image-2']['size']; $fileExtension = substr(strrchr($fileName2nd, '.'), 0); $fileExtension = strtolower($fileExtension); $replacedName2nd = str_replace(" ", "-", $productNM . "-2nd"); $newFileName2nd = "$replacedName2nd-" . time() . "$fileExtension"; $uploadDirectory2nd = "../imgProducts/img-fs/$newFileName2nd"; $generate2ndImage = true; } //!empty($_FILES['txt-product-image-2']['name']) if (empty($productNM)) { print "<p class=\"fcp-message-error\">You never entered a product name.</p>"; } //empty($productNM) if (empty($productDS)) { print "<p class=\"fcp-message-error\">You never entered a product description.</p>"; } //empty($productDS) if (empty($productPR)) { print "<p class=\"fcp-message-error\">You never entered a product price.</p>"; } //empty($productPR) if (empty($fileSize)) { print "<p class=\"fcp-message-error\">You never entered a product image.</p>"; } //empty($fileSize) if (!isImageFile($fileType)) { print "<p class=\"fcp-message-error\">The file you uploaded doesn't seem to be an image.</p>"; } //!isImageFile($fileType)*/ $fileExtension = substr(strrchr($fileName, '.'), 0); $fileExtension = strtolower($fileExtension); $replacedName = str_replace(" ", "-", $productNM); $newFileName = "$replacedName-" . time() . "$fileExtension"; $uploadDirectory = "../imgProducts/img-fs/$newFileName"; // US // if ($productST == "US") { $uploadDirectory = "../../first-choice-pharmacy.com/imgProducts/img-fs/$newFileName"; //move_uploaded_file($fileTemp, $uploadDirectory2nd); if (move_uploaded_file($fileTemp, $uploadDirectory)) { $productWM = watermark_image($uploadDirectory, $newFileName, 1); $productTH = resize_image($uploadDirectory, $newFileName, 1); } //move_uploaded_file($fileTemp, $uploadDirectory) /*if (isset($generate2ndImage)) { watermark_image($uploadDirectory2nd, $fileTemp2nd); move_uploaded_file($fileTemp2nd, $uploadDirectory2nd); } //isset($generate2ndImage)*/ $qI = mysql_query("INSERT INTO `fcpv3_products` (`id`,`category_id`,`product_name`,`product_description`,`product_thumbnail`,`product_fullsize`,`product_fullsize_second`,`product_price`,`product_weight`,`p_med`,`is_breakable`,`site`,`date_added`) VALUES ('','$productCT','$productNM','$productDS','$productTH','$newFileName','$newFileName2nd','$productPR','0.00','$productPM','N','US',NOW())"); if ($_POST['updateTwitter'] == "yes") { $last_product_id = mysql_insert_id(); $twitter_url = generate_seo_friendly_links($productNM, $last_product_id); $username = 'firstchoicephar'; $password = ''; $status = urlencode(stripslashes(urldecode('We just added ' . $productNM . ' http://www.firstchoicepharmacy.co.uk/product.php?id=' . mysql_insert_id()))); if ($status) { $tweetUrl = 'http://www.twitter.com/statuses/update.xml'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$tweetUrl"); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status"); curl_setopt($curl, CURLOPT_USERPWD, "$username:$password"); $result = curl_exec($curl); $resultArray = curl_getinfo($curl); if ($resultArray['http_code'] == 200) { print "<p class=\"fcp-message-success\">Tweet made successfully :).</p>"; } //$resultArray['http_code'] == 200 else { print '<p class="fcp-message-error">OOPS, an error has occured Posting to twitter, please contact the site administrator.</p>'; curl_close($curl); } } //$status if ($qI) { print "<p class=\"fcp-message-success\">You have successfully added a new product.</p>"; } //$qI else { print '<p class="fcp-message-error">OOPS, an error has occured please contact the site administrator.</p>'; } } //$_POST['updateTwitter'] == "yes" } elseif($productST == "UK") { if (move_uploaded_file($fileTemp, $uploadDirectory)) { $productWM = watermark_image($uploadDirectory, $newFileName); $productTH = resize_image($uploadDirectory, $newFileName); } //move_uploaded_file($fileTemp, $uploadDirectory) /*if (isset($generate2ndImage)) { watermark_image($uploadDirectory2nd, $fileTemp2nd); move_uploaded_file($fileTemp2nd, $uploadDirectory2nd); } //isset($generate2ndImage)*/ $qI = mysql_query("INSERT INTO `fcpv3_products` (`id`,`category_id`,`product_name`,`product_description`,`product_thumbnail`,`product_fullsize`,`product_fullsize_second`,`product_price`,`product_weight`,`p_med`,`is_breakable`,`site`,`date_added`) VALUES ('','$productCT','$productNM','$productDS','$productTH','$newFileName','$newFileName2nd','$productPR','0.00','$productPM','N','UK',NOW())"); if ($_POST['updateTwitter'] == "yes") { $last_product_id = mysql_insert_id(); $twitter_url = generate_seo_friendly_links($productNM, $last_product_id); $username = 'firstchoicephar'; $password = 'milr'; $status = urlencode(stripslashes(urldecode('We just added ' . $productNM . ' http://www.firstchoicepharmacy.co.uk/product.php?id=' . mysql_insert_id()))); if ($status) { $tweetUrl = 'http://www.twitter.com/statuses/update.xml'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$tweetUrl"); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status"); curl_setopt($curl, CURLOPT_USERPWD, "$username:$password"); $result = curl_exec($curl); $resultArray = curl_getinfo($curl); if ($resultArray['http_code'] == 200) { print "<p class=\"fcp-message-success\">Tweet made successfully :).</p>"; } //$resultArray['http_code'] == 200 else { print '<p class="fcp-message-error">OOPS, an error has occured Posting to twitter, please contact the site administrator.</p>'; curl_close($curl); } } //$status if ($qI) { print "<p class=\"fcp-message-success\">You have successfully added a new product.</p>"; } //$qI else { print '<p class="fcp-message-error">OOPS, an error has occured please contact the site administrator.</p>'; } } //$_POST['updateTwitter'] == "yes" } } //isset($_POST['submit-add-product']) ?> When i change the $us flag the US site works and the UK one doesn't, the full size image always gets uploaded fine it appears to be my logic in the resize function (i think ) a fresh pair of eyes would be great thanks guys Graham I am trying to create a simple batch upload to "attach" to client's sites so they can use that in order to send me photos. I have been searching for a script and don't see one. I did find this, but it has no FORM to use: Code: [Select] <?php set_time_limit(0); $dir = "/path/to/the/uploaded/pictures/"; // trailing slash $moveto = "/path/to/where/they/should/be/copied/"; // trailing slash $files = glob($dir . "*.jp{e,}g"); // list of files, sorted by name $i = 1; // numbering foreach ($files as $filename) { $image = imagecreatefromjpeg($filename); if (!$image) continue; // load $w = imagesx($image); $h = imagesy($image); // width, height $neww = 140; $newh = $h * $neww / $w; // resized $thumb = imagecreatetruecolor($neww, $newh); imagecopyresampled($thumb, $image, 0, 0, 0, 0, $neww, $newh, $w, $h); // create thumbnail imagejpeg($image, $moveto . $i . ".jpg"); // copy original imagejpeg($thumb, $moveto . $i . "_th.jpg"); // copy thumbnail // optional: echo "copied ", basename($filename), " (orig: $w, $h) to $i (thumb: $neww, $newh)<br>\n"; $i++; imagedestroy($image); imagedestroy($thumb); } ?> ??? Would I just need to add a TEXTAREA to it, and then people can drag-and-drop .JPGs into it and it will automatically upload the files? I am not certain. I would have thought there would be a free script for this, since it's so common. I currently have the following script used on my site to upload files. When the linked web page executes it, however, I receive the infamous Parse Error - Unexpected '<' in x:/xxxx. The problem lies in Line 11 where I attempt to define a command that will display a message box to the user upon successful file upload. The syntax is not correct and I was hoping someone would be able to help me with it. Here is the contents of the PHP file. <?php // Where the file is going to be placed $target_path = $_SERVER['DOCUMENT_ROOT'] . "/file_uploads/"; /*Add the original filename to our target path. Result is "uploads/filename.extension"*/ $target_path=$target_path.basename($_FILES['file']['name']); //Move file to upload directory if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { echo <script type="text/javascript">alert("Upload was successful. Thank you for your contribution")</script>; } else{ echo "There was a problem submitting the file. Plese try again!"; } ?> Thank you in advance for any help. I am looking to allow people to also upload pdf and doc ad txt files can you show me how to convert this script . Thanks. Code: [Select] [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"); if (in_array($file['type'], $valid_types)) return 1; return 0; } [/php] Hi Guys! I already have a database with a table that stores information about different franchises for the company like franchise name, address, tel, email etc etc. This works beautiful so I can CRUD this data. However, now to be able to add the facility for each franchise to be able to upload their own image of the franchise itself and still be able to CRUD the data. I have looked on the internet and found many scripts using BLOB etc but I can get it to link in with my existing table. I'll show you the edit form that I have so far. (Pleas not Ter = territory, ie the territory that franchise covers. <?php include('config.php'); if (isset($_GET['Ter']) ) { $ter = (int) $_GET['Ter']; if (isset($_POST['submitted'])) { foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } $sql= "UPDATE `ter` SET `Ter` = '{$_POST['Ter']}' , `BranchName` = '{$_POST['BranchName']}' , `BranchAddress` = '{$_POST['BranchAddress']}' , `BranchTel` = '{$_POST['BranchTel']}' , `BranchEmail` = '{$_POST['BranchEmail']}' , `BranchLink` = '{$_POST['BranchLink']}' , `Theme` = '{$_POST['Theme']}' , `LocalInfo` = '{$_POST['LocalInfo']}' , `BranchInfo` = '{$_POST['BranchInfo']}' WHERE `Ter` = '$ter' "; mysql_query($sql) or die(mysql_error()); echo (mysql_affected_rows()) ? "Edited Branch.<br />" : "Nothing changed. <br />"; } $row = mysql_fetch_array ( mysql_query("SELECT * FROM `ter` WHERE `Ter` = '$ter' ")); ?> <form action='' method='POST'> <p><b>Territory:</b><br /><input name='Ter' type='text' value='<?= stripslashes($row['Ter']) ?>' size="3" readonly="readonly" /> <p><b>Branch Name:</b><br /><input name='BranchName' type='text' value='<?= stripslashes($row['BranchName']) ?>' size="50" /> <p><b>Address:</b><br /> <textarea name='BranchAddress' cols="40" rows="5"><?= stripslashes($row['BranchAddress']) ?></textarea> <p><b>Telephone:</b><br /><input name='BranchTel' type='text' value='<?= stripslashes($row['BranchTel']) ?>' size="15" /> <p><b>Email:</b><br /><input name='BranchEmail' type='text' value='<?= stripslashes($row['BranchEmail']) ?>' size="50" /> <p><b>Link:</b><br /><input name='BranchLink' type='text' value='<?= stripslashes($row['BranchLink']) ?>' size="50" /> <hr /> <p><b>Your Single Webpage Options</b> <p><b>Theme:</b><br /> <input name='Theme' type='text' value='<?= stripslashes($row['Theme']) ?>' size="1" /> <p><b>Local Information:</b><br /> <textarea name='LocalInfo' cols="85" rows="8" id="LocalInfo"><?= stripslashes($row['LocalInfo']) ?> </textarea> <p><b>Franchise Information:</b><br /> <textarea name='BranchInfo' cols="85" rows="8" id="BranchInfo"><?= stripslashes($row['BranchInfo']) ?> </textarea> <p><b>Photo:</b><br /> <label> <input type="file" name="photo" id="photo" /> </label> (Franchise Photo) <p><b>Downloads:</b><br /> <label> <input type="file" name="download1" id="download1" /> </label> (S/O Mandate) <p> <label> <input type="file" name="download2" id="download2" /> </label> (Other Download) <p> <label> <input type="file" name="download3" id="download3" /> </label> (Other Download) <p> <input type='submit' value='Save' /> <input type='hidden' value='1' name='submitted' /> </form> <? } ?> It is the 'photo' file above that I want to be able to upload the image with. Is this the right way to do it? Ignore the download1,2,3 bit. Cheers, S Dear user I write a file upload code in php, the code work's fine but it will upload the file up to 60 KB, when i try to upload more then 60 KB file then the page stuck on loading. The problem is why it is not uploading more then 60kb file? is there any fault in my code please check it out.. My form.php code is... <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="css/bootstrap.css"/> <link rel="stylesheet" href="css/bootstrap.min.css"/> </head> <body> <div class="col-md-6"> <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="">Item</label><br/> <input type="file" name="picture" class="form-control"><br/> <label for="">Description</label><br/> <textarea name="description" id="" placeholder="Enter Item Description" class="form-control" cols="50" rows="20"></textarea><br/> <input type="submit" name="submit" value="Upload" class="btn btn-success"> </form> </div> <script src="js/bootstrap.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery-2.1.1.min.js"></script> <body> </html>my upload.php code is <?php include 'conn.php'; $desc=$_POST['description']; $image=$_FILES['picture']; $image_name=$_FILES['picture']['name']; $placed='uploads/'; if(move_uploaded_file($_FILES['picture']['tmp_name'],$placed.$image_name)) { $smt=$conn->prepare("INSERT INTO images(Image_Name,Description,Placed_On)VALUES('".$image_name."','".$desc."','".$placed."')"); $smt->execute(); header('location:form.php'); } else { echo 'error on uploading file'; } ?> anybody know of any tutorials on how to make an upload to server form? ive been searching google for hours and it seems as though all the scripts on there just upload to php temp. i need to make it goto a specific folder on the server. thanks hello i am wondering how to upload an image into mysql, i am wanting to upload it with some more fields, this is my codei wish to add the image upload. add_recipie.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 method="POST" action="include/recipe.php"> <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 name="prep" type="text" size="7" maxlength="10" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Cooking time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="cook" type="text" size="7" maxlength="10" /> </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 name="submit" type="submit" style="padding:5px 10px;" value="Submit" /></td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> |