PHP - Need Help With Upload Php Code
Hi all, i am new here, but i have a working upload php working inside a flash file.....
It working perfectly fine with uploading file onto my website. But i would like to add some code in it. Example: if you upload a file through it, i would like it to say " Your file have successfully uploaded" but i want to add the code, if you upload the same image.extension and same size, it would like it to say "Error - File exist!" <?php session_start(); $Directory = "image/"; $DAT = "file/"; $datei=$_GET['datei']; $txt1=$_GET['txt1']; $ok="0"; if ($_SESSION['ko']=="1") { session_unset(); echo "&message=File ".$_SESSION['tempdatei']." u. Information Process!&"; }else{ session_unset(); echo "&message=Server Error or Error File exists!&"; } if ($_FILES['Filedata']) { if (preg_match("/^.*?\.(pdf|wav|mp3|mov|wmv|mpeg|exe|avi|mpg|rar|zip|flv|xls|ppt|doc|mdb|txt|jpg|gif|png|swf|jpeg)$/si",$_FILES['Filedata']['name'])) { if($_FILES['Filedata']['size'] > 0 && $_FILES['Filedata']['size'] < 10485760) { $uploadfile = $Directory.basename($_FILES['Filedata']['name']); if (!file_exists($uploadfile)) { move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadfile); $_SESSION['ko']=$ok; $_SESSION['tempdatei']=$datei; }else{ echo "&message=check me out!&"; } chmod( $Directory. basename( $_FILES['Filedata']['name']),0644); if (!chmod( $Directory. basename( $_FILES['Filedata']['name']),0644)) { fail("The permissions failed to set to 0644."); } $tx=$DAT.$datei.".txt"; $fp= fopen($tx,'w+'); fwrite($fp,$txt1); fclose($fp); $ok="1"; }}} ?> Similar TutorialsI have an image upload script where I am trying to compress an image to a lower file size. The code works. The image uploads to the directory with the correct name as intended. The only thing is that it's not compression the image as it should be. The size of the new image is the same as the old image. Here's my code. Can you spot what i'm doing wrong? // FUNCTION FOR COMPRESSION function compress_image($source_url, $destination_url, $quality) { $info = getimagesize($source_url); if($info['mime'] == 'image/jpeg') { $image = imagecreatefromjpeg($source_url); } else if ($info['mime'] == 'image/gif') { $image = imagecreatefromgif($source_url); } else if ($info['mime'] == 'image/png') { $image = imagecreatefrompng($source_url); imagejpeg($image, $destination_url, $quality); } return $destination_url; } // FORM SUBMIT CODE $errors = array(); $db->beginTransaction(); if(isset($_FILES['fileToUpload']) AND !empty($_FILES['fileToUpload']["name"])) { if(is_uploaded_file($_FILES['fileToUpload']["tmp_name"])) { // GENERATES A 10 CHARACTER STRING TO BE USED FOR AN IMAGE NAME $random_name = generateRandomString(10); $global_user_id = 10; $url_project_id = 5; $target_dir = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/'; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); if(!is_dir($target_dir)){ mkdir($target_dir, 0775, true); } // RESIZE IMAGE $pathname = $_FILES["fileToUpload"]["tmp_name"]; $resized_image = compress_image($pathname, $random_name, 40); $new_file_path = $target_dir . $resized_image . '.' . $imageFileType; // Check if image file is a actual image or fake image $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { // echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { $errors[] = 'File is not an image!'; $uploadOk = 0; } // Check if file already exists if (file_exists($new_file_path)) { $errors[] = 'Sorry, file already exists!'; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 5000000) { $errors[] = 'Sorry, your file size is bigger than 5mb!'; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG" && $imageFileType != "GIF") { $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed!'; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if($uploadOk == 0) { $errors[] = 'Sorry, your file was not uploaded!'; // if everything is ok, try to upload file } else { if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $new_file_path)) { // SUCCESS MESSAGE } else { $errors[] = 'Sorry, there was an error uploading your file!'; } } } else { $errors[] = 'You must upload an image!'; } } if(empty($errors)) { $db->commit(); header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); exit; } else { $db->rollBack(); }
Hello, I've looked everywhere for help, is there any chance anyone here that knows of PHP can help me out? I have this snippet of code for uploading files. I really want it to rename the files with a date and/or time or anything random at the end of the image's name as it uploads. Would be an amazing help!! Thanks! Here is the code. Code: [Select] <?php // Set the uplaod directory $uploadDir = '/images/'; if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name'][0]; $uploadDir = $_SERVER['DOCUMENT_ROOT'] . $uploadDir; $targetFile = $uploadDir . $_FILES['Filedata']['name'][0]; // Validate the file type $fileTypes = array('jpg'); // Allowed file extensions $fileParts = pathinfo($_FILES['Filedata']['name'][0]); // Validate the filetype if (in_array($fileParts['extension'], $fileTypes)) { // Save the file move_uploaded_file($tempFile,$targetFile); echo 1; } else { // The file type wasn't allowed echo 'Invalid file type.'; } } ?> 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]; } } } Hello everybody,
i have an easy short code to upload multiple photos to "images" directory.
after upload each file, i give it unique name.
the problem i have is:
i want see the name of uploaded files and print this using echo as in line 21.
the line 21 gives me names but not the same names of uploaded files!
thank you very much for your help.
Rafal
<?php foreach ($_FILES['file']['name'] as $i => $name) { $types = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $name); $extension = end($temp); if ($_FILES["file"]["size"][$i] < 10240000 && in_array($extension, $types)) { if ($_FILES["file"]["error"][$i] > 0) { echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br>"; } else { if (file_exists("images/" . $name)) { } else { move_uploaded_file($_FILES["file"]["tmp_name"][$i], "images/" . uniqid() . "." . $extension); echo "uploaded " . $_FILES["file"] , uniqid() . "." . $extension ; echo "<br>"; } } } else { $error = "Invalid file"; } } ?> <html> <head> <title></title> </head> <body> <form enctype="multipart/form-data" action="photo.php" method="POST"> <input type="file" name="file[]" id="file" ><br> <input type="file" name="file[]" id="file" ><br> <input type="file" name="file[]" id="file" ><br> <input type="file" name="file[]" id="file" ><br> <input type="submit" value="upload"> </form> </body> </html> Hi 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. 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> 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, I have some code which displays my blog post in a foreach loop, and I want to add some social sharing code(FB like button, share on Twitter etc.), but the problem is the way I have my code now, creates 3 instances of the sharing buttons, but if you like one post, all three are liked and any thing you do affects all of the blog post. How can I fix this? <?php include ("includes/includes.php"); $blogPosts = GetBlogPosts(); foreach ($blogPosts as $post) { echo "<div class='post'>"; echo "<h2>" . $post->title . "</h2>"; echo "<p class='postnote'>" . $post->post . "</p"; echo "<span class='footer'>Posted By: " . $post->author . "</span>"; echo "<span class='footer'>Posted On: " . $post->datePosted . "</span>"; echo "<span class='footer'>Tags: " . $post->tags . "</span>"; echo ' <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_counter addthis_pill_style"></a> </div> <script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=webguync"></script>'; echo "</div>"; } ?> I have the following code in html: <html> <head> <script type="text/javascript"> <!-- function delayer(){ window.location = "http://VARIABLEVALUE.mysite.com" } //--> </script> <title>Redirecting ...</title> </head> <body onLoad="setTimeout('delayer()', 1000)"> <script type="text/javascript"> var sc_project=71304545; var sc_invisible=1; var sc_security="9c433fretre"; </script> <script type="text/javascript" src="http://www.statcounter.com/counter/counter.js"></script><noscript> <div class="statcounter"><a title="vBulletin statistics" href="http://statcounter.com/vbulletin/" target="_blank"><img class="statcounter" src="http://c.statcounter.com/71304545/0/9c433fretre/1/" alt="vBulletin statistics" ></a></div></noscript> </body> </html> Is a basic html webpage with a timer redirect script and a stascounter code. I know a bit about html and javascript, but almost nothing about php. My question is: How a can convert this html code into a php file, in order to send a variable value using GET Method and display this variable value inside the javascript code where says VARIABLEVALUE. Thanks in adavance for your help. 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. 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 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 Hi I was wondering if anyone could help me out with a code problem. I am not very advanced with php but I do try to learn and I have been trying to figure out how to do something for a few hours now and im hoping someone here can help. Basically I have a php form with an upload box that posts data to my database this all works perfectly but my problem now is editing my data. When I edit the data and ignore the upload box it deletes the currect image in my database that I originally added. How can I edit the code so it keeps the currect image if the upload box is left blank. This is my currect modify page code: Code: [Select] <?php //This is the directory where images will be saved $target = "images/products/"; $target = $target . basename( $_FILES['link_image']['name']); //This gets all the other information from the form $link_image=($_FILES['link_image']['name']); //Writes the photo to the server if(move_uploaded_file($_FILES['link_image']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } #+--------------------------------------- $short_desc = $_POST['short_desc']; $url = $_POST['url']; $category = $_POST['category']; $designers = $_POST['designers']; $shop = $_POST['shop']; $price = $_POST['price']; $rss_long_desc = $_POST['rss_long_desc']; $long_desc = $_POST['long_desc']; $news_id = $_POST['news_id']; $todays_date = date('Y-m-j H:i:s'); #+--------------------------------------- $modify_news_query = "UPDATE "; $modify_news_query .= $tbl_news; $modify_news_query .= " SET "; $modify_news_query .= " short_desc='" . $short_desc . "', "; $modify_news_query .= " rss_long_desc='" . $rss_long_desc . "', "; $modify_news_query .= " url='" . $url . "', "; $modify_news_query .= " date_added='" . $todays_date . "', "; $modify_news_query .= " link_image='" . $link_image . "', "; $modify_news_query .= " price='" . $price . "', "; $modify_news_query .= " category='" . $category . "', "; $modify_news_query .= " designers='" . $designers . "', "; $modify_news_query .= " shop='" . $shop . "' "; $modify_news_query .= " WHERE news_id='" . $news_id . "'"; $modify_news_query .= ";"; $modify_news_result = domysql($modify_news_query,'updating 1 news item in ' . $_SERVER['PHP_SELF']); $action = ''; $message = "Updated Item : '" . $short_desc . "'"; //echo "Modifying news item ".$news_id." with query: ".$modify_news_query; #+--------------------------------------- ?> <script type="text/javascript"> <!-- function x() { window.location.href = "admin.php?news_action=preview&indexKey=<?php echo $news_id;?>" } x() --> </script> 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 I am currently using a form for uploading resumes. <?php $target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition if ($uploaded_size > 350000) { echo "Your file is too large.<br>"; $ok=0; } //This is our limit file type condition if ($uploaded_type =="text/php") { echo "No PHP files<br>"; $ok=0; } //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } /* this part can either be in the same file as the form or it can be in a different file. If you want this in a different file, make the "action" of the form go to that file */ if(sizeof($_POST)) { $body = ""; while(list($key, $val) = each($HTTP_POST_VARS)) { $body .= "$key: $val \n"; } mail("xx@xx.com", // to "Resume", $body, "From:".$Email); } // end form processing ?> I am hoping that if no file is uploaded it skips the upload process and just sends the email. Also how can i make it so when the file is uploaded it is renamed to "Resume - Users first and last name" Thanks |