PHP - Saving Image To Certain Directory
Hello dear,
I'm willing to use thumbnails into my website which is mainly like websites directory. I've been thinking to save url thumbnails into certain directory ! If i've index.php with the following image code (this would show thumbnail image of the website ANY_SITE.COM Code: [Select] <img src='http://thumbnails_provider.com/url=ANY_SITE.COM'/> then how to save the generated image into certain directory like my_site.com/thumbnails i've been thinking about Using cURL but i don't know how to apply it any help ~thanks Similar TutorialsHello, Its my first day coding so please forgive me for some of the silly errors I might make.
I am writing a small upload script and I want to have some sort of orginazation by uploading images to a direcotry based on the day. The following is my code but it will fail to save the file Warning: file_put_contents(images/14-09-26/5425905a18bba.png): failed to open stream: No such file or directory This is becuase the directory with the data part is not created how should I go about first checking that this directory is there and then creating it ? <?php ini_set('display_errors',1); error_reporting(E_ALL); $today = date('y-m-j'); define('UPLOAD_DIR', 'images/' .$today. '/'); $img = $_POST['data']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = UPLOAD_DIR . uniqid() . '.png'; $success = file_put_contents($file, $data); print $success ? $file : 'Unable to save the file.'; ?> Hi I'm really new to php and could really do with some help. I am using the following script http://test.dpetroff.ru/jquery.iviewer.test/test/ which basically allows me to position an image within a DIV area My question is, how can I get PHP to save just the image within the DIV area, so it's almost acting like a crop tool I've tried a few things but so far not managed to get anything working Hi Guys, Using this code i am able to overlay a logo onto an image: <?php // Load the image where the logo will be embeded into $image = imagecreatefromjpeg("box.jpg"); // Load the logo image $logoImage = imagecreatefrompng("logo.png"); imagealphablending($logoImage, true); // Get dimensions $imageWidth=imagesx($image); $imageHeight=imagesy($image); $logoWidth=imagesx($logoImage); $logoHeight=imagesy($logoImage); // Paste the logo imagecopy( // source $image, // destination $logoImage, // destination x and y $imageWidth-$logoWidth, $imageHeight-$logoHeight, // source x and y 0, 0, // width and height of the area of the source to copy $logoWidth, $logoHeight); // Set type of image and send the output //header("Content-type: image/png"); //imagePng($image); imagejpeg($logoImage, "imageWithLogo.jpg", 100); // Release memory imageDestroy($image); imageDestroy($imageLogo); ?> this part: //header("Content-type: image/png"); //imagePng($image); shows me the complete image with the logo ontop, what i'm having trouble with is saving the image. any help would be appreciated thanks guys Graham Hello. I'm using an Amazon S3 class to uploaded to S3. I have 2 upload boxes - The first uploads once and the second needs to upload twice - 1 full size, 1 thumb. The issue i'm having is that the 2nd image (the thumb) seems to be failing, although if I don't save the first full sized image I am able to upload the thumb. So I think the issue is with using the temp file twice? This is my code: //retreive post variables $fileName = $randomString . "_" . $_FILES['theFile']['name']; $fileTempName = $_FILES['theFile']['tmp_name']; $fileName2 = $randomString . "_" . $_FILES['theFile2']['name']; $fileTempName2 = $_FILES['theFile2']['tmp_name']; //move the file if ($s3->putObjectFile($fileTempName, "containerhere", $fileName, S3::ACL_PUBLIC_READ)) { echo "<strong>Uploaded Image</strong>"; }else{ echo "<strong>Something went wrong while uploading your file... sorry.</strong>"; } //move the file if ($s3->putObjectFile($fileTempName2, "containerhere", $fileName2, S3::ACL_PUBLIC_READ)) { echo "<strong>Uploaded Image</strong>"; }else{ echo "<strong>Something went wrong while uploading your file... sorry.</strong>"; } include('simpleImage.php'); $image = new SimpleImage(); $image->load($_FILES['theFile2']['tmp_name']); $image->resizeToWidth(100); $image->save($_FILES['theFile2']['tmp_name']); $fileName3 = $randomString . "_" . $_FILES['theFile2']['name']; $fileTempName3 = $_FILES['theFile2']['tmp_name']; //move the file if ($s3->putObjectFile($fileTempName3, "containerhere", "thumbs/" . $fileName3, S3::ACL_PUBLIC_READ)) { echo "<strong>Uploaded Image</strong>"; }else{ echo "<strong>Something went wrong while uploading your file... sorry.</strong>"; } Can anyone offer any advice? Thanks. Hey. I'm just wondering what would be the most logical or most efficient way to save an image resource that has been constructed on say the www. to a subdirectory or on another webserver? For eg The script on www.example.com constructs an image using the GD library from image1.png and image2.png. It has now got the final image resource for what's been constructed. I now want to save this image onto images.example.com How would you suggest? Hi All, This is my first post on here. I'd really appreciate any help with this, it's driving me mad. I'm trying to create a form to save a image into a mySQL database. I have a website hosted by UK2.net which has a mysql db with a table called gallery(name (varchar 30), size (int), type varchar(30), thePic(mediumBlob)). I have a form with this: Code: [Select] <td><p><label>Pic: </label></td><td><input name="userfile" type="file" id="userfile" /></td></p> Which when submitted actions addImage.php. The code for this looks like this: Code: [Select] <?php $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } $con = mysql_connect("localhost", "userName", "password") or die(mysql_error()); mysql_select_db("dbName", $con) or die(mysql_error()); $query = "INSERT INTO gallery (name, size, type, thePic) ". "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; if (!mysql_query($query,$con)) { die('Error: ' . mysql_error()); } echo "<br>File $fileName uploaded<br>"; ?> I get the following error message: Quote Warning: fopen() [function.fopen]: Filename cannot be empty in /home/hiddenje/public_html/addImage.php on line 13 Does anyone know what this is about? I've been on out friend google and a lot of people seem to be pointing to permissions but I can't seem to apply it to my scenario and just can't get it to work. Im a developer by trade, but this is my first step into the...interesting world of PHP and mySQL. Again, I'd appreciate any help with this. I'd love someone to talk me through exactly what I'm missing or doing wrong. Thanks in advance. Hi, I've read a lot of places that it's not recommended to store binary files in my db. So instead I'm supposed to upload the image to a directory, and store the link to that directory in database. First, how would I make a form that uploads the picture to the directory (And what kinda directories are we talking?). Secondly, how would I retrieve that link? And I guess I should rename the picture.. I'd appreciate any help, or a good tutorial (Haven't found any myself). I am working on a simple gallery. I want to have an option to download full scale image without users having to right click and "save as". Using this code you get a image preview: <a href="pictures/img-(1).jpg"><img src="thumbnails/img-(1).jpg"></a> How can I modify it so when user clicks on thumbnail of image 1 it will prompt him to save the image instead of viewing it. Thanks Can I get some help or a point in the right direction.
I am trying to create a form that allows me to add, edit and delete records from a database.
I can add, edit and delete if I dont include the image upload code.
If I include the upload code I cant edit records without having to upload the the same image to make the record save to the database.
So I can tell I have got the code processing in the wrong way, thing is I cant seem to see or grasp the flow of this, to make the corrections I need it work.
Any help would be great!
Here is the form add.php code
<?php require_once ("dbconnection.php"); $id=""; $venue_name=""; $address=""; $city=""; $post_code=""; $country_code=""; $url=""; $email=""; $description=""; $img_url=""; $tags=""; if(isset($_GET['id'])){ $id = $_GET['id']; $sqlLoader="Select from venue where id=?"; $resLoader=$db->prepare($sqlLoader); $resLoader->execute(array($id)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Venue Page</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <?php $sqladd="Select * from venue where id=?"; $resadd=$db->prepare($sqladd); $resadd->execute(array($id)); while($rowadd = $resadd->fetch(PDO::FETCH_ASSOC)){ $v_id=$rowadd['id']; $venue_name=$rowadd['venue_name']; $address=$rowadd['address']; $city=$rowadd['city']; $post_code=$rowadd['post_code']; $country_code=$rowadd['country_code']; $url=$rowadd['url']; $email=$rowadd['email']; $description=$rowadd['description']; $img_url=$rowadd['img_url']; $tags=$rowadd['tags']; } ?> <h1 class="edit-venue-title">Add Venue:</h1> <form role="form" enctype="multipart/form-data" method="post" name="formVenue" action="save.php"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>"/> <p><strong>ID:</strong> <?php echo $id; ?></p> <strong>Venue Name: *</strong> <input class="form-control" type="text" name="venue_name" value="<?php echo $venue_name; ?>"/><br/> <br/> <strong>Address: *</strong> <input class="form-control" type="text" name="address" value="<?php echo $address; ?>"/><br/> <br/> <strong>City: *</strong> <input class="form-control" type="text" name="city" value="<?php echo $city; ?>"/><br/> <br/> <strong>Post Code: *</strong> <input class="form-control" type="text" name="post_code" value="<?php echo $post_code; ?>"/><br/> <br/> <strong>Country Code: *</strong> <input class="form-control" type="text" name="country_code" value="<?php echo $country_code; ?>"/><br/> <br/> <strong>URL: *</strong> <input class="form-control" type="text" name="url" value="<?php echo $url; ?>"/><br/> <br/> <strong>Email: *</strong> <input class="form-control" type="email" name="email" value="<?php echo $email; ?>"/><br/> <br/> <strong>Description: *</strong> <textarea class="form-control" type="text" name="description" rows ="7" value=""><?php echo $description; ?></textarea><br/> <br/> <strong>Image Upload: *</strong> <input class="form-control" type="file" name="image" value="<?php echo $img_url; ?>"/> <small>File sizes 300kb's and below 500px height and width.<br/><strong>Image is required or data will not save.</strong></small> <br/><br/> <strong>Tags: *</strong> <input class="form-control" type="text" name="tags" value="<?php echo $tags; ?>"/><small>comma seperated vales only, e.g. soul,hip-hop,reggae</small><br/> <br/> <p>* Required</p> <br/> <input class="btn btn-primary" type="submit" name="submit" value="Save"> </div> </form> </div> </body> </html>Here is the save.php code <?php error_reporting(E_ALL); ini_set("display_errors", 1); include ("dbconnection.php"); $venue_name=$_POST['venue_name']; $address=$_POST['address']; $city=$_POST['city']; $post_code=$_POST['post_code']; $country_code=$_POST['country_code']; $url=$_POST['url']; $email=$_POST['email']; $description=$_POST['description']; $tags=$_POST['tags']; $id=$_POST['id']; if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "images/hs-venues/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { //echo "succesful upload, we have an image!"; var_dump($_POST); if($id==null){ $sql="INSERT INTO venue(venue_name,address,city,post_code,country_code,url,email,description,img_url,tags)values(:venue_name,:address,:city,:post_code,:country_code,:url,:email,:description,:img_url,:tags)"; $qry=$db->prepare($sql); $qry->execute(array(':venue_name'=>$venue_name,':address'=>$address,':city'=>$city,':post_code'=>$post_code,':country_code'=>$country_code,':url'=>$url,':email'=>$email,':description'=>$description,':img_url'=>$full_path,':tags'=>$tags)); }else{ $sql="UPDATE venue SET venue_name=?, address=?, city=?, post_code=?, country_code=?, url=?, email=?, description=?, img_url=?, tags=? where id=?"; $qry=$db->prepare($sql); $qry->execute(array($venue_name, $address, $city, $post_code, $country_code, $url, $email, $description, $full_path, $tags, $id)); } if($success){ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //if uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Upload Recieved but Processed Failed!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //move uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Updated.')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } ?>Thanks in advance! Edited by hankmoody, 12 August 2014 - 05:15 PM. hi, Is it possible to display an image that is above the root directory using php? for example if i have an image in /home/user/uploads/test.jpg and lets say my root directory for my site is /home/user/public_html/ is it possible to display test.jpg on /home/user/public_html/index.html ? i am trying to create a secure file upload script and i think not having the file be directly accessed by the public is one of the main steps. Hello, I'm a complete PHP newb. I'm curious whether PHP is even the best solution for my problem. I'm trying to automatically generate an xml file with the following structu Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <portfolio> <categories> <category id="film">Films</category> <category id="photo">Photography</category> <category id="graphic">Graphic Design</category> <category id="web">Web Design</category> </categories> <items> <item> <thumbnail>img/photo/003_small.jpg</thumbnail> <preview>img/photo/003.jpg</preview> <category>photo,film</category> <description>Description goes here.</description> </item> <item> <thumbnail>img/photo/003_small.jpg</thumbnail> <preview>img/photo/003.jpg</preview> <category>film</category> <description>Description goes here.</description> </item> <item> <thumbnail>img/photo/003_small.jpg</thumbnail> <preview>img/photo/003.jpg</preview> <category>graphic,photo</category> <description>Description goes here.</description> </item> </items> </portfolio> (You can ignore the description as I can put that in manually after the fact) There are lots of images and I just know that theres a way to fascilitate a script for this repetitive task to read a directory of a folder named "img" - see that there are a few folders named "photo" "film" and "graphic" etc, pull the images out of them in their corresponding categories etc. I just need the initial generated script with thumbnails and all the attributes, I can do the final tweeks afterward. This is for http://www.zoomrix.com/#portfolio This is the code that I'm working from right now (gathered from a few sources) Code: [Select] <?php $path_to_image_dir = 'images2'; // relative path to your image directory $xml_string = <<<XML <?xml version="1.0" encoding="UTF-8"?> <items> </items> XML; $xml_generator = new SimpleXMLElement($xml_string); if ( $handle = opendir( $path_to_image_dir ) ) { while (false !== ($file = readdir($handle))) { if ( is_file($path_to_image_dir.'/'.$file) ) { $item = $xml_generator->addChild('item'); $item->addChild('thumbnail', $path_to_image_dir.'/thumbs/'.$file); $item->addChild('preview', $path_to_image_dir.'/'.$file); $item->addChild('category', 'photo'); $item->addChild('description', ' '); } } closedir($handle); } header("Content-Type: text/xml"); echo $xml_generator->asXML(); ?>(The above code could be ran he http://www.zoomrix.com/index5.php ) I just can't figure out how to include the <portfolio> and <category> tags, or how to reference a file structure to input for the category child (depending on what folder an image is in). All the help would be greatly appreciated, even if you point me to the right tutorial. Thanks, GeorgeKotelnikov www.zoomrix.com How can i save image just assume that i have "test.jpg" and wish to store the image to directory "directory A" using Curl..how can i do that? thanks in adv I'm trying to save images from a directory into mine. To get the image I am having to take the email from a database, split it and take whatever it is before the '@' sign and add it to "-S.jpg". I wrote the script and when I echo the variable it shows the correct thing, but when it tries to save it , it is trying to find the image as "script>-S.jpg". It looks like it is taking whatever is after the last '/' which in the variable since I am running javascript it is going to be </script> if you look at my variable $url. Here is the code below. Any help is appreciated. while($rows=mysql_fetch_array($result)){ $email=$rows['email']; $url= "<SCRIPT LANGUAGE=\"javascript\"> var url; var email = \"$email\"; function emailsplit () { var userid = email.split(\"@\"); var url = userid[0]; var imgid = \"http://my.snu.edu/images/idpictures/\" + url + \"-S.jpg\"; return url; } document.write(emailsplit()); </script> "; $img[]= 'http://my.snu.edu/images/idpictures/'.$url.'-S.jpg'; } 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); } foreach($img as $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>'; } } Code: [Select] <?php $path = "../assets/tattoos/"; $path2 = "../assets/tattoos-thumbs/"; if(isset($_POST['file']) && is_array($_POST['file'])) { foreach($_POST['file'] as $file) { unlink($path. "/" . $file) or die("Failed to delete file"); unlink($path2. "/" . $file) or die("<meta http-equiv=\"refresh\" content=\"0; url=index.php\" />"); } } ?> <form name="form1" method="post"> <?php $imageDir = "../assets/tattoos/"; $dir_handle = @opendir($path) or die("Unable to open folder"); while (false !== ($file = readdir($dir_handle))) { if($file == "index.php") continue; if($file == ".") continue; if($file == "..") continue; echo "<input type='CHECKBOX' name='file[]' value='$file'>"; echo "<img src='../assets/tattoos/$file' style='height:auto;width:8%;' alt='$file'>"; } closedir($dir_handle); ?> <input type="submit" name="Delete" value="Delete"> </form> I have this code, which calls an image directory and adds a checkbox next to it, you check the boxes you wish, hit delete and the pictures are removed from the server. I need them to display in a grid view, like 4 columns by X amount of rows. Any help would be greatly appreciated. hi to all.Im currently displaying the images from my upload directory but the image does not display.please help thanks Hi I'm trying to setup Pagination at the bottom of the page after showing 10 images in the following script but have no clue where to start and how to implement it into the script. I have this code where I add records: Code: [Select] <?php ini_set('display_errors',1); error_reporting(-1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Check for a name: if (empty($_POST['product'])) { $add_cat_errors['product'] = 'Please enter the name!'; } // Check for a description: if (empty($_POST['prod_descr'])) { $add_cat_errors['prod_descr'] = 'Please enter the description!'; } // Check for a category: if (!isset($_POST['cat']) || !filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['cat'] = 'Please select a category!'; } // Check for a price: if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) { $add_cat_errors['price'] = 'Please enter a valid price!'; } // Check for a category: if (!isset($_POST['directory']) || !filter_var($_POST['directory'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['directory'] = 'Please select a directory!'; } // Check for an image: if (is_uploaded_file ($_FILES['image']['tmp_name']) && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) { $file = $_FILES['image']; $size = ROUND($file['size']/1024); // Validate the file size: if ($size > 512) { $add_cat_errors['image'] = 'The uploaded file was too large.'; } // Validate the file type: $allowed_mime = array ('image/jpeg', 'image/JPG', 'image/jpg'); $allowed_extensions = array ('.jpg', 'jpeg'); $image_info = getimagesize($file['tmp_name']); $ext = substr($file['name'], -4); if ( (!in_array($file['type'], $allowed_mime)) || (!in_array($image_info['mime'], $allowed_mime) ) || (!in_array($ext, $allowed_extensions) ) ) { $add_cat_errors['image'] = 'The uploaded file was not of the proper type.'; } // Move the file over, if no problems: if (!array_key_exists('image', $add_cat_errors)) { // Create a new name for the file: $new_name = (string) sha1($file['name'] . uniqid('',true)); // Add the extension: $new_name .= ((substr($ext, 0, 1) != '.') ? ".{$ext}" : $ext); //$new_name = $dir . '/' . $new_name; $dest = "../db/images/$new_name"; // Move the file to its proper folder but add _tmp, just in case: //$dest = "../db/images/$new_name"; $dirs = array('full_heads', 'human_hair', 'lip_tattoos', 'ponytails', 'synthetic_hair'); if (move_uploaded_file($file['tmp_name'], $dest)) { // Store the data in the session for later use: $_SESSION['image']['new_name'] = $new_name; $_SESSION['image']['file_name'] = $file['name']; // Print a message: echo '<h4>The file has been uploaded!</h4>'; } else { trigger_error('The file could not be moved.'); unlink ($file['tmp_name']); } } // End of array_key_exists() IF. } elseif (!isset($_SESSION['image'])) { // No current or previous uploaded file. switch ($_FILES['image']['error']) { case 1: case 2: $add_cat_errors['image'] = 'The uploaded file was too large.'; break; case 3: $add_cat_errors['image'] = 'The file was only partially uploaded.'; break; case 6: case 7: case 8: $add_cat_errors['image'] = 'The file could not be uploaded due to a system error.'; break; case 4: default: $add_cat_errors['image'] = 'No file was uploaded.'; break; } // End of SWITCH. } // End of $_FILES IF-ELSEIF-ELSE. // Check for a stock: if (empty($_POST['stock']) || !filter_var($_POST['stock'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['stock'] = 'Please enter the quantity in stock!'; } if (empty($add_cat_errors)) { $query = "INSERT INTO product (product, prod_descr, catID, price, dirID, image, stock) VALUES (?, ?, ?, ?, ?, ?, ?)"; // Prepare the statement: $stmt = mysqli_prepare($dbc, $query); // For debugging purposes: // if (!$stmt) echo mysqli_stmt_error($stmt); // Bind the variables: mysqli_stmt_bind_param($stmt, 'ssssssi', $name, $desc, $_POST['cat'], $_POST['price'], $_POST['directory'], $_SESSION['image']['new_name'], $_POST['stock']); // Make the extra variable associations: $name = strip_tags($_POST['product']); $desc = strip_tags($_POST['prod_descr']); // Execute the query: mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) == 1) { // If it ran OK. // Print a message: echo '<h4>The product has been added!</h4>'; // Clear $_POST: $_POST = array(); // Clear $_FILES: $_FILES = array(); // Clear $file and $_SESSION['image']: unset($file, $_SESSION['image']); } else { // If it did not run OK. trigger_error('The product could not be added due to a system error. We apologize for any inconvenience.'); unlink ($dest); } } // End of $errors IF. } else { // Clear out the session on a GET request: unset($_SESSION['image']); } // End of the submission IF. require_once ('./includes/form_functions.inc.php'); ?> <form enctype="multipart/form-data" action="add_product.php" method="post" accept-charset="utf-8"> <input type="hidden" name="MAX_FILE_SIZE" value="524288" /> Product<br /><?php create_form_input('product', 'text', $add_cat_errors); ?> Description<br /><?php create_form_input('prod_descr', 'textarea', $add_cat_errors); ?> Category<br /><select name="cat"<?php if (array_key_exists('cat', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT catID, cat FROM category ORDER BY cat ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['cat']) && ($_POST['cat'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('cat', $add_cat_errors)) echo $add_cat_errors['cat']; ?> Price<br /><?php create_form_input('price', 'text', $add_cat_errors); ?> Directory<br /><select name="directory"<?php if (array_key_exists('directory', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT dirID, directory FROM directory ORDER BY directory ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['directory']) && ($_POST['directory'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('directory', $add_cat_errors)) echo $add_cat_errors['directory']; ?> </select> Image<br /><?php // Check for an error: if (array_key_exists('image', $add_cat_errors)) { echo $add_cat_errors['image'] . '<br /><input type="file" name="image"/>'; } else { // No error. echo '<input type="file" name="image" />'; // If the file exists (from a previous form submission but there were other errors), // store the file info in a session and note its existence: if (isset($_SESSION['image'])) { echo "<br />Currently '{$_SESSION['image']['file_name']}'"; } } // end of errors IF-ELSE. ?> <br /> Stock<br /><?php create_form_input('stock', 'text', $add_cat_errors); ?> <input type="submit" value="Add This Product" class="button" /> </fieldset> </form> What I want to achieve is this; When a record is being inserted, a user will make a selection from the dropdown box with a list of directories. Then, a user will upload an image. When a image is uploaded and a directory is chosen, I want the image to be assigned to a specific directory from the list so when the record is inserted, that image will be placed in the specific directory. How do I achieve this please? Hi guys, I've been working on a script for a while now, and I'm sure it doesn't look great and all, and it's probably really messed up.. But right now I've finally got it working! There's only 1 thing I'd really like to add.. Searching through & listing of remote directories! The directories I'm trying to list have directory listings enabled, and I think it *should* be possible. I just have no clue how. Here's my current code in a beautiful mix of HTML and PHP: <? $border_size = "0"; function returner($what) { $what=explode("/",$what); $tps=count($what); $what=$what[$tps-1]; return $what; } $page_url= ""; $home_url=returner(__FILE__); if(isset($_GET['q'])) { $qtext=$_GET['q']; } else { $qtext=""; } function getdirsize($directory, $format=FALSE) { $size = 0; if(substr($directory,-1) == '/') { $directory = substr($directory,0,-1); } if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { return -1; } if($handle = opendir($directory)) { while(($file = readdir($handle)) !== false) { $path = $directory.'/'.$file; if($file != '.' && $file != '..') { if(is_file($path)) { $size += filesize($path); } elseif(is_dir($path)) { $handlesize = getdirsize($path); if($handlesize >= 0) { $size += $handlesize; } else { return -1; } } } } closedir($handle); } if($format == TRUE) { if($size / 1048576 > 1) { return round($size / 1048576, 1).' MB'; } elseif($size / 1024 > 1) { return round($size / 1024, 1).' KB'; } else { return round($size, 1).' bytes'; } } else { return $size; } } if(isset($_GET['type'])){ $type=$_GET['type']; } else { $type="new"; } $textures=0; $models=0; $avatars=0; $seqs=0; $sounds=0; foreach (glob("textures/*.jpg") as $texture){ $textures++; } foreach (glob("models/*.zip") as $model){ $models++; } foreach (glob("avatars/*.zip") as $avatar){ $avatars++; } foreach (glob("seqs/*.zip") as $seq){ $seqs++; } foreach (glob("sounds/*.zip") as $sound){ $sounds++; } ?> <!DOCTYPE html> <html> <head> <title>ObjectPath Search</title> <style type="text/css"> #wrapper { width: 850px; margin: 30px auto 30px auto; padding: 10px; } body { color:#C6C6C6; background:#1E1E1E; /* margin:0; padding:0; */ overflow-x:hidden; } #tabs { font: 85% "Trebuchet MS", sans-serif; } .left { float: left; } .right { float: right; } a:link, a:visited, a:active { color: #3DB015; text-decoration: none; } a:hover { color: #00E0FF; } h2 { color: #3DB015; padding-bottom: 0.2em; font-size: 110%; } ul#icon {margin: 0; padding: 0;} ul#icon li {margin: 1px; position: relative; padding: 1px 0; cursor: pointer; float: left; list-style: none;} ul#icon span.ui-icon {float: left; margin: 0 1px;} </style> <link type="text/css" href="http://objects.jk-hosting.com/search/css/black-tie/jquery-ui-1.8.2.custom.css" rel="stylesheet" /> <script type="text/javascript" src="http://objects.jk-hosting.com/search/js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://objects.jk-hosting.com/search/js/jquery-ui-1.8.2.custom.min.js"></script> <script type="text/javascript"> function formHandler(form){ var URL = document.form.site.options[document.form.site.selectedIndex].value; window.location.href = URL; }; $(function(){ // Tabs $('#tabs').tabs(); }); </script> </head> <body> <div id="wrapper"> <div id="tabs"> <!-- Tabs start --> <ul> <li><a href="#tab-search">Search</a></li> <li><a href="#tab-list">List Objects</a></li> <li><a href="#tab-info">OP info</a></li> </ul> <div id="tab-search"><!-- Searchtab start --> Please enter a string to search for, and choose a folder to search in. <br /><br /> <form name="Search"> <input type='hidden' value='search' name='type'> <input value='<? print $qtext; ?>' type='text' name='q'> <select name='map'> <option selected='selected' value='models'>Models</option> <option value='avatars'>Avatars</option> <option value='textures'>Textures</option> <option value='seqs'>Seqs</option> <option value='sounds'>Sounds</option></select> <input type='submit' value='Search'> </form> </div> <!-- Searchtab end --> <div id="tab-list"><!-- Listtab start --> Please pick a folder to browse. <br /><br /> <form name="form"> <select name="site" onChange="javascript:formHandler()"> <option value="#">Look in folder...</option> <option value="<? print $page_url; ?>?type=list&map=models">Models</option> <option value="<? print $page_url; ?>?type=list&map=avatars">Avatars</option> <option value="<? print $page_url; ?>?type=list&map=textures">Textures</option> <option value="<? print $page_url; ?>?type=list&map=seqs">Seqs</option> <option value="<? print $page_url; ?>?type=list&map=sounds">Sounds</option> </select> </form> </div> <!-- Listtab end --> <div id="tab-info"><!-- Info tab start --> The OP currently contains: <br /><br /> <table> <tr><td><b><? echo $models; ?></b></td> <td>Models</td></tr> <tr><td><b><? echo $avatars; ?></b></td> <td>Avatars</td></tr> <tr><td><b><? echo $textures; ?></b></td> <td>Textures</td></tr> <tr><td><b><? echo $seqs; ?></b></td> <td>Seqs</td></tr> <tr><td><b><? echo $sounds; ?></b></td> <td>Sounds</td></tr> </table> </div> <!-- Info tab end --> </div> <!-- Tabs end --> </div> <!-- Start PHP generated content --> <? if($type=="search" || $type=="list") { $M=$_GET['map']; if($type=="search") { $Q=$_GET['q']; $empty="Nothing found with <b>\"" . $Q . "\"</b> in it's name.<br />\nPlease make a more general search query, or try a different folder.\n\n"; } else { $Q=""; $empty='This folder is empty'; } if($M=="textures") { $ext="jpg"; } else { $ext="zip"; } $i=0; print "<hr>\n"; $endfile=array(); $endsize=array(); $endsize2=array(); foreach (glob($M."/*".$Q."*.".$ext) as $filename) { $filename = explode(".", $filename); $filename=$filename[0]; $filename = explode("/", $filename); $filename=$filename[1]; $i++; $endfile[$i]=$filename; if($ext=="jpg") { $endfile[$i]="<a name='".$endfile[$i]."' href='".$pageurl."?type=view&name=".$endfile[$i]."&folder=".$M."&from=".$type."&addon=".$Q."'>".$endfile[$i]."</a>"; } $endsize[$i]=$size; $endsize2[$i]=$size2; } if($i != 1) { print "<b>".$i."</b> items were found.\n<hr>\n"; } else { print "<b>".$i."</b> item was found.\n<hr>\n"; } echo("<table width='100%' border='" . $border_size . "' cellspacing='0' cellpadding='0' >\n"); if($i!=0) { for ($t = 1; $t < $i; $t++) { $thumbfile = $M."/".$endfile[$t].'.jpg'; if(file_exists($thumbfile)) { $thumbnail = "<a name='".$endfile[$t]."' href='".$page_url."?type=view&name=".$endfile[$t]."&folder=".$M."&from=".$type."&addon=".$Q."'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></a>"; } else { $thumbnail = ""; } if($t=="1") { echo("<tr><td width='10%'>Number</td><td width='3%'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></td><td width='60%'>Name</td></tr>\n"); } echo("<tr><td>" . $t . "</td><td>".$thumbnail."</td><td>" . $endfile[$t] . "</td></tr>\n"); flush(); } $thumbfile = $M."/".$endfile[$t].'.jpg'; if(file_exists($thumbfile)) { $thumbnail = "<a name='".$endfile[$t]."' href='".$page_url."?type=view&name=".$endfile[$t]."&folder=".$M."&from=".$type."&addon=".$Q."'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></a>"; } else { $thumbnail = ""; } echo("<tr><td>" . $t . "</td><td>".$thumbnail."</td><td>" . $endfile[$t] . "</td></tr>\n"); } print "</table>\n"; if($i=="0") { print $empty; } } elseif($type=="view") { $filename=$_GET['name']; $folder=$_GET['folder']; if($_GET['from']=="list"){ $addon="?type=list&map=".$folder."#".$filename; } if($_GET['from']=="search"){ $addon="?type=search&q=".$filename."&map=".$folder."#".$filename; } print"<center><a href='".$home_url."'>Home</a></center>"; print "<hr>\n<center><img src='".$folder."/".$filename.".jpg'></img></center>\n<hr>\n<br />\n<a href='".$page_url."".$addon."'>Previous Page</a>\n"; } $htmlshow=""; if($_GET['type']=="returnOPfile") { if(isset($_GET['split'])) { $splitter=$_GET['split']; } else { $splitter=" | "; } if(isset($_GET['html'])) { $htmlshow="<br />"; } foreach (glob("textures/*.jpg") as $texture){ if(isset($_GET['size'])) { $size=$splitter.filesize($texture); } $texture = explode("/", $texture); $texture=$texture[1]; print "textures".$splitter.$texture.$size."\n".$htmlshow; } foreach (glob("models/*.zip") as $model){ if(isset($_GET['size'])) { $size=$splitter.filesize($model); } $model = explode("/", $model); $model=$model[1]; print "models".$splitter.$model.$size."\n".$htmlshow; } foreach (glob("avatars/*.zip") as $avatar){ if(isset($_GET['size'])) { $size=$splitter.filesize($avatar); } $avatar = explode("/", $avatar); $avatar=$avatar[1]; print "avatars".$splitter.$avatar.$size."\n".$htmlshow; } foreach (glob("seqs/*.zip") as $seq){ if(isset($_GET['size'])) { $size=$splitter.filesize($seq); } $seq = explode("/", $seq); $seq=$seq[1]; print "seqs".$splitter.$seq.$size."\n".$htmlshow; } foreach (glob("sounds/*.zip") as $sound){ if(isset($_GET['size'])) { $size=$splitter.filesize($sound); } $sound = explode("/", $sound); $sound=$sound[1]; print "sounds".$splitter.$sound.$size."\n".$htmlshow; } } ?> <!-- End PHP generated content --> </body> </html> So right now my question to you PHP freaks is, can you please help me edit my script so I can search through a remote directory? *This* is one of the directories I wish to be able to search through & list.. Thanks in advance. Edit; It might help if you know what the site currently looks like. *Click*
I have a form on which the filepond plugin send the file manually
Look here if(empty($_POST['image'])) { echo 'add file!'; } $myimage = $_POST['image']; $myimage = str_replace('data:image/png;base64,', '', $myimage); $myimage = str_replace(' ', '+', $myimage); $decode = base64_decode($myimage); $myfile = $_SERVER['DOCUMENT_ROOT'].'/mages/' . uniqid() . '.png'; //now put the file file_put_contents($myfile, $decode);
I have a very simple piece of code to create a grid based gallery. The thumbnails are loaded from a single directory and are name 1.jpg... 2.jpg... 3.jpg etc At the moment the images appear to be loaded in randomly. I want them to load in numerically in terms of their filename. I know I may need to use 'sort' or 'natsort' but where in the code? Thanks for any help you can give me Code: [Select] <? $images = "Images/Bag Thumbs/"; # Location of small versions $big = "ruxxwomens.php?id="; # Location of big versions (assumed to be a subdir of above) $cols = 4; # Number of columns to display if ($handle = opendir($images)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && $file != rtrim($big,"/")) { $files[] = $file; } } closedir($handle); } $colCtr = 0; echo '<table width="800" cellspacing="0" cellpadding="0" border="0"><tr>'; foreach($files as $file) { if($colCtr %$cols == 0) echo '</tr><tr>'; echo '<td align="center"><a href="' . $big . $file . '"><img src="' . $images . $file . '" cellspacing="0" cellpadding="0" border="0"></a></td>'; $colCtr++; } echo '</table>' . "\r\n"; ?> |