PHP - Update Stored Image Filename
Hi
I am winning I think
I have got the records displayed for the current user logged in so basically they can only see their submitted listings and just working on the edit of them so the current user logged in can update their listing and is all working apart from the update of the images
the images are stored by the file name on the database and then gets moved onto the server so the actual images are not stored on the database only the file names are and the images are moved onto the server, hope that makes sense
what I can't do at the mo is work out how to update the file names of the images on the database and update on the server
I get the following error
Notice: Undefined index: photo on line 209 and line 211
the coding for them lines are below
$pic1= basename($_FILES['photo']['name'][0]); $pic2= basename($_FILES['photo']['name'][1]);The rest of the coding below that is if(!empty($_FILES['photo']['tmp_name'])) { // Number of uploaded files $num_files = count($_FILES['photo']['tmp_name']); /** loop through the array of files ***/ for($i=0; $i < $num_files;$i++) { // check if there is a file in the array if(!is_uploaded_file($_FILES['photo']['tmp_name'][$i])) { $messages[] = 'No file uploaded'; } else { // move the file to the specified dir if(move_uploaded_file($_FILES['photo']['tmp_name'][$i],$target.'/'.$_FILES['photo']['name'][$i])) { $messages[] = $_FILES['photo']['name'][$i].' uploaded'; } else { // an error message $messages[] = 'Uploading '.$_FILES['photo']['name'][$i].' Failed'; } } }The update query is below // save the data to the database mysql_query("UPDATE privatelistings SET listingtitle='$listingtitle', make='$model', model='$model', exteriorcolour='$exteriorcolour', enginesize='$enginesize', fueltype='$fueltype', yearregistered='$yearregistered', transmission='$transmission', mileage='$mileage', nodoors='$nodoors', bodystyle='$bodystyle', price='$price', photo='$pic1', photo1='$pic2' WHERE id='$id'") or die(mysql_error());I am going to be updating to mysqli just want to get it working first My HTML form coding is below <form action="" method="post" enctype="multipart/form-data"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div> <strong>Listing Title: *</strong> <input type="text" name="listingtitle" value="<?php echo $listingtitle; ?>"/> <br/> <strong>Make: *</strong> <input type="text" name="make" value="<?php echo $make; ?>"/> <br/> <strong>Model: *</strong> <input type="text" name="model" value="<?php echo $model; ?>"/> <br/> <strong>Exterior Colour: *</strong> <input type="text" name="exteriorcolour" value="<?php echo $exteriorcolour; ?>"/> <br/> <strong>Engine Size: *</strong> <input type="text" name="enginesize" value="<?php echo $enginesize; ?>"/> <br/> <strong>Fuel Type: *</strong> <input type="text" name="fueltype" value="<?php echo $fueltype; ?>"/> <br/> <strong>Year Registered: *</strong> <input type="text" name="yearregistered" value="<?php echo $yearregistered; ?>"/> <br/> <strong>Transmission: *</strong> <input type="text" name="transmission" value="<?php echo $transmission; ?>"/> <br/> <strong>Mileage: *</strong> <input type="text" name="mileage" value="<?php echo $mileage; ?>"/> <br/> <strong>Number of Doors: *</strong> <input type="text" name="nodoors" value="<?php echo $nodoors; ?>"/> <br/> <strong>Body Style: *</strong> <input type="text" name="bodystyle" value="<?php echo $bodystyle; ?>"/> <br/> <strong>Price: *</strong> <input type="text" name="price" value="<?php echo $price; ?>"/> <br/> <strong>Photo One:</strong> <input type='hidden' name='size' value='350000'><input type='file' name='photo[]'> <br> <strong>Photo Two:</strong> <input type='hidden' name='size' value='350000'><input type='file' name='photo[]'> <br> <input type="submit" name="submit" value="Submit"> </div> </form>sorry was not sure what other I need to show, so you guys get the idea? Similar TutorialsHello, Five images will be displayed inside a division. There will be a previous and next button/link. If someone click the next button the next image will be added in that div and the first image will be gone from that div. The previous button/link will do the same thing. Is it possible with php? I am confused if it's a javascript or ajax question. Thanks. Hi everyone. I have a small problem. I have a database that shows student images, in the format of 1234.jpg but the file name extension is in both upper case and lower case. My server OS is linux ubuntu. apache2 php5. Linux see these as 2 different file so will not show the upper case ones. 1234.JPG What i have already is working but for lower case only, i need something to detect when the extension is in uppercase and change accordingly. This is what i have now that works for lower case only. <img src=../images/mbr_images/<?php echo H($mbr->getBarcodeNmbr());?>.jpg height=150 width=100 border=1px </img This is what i have tried but gives me a filename of "1234jpg" see the "." is missing? and is still lower case. <img src=../images/mbr_images/<?php echo H($mbr->getBarcodeNmbr()); $image = jpg; $image2 = JPG; if ($image = $image) { echo $image; } else { echo $image2; };?> height=150 width=100 border=1px </img> can anyone offer any help please? TIA Peter I'm trying to create a form that has a drag and drop image with it. I did a tutorial for the drag and drop and now I'm trying to put it together with a form. The problem I'm having is that I'm not able to get the filename, so that I can insert it into the database. I've tried doing this if(isset($_POST['add_product'])) { $filename = $_FILES['files']['name']; echo print_r($filename); die(); }
Array ( [0] => ) 1
if(isset($_FILES['files'])) { $filename = $_FILES['files']['name']; echo print_r($filename); die(); }
if(isset($_FILES['files'])) { $filename = $_FILES['files']['name']; } if(isset($_POST['add_product'])) { echo print_r($filename); die(); }
Array ( [0] => ) 1
if(isset($_POST['add_product])) Here is my form <form action="" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" name="title"> </div> <div class="form-group"> <label for="content">content</label> <textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea> </div> <input type="file" name="files[]" id="standard-upload-files" multiple> <input type="submit" value="Upload files" id="standard-upload"> <div class="wrapper"> <div class="upload-console"> <h2 class="upload-console-header"> Upload </h2> <div class="upload-console-body"> <div class="upload-console-drop" id="drop-zone"> just drag and drop files here </div> <div class="bar"> <div class="bar-fill" id="bar-fill"> <div class="bar-fill-text" id="bar-fill-text"></div> </div> </div> <div class="hidden" id="uploads-finished"> <h3>Process files</h3> <div class="upload-console-upload"> <a href="#">filename.jpg</a> <span>Success</span> </div> </div> </div> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product">Save</button> </div> </form>
main.js (function(){ "use strict"; var dropZone = document.getElementById('drop-zone'); var barFill = document.getElementById('bar-fill'); var barFillText = document.getElementById('bar-fill-text'); var uploadsFinished = document.getElementById('uploads-finished'); var startUpload = function(files){ // console.log(files); app.uploader({ files: files, progressBar: barFill, progressText: barFillText, processor: 'index.php', finished: function(data){ // console.log(data); var x; var uploadedElement; var uploadedAnchor; var uploadedStatus; var currFile; for(x = 0; x < data.length; x = x + 1) { currFile = data[x]; uploadedElement = document.createElement('div'); uploadedElement.className = 'upload-console-upload'; uploadedAnchor = document.createElement('a'); uploadedAnchor.textContent = currFile.name; if(currFile.uploaded) { uploadedAnchor.href = 'uploads/'+currFile.file; } uploadedStatus = document.createElement('span'); uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed'; uploadedElement.appendChild(uploadedAnchor); uploadedElement.appendChild(uploadedStatus); uploadsFinished.appendChild(uploadedElement); } uploadsFinished.className = ''; }, error: function(){ console.log('there was an error'); } }); }; //drop functionality dropZone.ondrop = function(e){ e.preventDefault(); this.className = 'upload-console-drop'; startUpload(e.dataTransfer.files); }; dropZone.ondragover = function(){ this.className = 'upload-console-drop drop'; return false; }; dropZone.ondragleave = function(){ this.className = 'upload-console-drop'; return false; }; }());
var app = app || {}; (function(o){ "use strict"; //private methods var ajax, getFormData, setProgress; ajax = function(data){ var xmlhttp = new XMLHttpRequest(); var uploaded; xmlhttp.addEventListener('readystatechange', function(){ if(this.readyState === 4) { if(this.status === 200) { uploaded = JSON.parse(this.response); if(typeof o.options.finished === 'function') { o.options.finished(uploaded); } }else{ if(typeof o.options.error === 'function') { o.options.error(); } } } }); xmlhttp.upload.addEventListener('progress', function(e){ var percent; if(e.lengthComputable === true) { percent = Math.round((event.loaded / event.total) * 100); setProgress(percent); } }); xmlhttp.open('post', o.options.processor); xmlhttp.send(data); }; getFormData = function(source){ var data = new FormData(); var i; for(i = 0; i < source.length; i = i + 1) { data.append('files[]', source[i]); } return data; }; setProgress = function(value){ if(o.options.progressBar !== undefined) { o.options.progressBar.style.width = value ? value + '%' : 0; } if(o.options.progressText !== undefined) { o.options.progressText.textContent = value ? value + '%' : ''; } }; o.uploader = function(options){ o.options = options; if(options.files !== undefined) { ajax(getFormData(o.options.files)); // getFormData(o.options.files); } } }(app));
I am writting a php function that uses mysql to get user data - pretty common, right Well, my issue is that I need to run a check in my file system. Users profile pictures are stored in my image directory as .png's. I need to have my function check that directory and if an image matches their id, then return their information. I only want the user data if they have an image uploaded. Here is my current function: Code: [Select] function fetch_users_login($limit) { $limit = $limit(int); $sql = "SELECT `users`.`id`, `users`.`firstname`, `users`.`lastname`, `users`.`username`, `user_privacy`.`avatar` FROM `users` LEFT JOIN `user_privacy` ON `users`.`id` = `user_privacy`.`uid` WHERE `users`.`status` > 2 AND `user_privacy`.`avatar` = 1 ORDER BY `users`.`id` DESC LIMIT 0, {$limit}"; $result = mysql_query($sql) or die(mysql_error()); $users = array(); $i = 0; while(($row = mysql_fetch_assoc($result)) !== false) { $users[$i] = array( 'id' => $row['id'], 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], ); $users[$i]['avatar'] = getUserAvatar($row['username']); $i++; } return $users; } Hi Everyone, I have a program that generates 200 unique images keeping the first image static in each run.The images keep scrolling on to the screen pause for 3 seconds and scroll off I'm able to generated all 200 unique images without repetition, everything is working well except for the lase two images the last two images are scrolling on to the screen but are not been displayed in the database, Moreover The last image is a duplicate of 197th image.I don't know what is happening..... Here is MY code.......... <?php session_start(); $sid = $_SESSION['id']; $_SESSION['imageDispCnt'] = 0; $myQuery = "SELECT * from image"; $conn = mysql_connect("localhost","User","Passwd"); mysql_select_db("database_Name",$conn); $result = mysql_query($myQuery); $img =Array(); $id =Array(); $i =0; $imagepath = 'http://localhost/images/'; while ($row = mysql_fetch_array($result)) { $img[$i] = $imagepath.$row['img_name']; $id[$i] = $row['imageid']; $i = $i + 1; } ?> </head> <script language="JavaScript1.2"> var scrollerwidth='800px'; var scrollerheight='600px'; var scrollerbgcolor='white'; var pausebetweenimages=3200; var s; var sec; var d; var j; var imgid; var milisec = 0; var seconds = 0; var flag = 1; var ses_id = '<?php echo $sid;?>'; var count = 0; var i = 0; var imgname; var imgid; var k =0; var slideimages=new Array(); var img_id = new Array(); var index; <?php $l =0; $count = array(); $j = rand(0,199); while($l < 200) { while(in_array($j, $count)) { $j = rand(0,199); } $count[$l] = $j; $l++; }?> <?php $k = 0; for($k = 0;$k<count($count);$k++){ ?> index = <?php echo $k;?>; <?php $indx = $count[$k];?> if(index == 0){ slideimages[0] = '<img src="http://localhost/images/hbag044.jpg" name="r_img" id="0"/>'; img_id[0] = '<input type="hidden" value="0" id="imgId" />'; } else if(index > 0) { slideimages[<?php echo $k?>] = '<img src="<?php echo $img[$indx]?>" name="r_img" id="<?php echo $id[$indx]?>"/>'; img_id[<?php echo $k?>] = '<input type="hidden" value="<?php echo $id[$indx]?>" id="imgId" />'; } <?php } ?> Can Any one plese help me Appreciate your help... Thanks I put together the following blocs of code for uploading pictures into a database and displaying them on a webpage. The pictures are supposed to be displayed on the member's only page of a website I'm working on, upon logging in, and they are supposed to be the member's uploaded picture. I created several members and and used one of my existing member accounts to test the uploading process. The picture upload process appeared to have been successful when I checked on myphpadmin. Yet, when I login with this account, no picture is displayed, instead, a tiny jpg icon is displayed at the top left corner of the box in which the picture was supposed to be displayed. Same thing when I login with the other accounts with which I haven't yet uploaded a picture. I'll start with the code that installs the table in the database $query = "CREATE TABLE images ( image_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , member_id INT UNSIGNED, like_id INT UNSIGNED, image LONGBLOB NOT NULL, image_name varchar(255) NOT NULL, image_type varchar(4) NOT NULL, image_size int(8) NOT NULL, image_cartegory VARCHAR(20) NOT NULL, image_path VARCHAR(300), image_date DATE )"; Then here is the code which allows the member to upload his pictu <form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer"> <input name="MAX_FILE_SIZE" value="102400" type="hidden"> <input name="image" accept="image/jpeg" type="file"> <input value="Submit" type="submit"> </form> And here is the insertimage.php which inserts the image into our database: Note that I have to authenticate the user in order to register his session id which is used later on in the select query to identify him and select the right image that corresponds to him. <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Make sure the user actually // selected and uploaded a file if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { // Temporary file name stored on the server $tmpName = $_FILES['image']['tmp_name']; // Read the file $fp = fopen($tmpName, 'r'); $data = fread($fp, filesize($tmpName)); $data = addslashes($data); fclose($fp); // Create the query and insert // into our database. $query = "INSERT INTO images (member_id, image_cartegory, image_date, image) VALUES ('{$_SESSION['id']}', 'main', NOW(), '$data')"; $results = mysql_query($query); // Print results print "Thank you, your file has been uploaded."; } else { print "No image selected/uploaded"; } // Close our MySQL Link mysql_close(); } //End of if statmemnt. ?> On the page which is supposed to display the image upon login in, I inserted the following html code in the div that's supposed to contain the image: <div id="image_box" style="float:left; background-color: #c0c0c0; height:150px; width:140px; border- color:#a0a0a0;border-style:outset;border-width:1px; margin:auto; "> <img src=picscript.php?imname=potwoods> </div> And finally, the picscript.php contained the select query: <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //include the config file require('config.php'); $image = stripslashes($_REQUEST[imname]); $rs = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND cartegoty = 'main' "); $row = mysql_fetch_assoc($rs); $imagebytes = $row[image]; header("Content-type: image/jpeg"); print $imagebytes; ?> Now the million dollar question is, "What is preventing the picture from getting displayed?" I know this is a very lengthy and laborious problem to follow but I'm sure there is someone out there who can point out where I'm not getting it. Thanks. Okay, so here is the deal. Have a table which stores image as blob files. Now i want to read the image width and height directly from the blob field. Is this possible and if yes, how? Things i tried so far; list($size[0],$size[1],$type, $attr) = getimagesize('image.php?i=26ddd45b02859e836d13d4b9fde34281'); print_r($size); $img = 'image.php?i=26ddd45b02859e836d13d4b9fde34281'; echo imagesy($img); image.php grabs the image from DB and show's it with header("Content-type: image/jpg"); It works for just showing the images with the <img> tag. Any ideas of help would be great! Hi guys, I am wirting a script to upload an image file, but I get the error: copy() [function.copy]: Filename cannot be empty in Obviouly it has something to do with the copy() function - (copy($HTTP_POST_FILES['product_img']['tmp_name'], $path)) I think it is not copying from my temp folder or something. Can anyone help me out? Code is: Code: [Select] //IMAGE FILE $file_name = $_FILES['product_img']['name']; echo '<p>File Name:' . $file_name . '</p>'; //IMAGE UPLOAD // random 4 digit to add to file name $random_digit=rand(0000,9999); //combine random digit to file name to create new file name //use dot (.) to combile these two variables $new_image_name = $random_digit.$file_name; echo $new_image_name; //SET DESINATION FOLDER $path= "uploads/".$new_image_name; echo '<p>Path:' . $path . '</p>'; if($product_img !=none) { if(copy($HTTP_POST_FILES['product_img']['tmp_name'], $path)) { echo "Successful<BR/>"; echo "File Name :".$new_file_name."<BR/>"; echo "File Size :".$HTTP_POST_FILES['product_img']['size']."<BR/>"; echo "File Type :".$HTTP_POST_FILES['product_img']['type']."<BR/>"; } else { echo "Image upload Error<BR/>"; } } Any help would be greatly appreciated! Thanks wrote a stored procedure this morning and i don’t know how to get the values out of it through a class function in php or phpmyadmin. here is what i wrote : public function totalProcedures($friend_name,$session_id) { /* *query to fetch stored procedure */ try { //executing the stored procedure $sql_sp="CALL timeline (:friend, :session,@updates, @group_posts)"; $stmt_sp= $this->_db->prepare($sql_sp); $stmt_sp->bindValue(":friend",$friend_name); $stmt_sp->bindValue(":session",$session_id); $stmt_sp->execute(); $rows=$stmt_sp->fetch(PDO::FETCH_ASSOC); $stmt_sp->closeCursor(); // closing the stored procedure //trying to get values from OUT parameters. $stmt_sp_2=$this->_db->prepare("select @updates,@group_posts"); $stmt_sp_2->execute(); return $stmt_sp_2->fetch(PDO::FETCH_ASSOC); } catch (PDOException $ei) { echo $ei->getMessage(); } } can someone helpme how to get results. here is the storedprocedu DELIMITER $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeline`(IN `friend` VARCHAR(255), IN `session_id` VARCHAR(255), OUT `updates` VARCHAR(62555), OUT `group_posts` VARCHAR(62555)) BEGIN select * FROM updates where author in (friend,session_id) order by time desc limit 5; select * FROM group_posts where author_gp in (friend,session_id) order by pdate desc limit 5; END$$ DELIMITER ; i get the result in php myadmin as follows:
how do i do this inside a php class function. CALL timeline('shan2batman','aboutthecreator', @updates, @group_posts);
Hi all, I have a script that is supposed to upload an image and then update a field in the table with the image's path in it. The image uploads okay but the details do not UPDATE in the table... any ideas? I have echoed after the sql statement which doesn't appear upon submitting but it shows the query printed out doing the right thing (I think) Quote UPDATE `fleet` SET `fleetimage4` = '../fleet/last.JPG' WHERE `fleetref` = '9' LIMIT 1 Code: [Select] <?php $ref = (!empty($_GET['ref']))?trim($_GET['ref']):""; $image = (!empty($_GET['image']))?trim($_GET['image']):""; $idir = "../fleet/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], "$idir" . $_FILES['fupload']['name']); // Move Image From Temporary Location To Permanent Location } } if (isset($_POST['submit'])){ //$fleetref=$_POST["fleetref"]; $fleetimage1 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $fleetimage2 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $fleetimage3 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $fleetimage4 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); # setup SQL statement if ($image == "1") { $query = sprintf("UPDATE `fleet` SET `fleetimage1` = '$fleetimage1' WHERE `fleetref` = '$ref' LIMIT 1"); } else if ($image == "2"){ $query = sprintf("UPDATE `fleet` SET `fleetimage2` = '$fleetimage2' WHERE `fleetref` = '$ref' LIMIT 1"); } else if ($image == "3"){ $query = sprintf("UPDATE `fleet` SET `fleetimage3` = '$fleetimage3' WHERE `fleetref` = '$ref' LIMIT 1"); } else if ($image == "4"){ $query = sprintf("UPDATE `fleet` SET `fleetimage4` = '$fleetimage4' WHERE `fleetref` = '$ref' LIMIT 1"); } #execute SQL statement echo "before exe"; $result = mysql_db_query($db,$query,$cid) or die($query."<br>".mysql_error()); echo "after exe"; # check for error if (!$result){ echo("ERROR: " . mysql_error() . "\n$SQL\n"); }} ?> <div class="controls_left"> <FORM NAME="fa" ACTION="<?php echo "fleet_edit_image.php?ref=$ref&image=$image"; ?>" METHOD="POST" enctype="multipart/form-data"> <input type = "hidden" name="MAX_FILE_SIZE" value = "1000000"> Select image: <input type = "file" name = "fupload"> <p>Copyright note: Please only use photographs either that you have taken yourself or that you have permission to use as we will not be held responsible for any Copyright infringement.</p> <input name="submit" type="submit" value="Edit image" /> </FORM> </div> <div class="image_right"><?php if ($image == "1") { $imageprint = "$fleetimage1"; } else if ($image == "2") { $imageprint = "$fleetimage2"; } else if ($image == "3") { $imageprint = "$fleetimage3"; } else if ($image == "4") { $imageprint = "$fleetimage4"; } echo "<div class=\"image_right\"><img src=\"../$imageprint\" alt=\"Edit image\" width=\"293\" height=\"218\"></div>"; ?> Hi, I wrote the function below. It switches out one color for another. The pictures going in are css sprites with various colors and a white background. So.. sprite 1 might by blue and sprite 2 might be green. The function would be run twice to replace the blue + green with whatever colors were required. /** * Changes the color of a graphic. * $settings = array ( * 'icon' * 'new_icon' * 'old_color' = array * 'new_color' = array * ); */ function updateIconColor($settings=array()) { // Create Image $image = imagecreatefrompng($settings['icon']); // Convert True color image to a palatte imagetruecolortopalette($image, false, 255); // Restore Alpha $white = imagecolorclosest($image, 255, 255, 255); imagecolortransparent($image, $white); // Find + Set color $index = imagecolorclosest($image, $settings['old_color'][0],$settings['old_color'][1],$settings['old_color'][2]); imagecolorset($image, $index, $settings['new_color'][0], $settings['new_color'][1], $settings['new_color'][2]); // Restore Alpha imageAlphaBlending($image, true); imageSaveAlpha($image, true); // Save imagepng($image, $settings['new_icon']); // save image as gif imagedestroy($image); } How could this be updated to allow some dithering (is that what it is called?) - the thing that smooths out an image to avoid pixelation around the edges? Minor question. 1) Is there any reason why imagecolorexact doesn't work in this function. When I use imagecolorexact nothing happens and the picture remains the same. have 2 scripts one that allows me to insert and upload image and one that allows me to delete and remove image so i was thinking in mix both together so it would be like this first the delete image in an if statment then close } and then { an insert image but with an update mysql query} i am trying to do a modify form where user can modify the data so i will need to update the image on the directory so with both delete and insert would it do the job??? <?php define('ROOT_DIR', './'); define('PROPER', TRUE); /** * include common files */ include_once(ROOT_DIR. 'includes/common.inc.php'); // No album id has been selected if (isset($_GET['drivers'])) { // get the image file name so we // can delete it from the server $sql = "SELECT id, image FROM driversnew WHERE id = {$_GET['drivers']}"; $result = mysql_query($sql) or die('Delete photo failed. ' . mysql_error()); if (mysql_num_rows($result) == 1) { $row = mysql_fetch_assoc($result); define("GALLERY_IMG_DIR", "./images/"); // remove the image and the thumbnail from the server unlink(GALLERY_IMG_DIR . $row['image']); unlink(GALLERY_IMG_DIR . 'thumbs/' . $row['image']); // and then remove the database entry } } /////////// this where the upload script starts/////////// this where the upload script starts//////// this where the upload script starts //define a maxim size for the uploaded images define ("MAX_SIZE","100"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","150"); define ("HEIGHT","100"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message //and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='images/thumbs/'.$image_name; // call the function that will create the thumbnail. The function will get as parameters //the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("eurico_edy", $con); $query = "UPDATE products SET name = '$name', location = '$location', date_of_birth='$date_of_birth', car_number='$car_number', favourite_track='$favourite_track', least_favourite_track='$least_favourite_track', achievements='$achievements', achievements='$achievements' email='$email', image='$image' WHERE id = '$id'"; echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; echo ''.$newname.''; mysql_close($con); } ?> Hi folks, This has been wrecking my brain. I did do a google a few times to see if I can find a solution but nothing unfortunately. I want to be able to update the details on a page without having to reupload a new image each time. But if I don't open a new image for upload, I cannot update any of the other details. Below is the code and form etc for this particular thing... Please note this is just a project and will not be going live. I know there are vulnerabilities and I will work on those at a later stage. Thanks for any help with this current issue. <?php include_once('includes/header.php'); if(isset($_POST['new']) && $_POST['new']==1){ if (isset($_POST['submit'])) { if(!empty($_FILES['image']['name'])) { // Get image name $image = $_FILES['image']['name']; $image = mysqli_real_escape_string($con, $_FILES['image']['name']); $slide_text = mysqli_real_escape_string($con, $_POST['slide_text']); $youtube = mysqli_real_escape_string($con, $_POST['youtube']); $vid_text = mysqli_real_escape_string($con, $_POST['vid_text']); // image file directory $target = "uploads/".basename($image); if($_POST['image'] = ""){ $sql = "UPDATE slide SET slide_text='".$slide_text."', image='".$image."', youtube='".$youtube."', vid_text='".$vid_text."'"; } else{ $sql = "UPDATE slide SET slide_text='".$slide_text."', youtube='".$youtube."', vid_text='".$vid_text."'"; } $result = mysqli_query($con, $sql); if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) { $msg = "Image uploaded successfully"; }else{ $msg = "Failed to upload image"; } if(!$result){ die('Error: ' . mysqli_error($con)); } else{ $message = ' - <i class="fa fa-check success"> Record Updated!</i>'; } } } } $sql = "SELECT * FROM slide"; $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { ?> <!-- Header--> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Slide Show</h1> </div> </div> </div> <div class="col-sm-8"> </div> </div> <div class="content mt-3"> <div class="animated fadeIn"> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-header"><strong>Image </strong><small>Slide</small></div> <div class="card-body card-block"> <form role="form" method="post" action"" enctype="multipart/form-data"> <input type="hidden" name="new" value="1" /> <div class="modal-body"> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="image" class=" form-control-label">Image</label> <input type="file" id="image" name="image" value="<?php echo $row['image']; ?>" class="form-control"> </div> </div> <div class="col-6"> <div class="form-group"><label for="name" class=" form-control-label">Uploaded Image</label> <img src="uploads/<?php echo $row['image']; ?>" width="150" height="150" class="img-fluid hover-shadow" /> </div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="youtube" class=" form-control-label">Video</label> <input type="text" id="youtube" name="youtube" value="<?php echo $row['youtube']; ?>" placeholder="Enter Video URL" class="form-control"> </div> </div> <div class="col-6"> <div class="form-group"><label for="vid_text" class=" form-control-label">Video Text</label> <input type="text" id="vid_text" name="vid_text" value="<?php echo $row['vid_text']; ?>" placeholder="Video Text" class="form-control"> </div> </div> </div> <div class="form-group"><label for="slide_text" class=" form-control-label">Text Overlay</label> <textarea is="slide_text" name="slide_text" class="form-control"><?php echo $row['slide_text']; ?></textarea> </div> <div class="modal-footer"> <button type="submit" name="submit" id="submit" class="btn btn-primary">Confirm</button> </div> </form> </div> </div> </div><!-- .animated --> </div><!-- .content --> <?php } } ?> </div><!-- /#right-panel --> <!-- Right Panel --> <script src="assets/js/vendor/jquery-2.1.4.min.js"></script> <script src="assets/js/popper.min.js"></script> <script src="assets/js/plugins.js"></script> <script src="assets/js/main.js"></script> <script src="assets/js/lib/data-table/datatables.min.js"></script> <script src="assets/js/lib/data-table/dataTables.bootstrap.min.js"></script> <script src="assets/js/lib/data-table/dataTables.buttons.min.js"></script> <script src="assets/js/lib/data-table/buttons.bootstrap.min.js"></script> <script src="assets/js/lib/data-table/jszip.min.js"></script> <script src="assets/js/lib/data-table/pdfmake.min.js"></script> <script src="assets/js/lib/data-table/vfs_fonts.js"></script> <script src="assets/js/lib/data-table/buttons.html5.min.js"></script> <script src="assets/js/lib/data-table/buttons.print.min.js"></script> <script src="assets/js/lib/data-table/buttons.colVis.min.js"></script> <script src="assets/js/lib/data-table/datatables-init.js"></script> <script src="https://cdn.tiny.cloud/1/sw6bkvhzd3ev4xl3u9yx3tzrux4nthssiwgsog74altv1o65/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script> <script> tinymce.init({ selector: 'textarea', plugins: 'advlist autolink lists link image charmap print preview hr anchor pagebreak', toolbar_mode: 'floating', }); </script> <script type="text/javascript"> $(document).ready(function() { $('#customer-table').DataTable(); } ); </script> </body> </html> As you can see I am trying to use an If clause if the image field in the form is empty then I just want to update the other details. Else, if I fill the image field with a file, then update the lot. if($_POST['image'] = ""){ $sql = "UPDATE slide SET slide_text='".$slide_text."', image='".$image."', youtube='".$youtube."', vid_text='".$vid_text."'"; } else{ $sql = "UPDATE slide SET slide_text='".$slide_text."', youtube='".$youtube."', vid_text='".$vid_text."'"; } This doesn't work. Any ideas, besides give up?
Hello i kinda new to programing mostly learning myself stuf there so i need some help to figure out. so i have lets say static link who always same and i write something in input field and press search button. so i get new link and immediately going to dat link, which means i leaving my site. in my case i working with image so my problem, is it somehow possible to display image in same page while writing someting in input field when presing button and image just change down below not going directly to link ? P.S. sory for my english
i have this code
<html> <body>
<center>
<form action="#" method="POST">
</form>
<?php require_once 'linkgenerator.php' ?>
PHP link generator code
<?php
Edited March 18, 2020 by eagle101 This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=342583.0 Hi all, As you will see this is my first post in I really hope somebody can nail this for me, as I have been working on this for some time and I cannot get it to work. Basically this is the final part of a CMS I'm building, and all was fine until I needed to build in an option of a multiple image uploader to accompany all other stock details. I have managed to nail the 'insert' part of the multiple image uploader in this case up to 4 images, and the code is below for this part, any help with improvements though will be greatly appreciated. Code: [Select] if(isset($_POST['btnsubmit'])) { $flag=$_POST['flag']; if ($flag==0) { $name=$_POST['txtname']; $desc1=$_POST['e1m1']; $meta=$_POST['txtmeta']; $sr=$_POST['srno1']; $name=$_POST['txtname']; $ref=$_POST['Ref']; $desc=$_POST['e1m1']; $maker=$_POST['Maker']; $date=$_POST['Date']; $weight=$_POST['Weight']; $height=$_POST['Height']; $depth=$_POST['Depth']; $width=$_POST['Width']; $price=$_POST['txtprice']; $sold=$_POST['txtsold']; $active=$_POST['active']; $pcats=$_POST['pcats']; $subcats=$_POST['subcats']; $str_str=''; $p=''; $j=0; for($i=0;$i<=3;$i++){ $j++; $p=$_REQUEST['p$j']; $file=$_FILES['pic']['name'][$i]; if(!empty($file) ){ $str_str.=",pic$j='$file'"; } else if(!empty($p))$str_str.=",pic$j='$p'"; $path1="imgdata/stock/".$file; copy($_FILES['pic']['tmp_name'][$i], $path1); } $q24=mysql_query("update stock set stock_Name='$name', stock_MetaTitle='$meta', parent_Category='$pcats', sub_Category='$subcats', stock_Image='imgdata/stock/$pic[0]', stock_Image2='imgdata/stock/$pic[1]', stock_Image3='imgdata/stock/$pic[2]', stock_Image4='imgdata/stock/$pic[3]', stock_Ref='$ref', stock_Description='$desc1', stock_Maker='$maker', stock_Date='$date', stock_Weight='$weight', stock_Height='$height', stock_Depth='$depth',stock_Width='$width', stock_Price='$price', stock_Sold='$sold', stock_Active='$active', stock_DateTime='$dt2' where stock_Id=$sr") or die (mysql_error()); $flag=1; $conf="Data Updated Successfully - Click <a href='http://www.accendsandbox.co.uk/adminSallam/admin_categories.php'>here</a> to continue"; $update="1"; Code: [Select] <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 1 (Main):</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 2:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 3:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 4:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <input type="submit" name="btnsubmit" value="Submit"> <input type="submit" name="btndelete" value="Delete" DEFANGED_OnClick="return check();"> <input type="hidden" name="srno1" value="<?= $rows["stock_Id"];?>"> <input type="hidden" name="action" value="Upload"> All seems to be fine above, I can upload 1,2,3 or 4 images and the image goes into the server and the path to the database. But I then needed the option for my client to be able to click to edit a certain stock and then aswel as edit the other details, if he wanted to change one pic, no pics or all 4 he could and when he clicked submit, if there was a new image it would change if not it would stay as it is. So here is my attempt and at the moment it doesnt work, so I'm looking for help of any kid and anything can change. Code: [Select] $name=$_POST['txtname']; $ref=$_POST['Ref']; $desc=$_POST['e1m1']; $maker=$_POST['Maker']; $date=$_POST['Date']; $weight=$_POST['Weight']; $height=$_POST['Height']; $depth=$_POST['Depth']; $width=$_POST['Width']; $price=$_POST['txtprice']; $sold=$_POST['txtsold']; $meta=$_POST['txtmeta']; $active=$_POST['active']; $pcats=$_POST['pcats']; $subcats=$_POST['subcats']; $pic1=''; for($i=0;$i<4;$i++){ if(isset($_FILES['pic1']['name'][$i]))$pic1[$i]=$_FILES['pic1']['name'][$i]; else $pic1[$i]=''; } for($i=0;$i<4;$i++){ if(isset($_FILES['pic1']['name'][$i]))$path1= "./imgdata/stock/".$_FILES['pic1']['name'][$i]; //echo $_FILES['pic1']['tmp_name'][$i]." :". $path1; if(!empty($_FILES['pic1']['name'][$i])&&isset($_FILES['pic1']['name'][$i]))copy($_FILES['pic1']['tmp_name'][$i], $path1); } $q=mysql_query("insert into stock (stock_Name, stock_MetaTitle, parent_Category, sub_Category, stock_Ref, stock_Description, stock_Maker, stock_Date, stock_Weight, stock_Height, stock_Depth, stock_Width, stock_Price, stock_Sold, stock_Image, stock_Image2, stock_Image3, stock_Image4, stock_Active, stock_DateTime) values('$name','$meta','$pcats','$subcats','$ref','$desc','$maker','$date','$weight','$height','$depth','$width','$price','$sold','imgdata/stock/$pic1[0]','imgdata/stock/$pic1[1]','imgdata/stock/$pic1[2]','imgdata/stock/$pic1[3]','$active','$dt2')") or die (mysql_error()); $conf="Data Inserted Successfully - Click <a href='http://www.accendsandbox.co.uk/adminSallam/admin_stock.php'>here</a> to continue"; $update=1; Code: [Select] <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 1 (Main):</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p1" value="<?php echo $pic1;?>" /> <img src="<?php echo $pic1;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 2:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p2" value="<?php echo $pic2;?>" /> <img src="<?php echo $pic2;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 3:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p3" value="<?php echo $pic3;?>" /> <img src="<?php echo $pic3;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 4:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p4" value="<?php echo $pic4;?>" /> <img src="<?php echo $pic4;?>" height="100px" /> </td> </tr> What happens above as its all on the same page, is when a stock item is selected to be edited the form to update the images changes to the image upload options above, instead of the original ones for a new stock item at the top of this post. I can provide anything you need to help me with this, so please can somebody take a look and see if it can be got working, as its been a long problem for me this. Cheers hi all i have a problem here, Iv got a form that uploads images to a folder and updates the db with the name of that image, that work ok but if one of the upload field are left blank then the script updates the db with empty values how can i get it to only update the db with only submitted form field data???? here is the form Code: [Select] <?php if (isset($_GET['id'])) { $id = $_GET['id']; } ?> <form action="ud_image.php?id=<? echo "$id"?>" method="post" enctype="multipart/form-data" name="form1" id="form1"> <table class="udp"> <tr> <th>Thumbnail:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 1:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 2:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 3:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 4:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /><input type="submit" name="Submit" value="Upload" /></td> </tr> </table> </form> and here is the processing page <?php include("protect/password_protect.php"); error_reporting(E_ALL); include ("../includes/db_config.php"); $con = mysql_connect($db_hostname,$db_username,$db_password); @mysql_select_db($db_database) or die( "Unable to select database"); $path1= "../thumbnails/".$_FILES['ufile']['name'][0]; $path2= "../images/".$_FILES['ufile']['name'][1]; $path3= "../images/".$_FILES['ufile']['name'][2]; $path4= "../images/".$_FILES['ufile']['name'][3]; $path5= "../images/".$_FILES['ufile']['name'][4]; //copy file to where you want to store file copy($_FILES['ufile']['tmp_name'][0], $path1); copy($_FILES['ufile']['tmp_name'][1], $path2); copy($_FILES['ufile']['tmp_name'][2], $path3); copy($_FILES['ufile']['tmp_name'][3], $path4); copy($_FILES['ufile']['tmp_name'][4], $path5); ?> <html> <head> <title>Update Project Images</title> <link rel="stylesheet" type="text/css" href="../../project/backend/style.css" /> </head> <body> <table class="udip"> <tr> <th><? echo "<img src=\"$path1\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path2\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path3\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path4\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path5\" width=\"150\" height=\"150\">";?></th> </tr> <tr> <td><? echo "File Name :".$_FILES['ufile']['name'][0]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][1]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][2]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][3]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][4]."<BR/>";?></td> </tr> <tr> <td><?echo "File Size :".$_FILES['ufile']['size'][0]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][1]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][2]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][3]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][4]."<BR/>";?></td> </tr> <tr> <td><? echo "File Type :".$_FILES['ufile']['type'][0]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][1]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][2]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][3]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][4]."<BR/>";?></td> </tr> </table> </body> </html> <? $filesize1=$_FILES['ufile']['size'][0]; $filesize2=$_FILES['ufile']['size'][1]; $filesize3=$_FILES['ufile']['size'][2]; $filesize4=$_FILES['ufile']['size'][3]; $filesize5=$_FILES['ufile']['size'][4]; if($filesize1 && $filesize2 && $filesize3 && $filesize4 && $filesize5 != 0) { echo "We have recieved your files<p>"; } else { echo "Error in you images check and try again Database has been updated to blank images so no images will be shown on details page."; } $query = "UPDATE $db_table SET thumbnail = '".$_FILES['ufile']['name'][0]."', image1 = '".$_FILES['ufile']['name'][1]."', image2 = '".$_FILES['ufile']['name'][2]."', image3 = '".$_FILES['ufile']['name'][3]."', image4 = '".$_FILES['ufile']['name'][4]."' WHERE id = '".$_GET['id']."'"; if (!mysql_query($query,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> I want to validate my PHP files to ensure that I didn't forget to import all the classes assigned to attributes. I will be using ReflectionClass to do so and need the FQCN's and not the filenames. Originally, I tried get_declared_classes(), however, ran into issues where a class was already declared. I came up with the following which appears to work, however, it was created based on trial and error and suspect there might be edge cases where it will not provide the desired results (and it is pretty damn ugly as well). How would you recommend doing so? A couple thoughts a Use composer to come up with the classes based on filename and use either vendor/Composer autoload_classmap.php or autoload_static.php. I don't really like this approach as it requires me to update composer to add any new files. Use composer but figure out how it generates the class map and use a similar approach. Appears that it is using phpstan or some other utility but I haven't really investigated. Use some third party script to generate the class maps. If so, please provide recommendations. Use some more modern approach other than PhpToken. If so, please provide recommendations. Use get_declared_classes() to get a base line and then require the PHP file to find the added class names and somehow deal with issues related to classes already being declared. Use tokens and my parseFile() method. If so, any recommendations on changing?PS. I originally wasn't 100% that attributes in traits and abstract classes would be propagated to the concrete class, but I should have known it to be true and this was confirmed by testing. At this time, I really just need the concrete classes, however, maybe in the future I will use the script to do some analysis on interfaces, traits, etc.
private function parseFile(string $filename):array { $getNext=null; $getNextNamespace=false; $skipNext=false; $isAbstract = false; $rs = ['namespace'=>null, 'class'=>[], 'trait'=>[], 'interface'=>[], 'abstract'=>[]]; foreach (\PhpToken::tokenize(file_get_contents($filename)) as $token) { if(!$token->isIgnorable()) { $name = $token->getTokenName(); switch($name){ case 'T_NAMESPACE': $getNextNamespace=true; break; case 'T_EXTENDS': case 'T_USE': case 'T_IMPLEMENTS': //case 'T_ATTRIBUTE': $skipNext = true; break; case 'T_ABSTRACT': $isAbstract = true; break; case 'T_CLASS': case 'T_TRAIT': case 'T_INTERFACE': if($skipNext) { $skipNext=false; } else { $getNext = strtolower(substr($name, 2)); } break; case 'T_NAME_QUALIFIED': case 'T_STRING': if($getNextNamespace) { if(array_filter($rs)) { throw new \Exception(sprintf('Namespace mus be defined first in %s', $filename)); } else { $rs['namespace'] = $token->text; } $getNextNamespace=false; } elseif($skipNext) { $skipNext=false; } elseif($getNext) { if(in_array($token->text, $rs[$getNext])) { throw new \Exception(sprintf('%s %s has already been found in %s', $rs[$getNext], $token->text, $filename)); } if($isAbstract) { $isAbstract=false; $getNext = 'abstract'; } $rs[$getNext][]=$token->text; $getNext=null; } break; default: $getNext=null; } } } $rs['filename'] = $filename; return $rs; }
Hi, I am struggling with a form in php. I am trying to add a form by using the include function. I want to include thsi form on all pages so it would be very useful if I can save the current page name somewhere so that I can use to validate the form. For example, this is the form I am trying to include. <?php if(!empty($errors)) { if(isset($errors['sendError'])) { echo '<p><strong class="error">There was a problem with our system please contact us directly.</strong></p>'; } else { echo '<p><strong class="error">Please check the form below for errors.</strong></p>'; } } ?> <form action="index.php" method="post" id="form1"> <p> <label><?php if(isset($errors['name'])) { echo '<span class="error">'; } ?>Name<font color="red">*</font>: <?php if(isset($errors['name'])) { echo '</span>'; } ?></label> <input id="search1" id="complete" type="text" value="<?php echo $form['name']; ?>" name="name" size="60" align="right" style="background:#EEF5A4" /> <label><?php if(isset($errors['company'])) { echo '<span class="error">'; } ?>Company: <?php if(isset($errors['company'])) { echo '</span>'; } ?></label> <input id="search1" id="complete" type="text" value="<?php echo $form['company']; ?>" name="company" size="60" align="right" /> <label><?php if(isset($errors['phone'])) { echo '<span class="error">'; } ?>Phone Number: <?php if(isset($errors['phone'])) { echo '</span>'; } ?></label> <input id="search1" id="complete" type="text" value="<?php echo $form['phone']; ?>" name="phone" size="60" align="right" /> <label><?php if(isset($errors['email'])) { echo '<span class="error">'; } ?>Email<font color="red">*</font>: <?php if(isset($errors['email'])) { echo '</span>'; } ?></label> <input id="search1" id="complete" type="text" value="<?php echo $form['email']; ?>" name="email" size="60" align="right" style="background:#EEF5A4" /> <label><?php if(isset($errors['enquiry'])) { echo '<span class="error">'; } ?>Enquiry: <?php if(isset($errors['enquiry'])) { echo '</span>'; } ?></label> <textarea id="search1" id="complete" textarea name="enquiry" rows=4 cols=40 value="<?php echo $form['enquiry']; ?>" name="enquiry" size="60" align="right"></textarea> </p> <p> <input type="submit" class="formbutton" value="Submit" /> <input type="reset" class="formbutton" value="Reset" /> </p> <p><font color="red">*</font> Denotes a required field</p> </form> Because I am going to use this form on all pages, I would like it to include whatever the filename is rather than index.php in the first line of the form so that when the user clicks submit, it will stay on the same page but validate the form based on the mandatory fields. I don't know if the question is clear. I would very much appreciate any help at all. Thank you very much. I need to process a CSV file in database (MySql using LOAD DATA INFILE)), while the code is working fine but it works only with file that is already on my apache server (where php is installed). Is there any way (Java/Ajax or anything) that I can prompt user to select a file from any loaction they prefer including there desktop?? Thanks in advance!! |