
Psycho
Moderators-
Posts
12,160 -
Joined
-
Last visited
-
Days Won
130
Everything posted by Psycho
-
I'm not surprised. As I already stated you should store your date values as date types. Part of my solution requires that you fix your database.
-
I am not going to read through all of that code. But, to do what you want you should: Run all the "logic" of your code first and determine what the output should be - THEN create the output. As part of this process you can determine what the appropriate title should be. Do, not intermix logic within the output like this: <div id="status"> <?php if($active == true) { echo "Your account is active"; } else { echo "Your account is not active"; } ?> </div> Instead, run the logic before you ever start the HTML output. Store the output in various variables and include those in the output. <?php if($active == true) { $activeText = "Your account is active"; } else { $activeText = "Your account is not active"; } ?> <html> . . . <div id="status"><?php echo $activeText; ?></div>
- 8 replies
-
- title
- dynamic title
-
(and 2 more)
Tagged with:
-
I've already provided a solution which you don't want to implement. Good luck.
-
Don't know. Any fields that will contain 'dates' should be a type that was meant for storing . . . dates. Change the field type and store the dates correctly.
-
No it will not. Your first post that showed a QUERY you said worked only for the last day appeared to indicate that the post_created field was some type of date field. If not, you should change it to one. Although, I don't think Kicken's last post will give you what you want. It will find the most recent post across all users and then only select posts that were created on that day. I think you were stating that you want the posts for the most recent day - for each user. So, if bob's most recent post was yesterday, you want all of his posts from yesterday. But, if dave's most recent post was from two days ago you want all of dave's posts from two days ago. So, if I am understanding your request correctly, I think this would work. Note: I don't know the correct field name to identify the user, so I guessed. Also, I assumed the post_created will be a timestamp type field. SELECT *.source FROM mediaPost AS source JOIN ( SELECT user_id, MAX(DATE(post_created)) AS post_date FROM mediaPost WHERE post_category = $cid AND post_enabled = 1 GROUP BY user ) as last ON source.user_id = last.user_id AND DATE(source.post_created) = last.post_date WHERE post_category = $cid AND post_enabled = 1
-
Doing inserts in a batch is much faster than processing them individually. But, that is typically the solution to use when you already have a number of records up-front. With what you are proposing, you don't know how many or how quickly the user will be making selections. Users aren't going to be clicking multiple ratings each second such that it should be an issue. You say this has the "potential" to be big. Well, if it does become big you should then have the capital and the resources to hire experienced developers and architects to recode the application to scale for the number of users. It's fine to try and look for potential problems, but trying to solve all the potential problems before you even see that there is one will only increase the time of getting something to production and, worse, can cause you to implement so much complexity that the application is buggy. It is better to identify these potential problems and identify how you will measure the activity to determine when you would need to react (e.g. monitor DB activity). In fact, the best solution might not to be creating some workaround in the code, but might be to scale the hardware to support the load. But, since you seem to have already made up your mind, I'm not sure why you asked. Anyway, let's say you go with the method of saving the data in text files. You still have the problems to overcome that I raised previously. If a user rates an item, leaves the page and comes back how do you plan to show the user that they have already rated the item? You are now going to have to do the DB operation to get the item data along with any saved ratings by the user - then you need to go see if there is a text file for the user and parse that to see if the user has already rated the item. Only then can you output the page and show the correct details. Also, if you are only going to process the file after X number of ratings, what happens if the user only rated X-1 items and then leaves? Are you going to store that file indefinitely? If the user's ratings don't get saved till they come back then they won't be calculated in the cumulative ratings for those items. You will have lots of records where the cumulative ratings are not accurate since user left with some records not being saved. Plus, you have to contend with potential data corruption since doing this through flat-files is much more likely to have problems than using the database. If a user was to click two items too close together one write operation may not complete before the other starts. You would have to implement some sort of process to 'lock' the files while they are being written to so that if another request is made that will edit the same file it will wait until the first one completed.
-
You could use RegEx in your query, but that is a sub-optimal solution since RegEx will be slow. Instead, you should handle this when saving the records to your database by stripping off the extraneous bit. If you do need the full URL then you should add a column and put the base URL in one and the parameters of the URL in the other.
-
I'm not making any promises, but you can give this a try <?php if (get_magic_quotes_gpc()) { function stripslashes_gpc(&$value) { $value = stripslashes($value); } array_walk_recursive($_GET, 'stripslashes_gpc'); array_walk_recursive($_POST, 'stripslashes_gpc'); array_walk_recursive($_COOKIE, 'stripslashes_gpc'); array_walk_recursive($_REQUEST, 'stripslashes_gpc'); } $message = ''; if (isset($_POST["publish-p"])) { $categoria= mysql_real_escape_string($_POST['categoria']); $categoria2= mysql_real_escape_string($_POST['categoria2']); $destaque= mysql_real_escape_string($_POST['destaque']); $publicado= mysql_real_escape_string($_POST['publicado']); $news_title= mysql_real_escape_string($_POST['news_title']); $news_subtitle= mysql_real_escape_string($_POST['news_subtitle']); $news_desc= mysql_real_escape_string($_POST['news_desc']); $news_post= mysql_real_escape_string($_POST['news_post']); $news_date= mysql_real_escape_string($_POST['news_date']); $hour= mysql_real_escape_string($_POST['hour']); $news_image= mysql_real_escape_string($_POST['news_image']); $news_image_peq= mysql_real_escape_string($_POST['news_image_peq']); $copyright= mysql_real_escape_string($_POST['copyright']); $publish="INSERT INTO news (news_guid, categoria, categoria2, destaque, publicado, news_title, news_subtitle, news_desc, news_post, news_date, hour, news_image, news_image_peq, copyright) VALUES (uuid(), '$categoria', '$categoria2', '$destaque', '$publicado', '$news_title', '$news_subtitle', '$news_desc', '$news_post', '$news_date', '$hour', '$news_image', '$news_image_peq', '$copyright')"; mysql_query($publish) OR DIE(mysql_error()); //mensagem após submeter dados $message = "<script>alert('NotÃcia publicada!');</script>"; //Add image upload if(isset($_FILES['uploadedfile'])) { $target_path = "uploads/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { $message .= "<br>The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ $message .= "<br>There was an error uploading the file, please try again!"; } } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta lang="en_US" /> <meta name="viewport" content="width=device-width" /><!-- Set the viewport width to device width for mobile --> <title>Publicar notÃcia MRN</title> <link href="../stylesheets/foundation.min.css" rel="stylesheet" type="text/css" /> <link href="../stylesheets/app.css" rel="stylesheet" type="text/css" /> <link href="../stylesheets/admin.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <link rel="shortcut icon" href="../images/logobar.ico" type="image/x-icon"> <script src="http://code.jquery.com/jquery.js"></script> <script type="text/javascript" src="../js/jquery.formvalidator.js?upd=1.5.1"></script> <script type="text/javascript" src="tinymce/tinymce.min.js"></script> </head> <body> <div class="bo-header"><div class="row"><div class="twelve columns"> <p>Olá <?php echo "<strong>".$_SESSION["name"]."</strong>."; ?><br/><strong><a href="?logout">Logout</a></strong></p> </div></div></div> <!--MENU--> <!-- Navigation --> <nav class="top-bar fixed"> <div class="twelve columns" ><div style="background:url(../images/carbonback.png); margin-top:2px;"><img src="../images/cabecresize.png" alt="Cabeçalho"></div></div> <ul> <li class="name"><h1 class="menu_dp">Menu</h1></li> <li class="toggle-topbar"><a href="#"></a></li> </ul> <section> <ul class="left"> <!--<li class="menu"><a href="?perfil" title="Ver perfil">Perfil</a></li>--> <li class="menu"><a href="?submit-news" title="Publicar notÃcia MRN">Publicar notÃcia MRN</a></li> </ul> </section></nav> <hr class="linha"/> <?php echo $message; ?> <!--CONTEUDO--> <div class="row"> <div class="twelve columns"> <form action="#" method="post" onsubmit="return $(this).validate()" name="publish" > <h3 class="n3">Publicar notÃcia</h3> <div class="publish-content"> <div> <h3 class="n3v4">Categoria</h3> <select name="categoria"> <option value="Autos/Pistas">Autos/Pistas</option> <option value="Autos/Ralis-TT">Autos/Ralis-TT</option> <option value="Motos/Pistas">Motos/Pistas</option> <option value="Motos/Ralis-TT">Motos/Ralis-TT</option> <option value="Outros">Outros</option> <option value="Entrevistas">Entrevistas</option> <option value="ci">C&I: OnTheRoad</option> <option value="Multimedia">Multimédia</option> </select> </div> <br/> <div> <h3 class="n3v4">Categoria 2 (opcional)</h3> <select name="categoria2"> <option value="">Nenhuma</option> <option value="Autos/Pistas">Autos/Pistas</option> <option value="Autos/Ralis-TT">Autos/Ralis-TT</option> <option value="Motos/Pistas">Motos/Pistas</option> <option value="Motos/Ralis-TT">Motos/Ralis-TT</option> <option value="Outros">Outros</option> <option value="Entrevistas">Entrevistas</option> <option value="ci">C&I: OnTheRoad</option> <option value="Multimedia">Multimédia</option> </select> </div> <br/> <h3 class="n3v4">Destaque?</h3> <label class="cbox"> <input type="radio" name="destaque" value="sim" checked>Sim</input> <input type="radio" name="destaque" value="não">Não</input> </label> <br/> <h3 class="n3v4">Publicar já?</h3> <label class="cbox"> <input type="radio" name="publicado" value="sim" checked>Sim</input> <input type="radio" name="publicado" value="não">Não</input> </label> <br/> <input name="news_title" type="text" class="title" placeholder="(tÃtulo)" data-validation="required" title="required"/> <input name="news_subtitle" type="text" class="title" placeholder="(subtÃtulo)" data-validation="required" /> <input name="news_desc" type="text" class="description" placeholder="(descrição)" data-validation="required" title="required" maxlength="165"/> <textarea name="news_post" type="text" class="post" placeholder="(notÃcia)" data-validation="required" title="required" ></textarea> <input name="news_date" type="text" class="date" placeholder="(data)" data-validation="required" title="required" id="datepicker" /> <input name="hour" type="text" class="description" placeholder="(hora HH:MM)" data-validation="required" title="required" maxlength="5" data-format="hh:mm:ss" id="datetimepicker3" /> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploadedfile" type="file" /><br /> <input type="submit" value="Upload File" /> <input name="news_image" type="text" class="description" placeholder="(imagem homepage)" data-validation="required" title="required"/> <input name="news_image" type="text" class="description" placeholder="(imagem main)" data-validation="required" title="required"/> <input name="news_image_peq" type="text" class="description" placeholder="(imagem pequena)" data-validation="required" title="required"/> <input name="copyright" type="text" class="description" placeholder="(Copyright da/s Imagem/ns)" data-validation="required" title="required"/></div> <div class="publish-footer"> <input type="submit" name="publish-p" value="Publicar" class="button"> <input type="submit" name="cancel" value="Cancelar" class="secondary button" onclick="window.location='../login/?submit-news'" > </div> </form> </div> </div> <?php include ("rodape.php") ?> <!--SCRIPTS--> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script> $(function() { $( "#datepicker" ).datepicker({ changeYear: true, dateFormat: "dd'-'mm'-'yy", showButtonPanel: true, }); }); </script> <!-- script para Toogle Menu --> <script src="../js/toogle-menu.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", plugins: [ "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker", "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking", "save table contextmenu directionality emoticons template textcolor colorpicker", "paste" ], image_advtab: true, font_size_style_values: "9px,10px,11px,12px,13px,14px,16px,18px,20px", toolbar1: "sizeselect | bold italic | insertfile undo redo | styleselect | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media",//used font size for showing font size toolbar toolbar2: "fontselect | fontsizeselect | colorpicker",//used font size for showing font size toolbar style_formats: [ {title: 'Bold text', inline: 'b'}, {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}}, {title: 'Red header', block: 'h1', styles: {color: '#ff0000'}}, {title: 'Example 1', inline: 'span', classes: 'example1'}, {title: 'Example 2', inline: 'span', classes: 'example2'}, {title: 'Table styles'}, {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'} ], resize: false, inline_styles : true, }); </script> </body> </html>
-
Slow down, you are making changes without having any understanding of what you are doing. You want to have ONE form with the normal form data AND the file input filed for the upload. Then have the form post to ONE page to do the processing. Go ahead and have the form post back to itself as you were previously. Then, after you have processed the text input and added to the database, add additional code to implement the saving of the file upload. Actually, you should be splitting out the functionality into separate functions or PHP pages to help keep things tidy. But, for now, go ahead and implement it all in one page. Just use comments and structure within your code to keep it organized.
-
Well, you have an individual delete link for each record. You want to change that to have a form and include a checkbox for each record with a single button to delete the selected records. Your code is very hard to follow, but the logic appears to be backwards. It appears you are outputting the page THEN processing the deletes. It needs to be the other way around, otherwise you will be displaying records that were meant to be deleted THEN deleting them. Another issue, element IDs in the HTML page MUST be unique. You gave all the checkboxes the same IDs. Also, the JavaScript function has some unnecessary code. Once you've determined that at least one record is checked - just return true. Lastly, there is no need to have different processing to delete a single record vs. deleting multiple records. You just need to call the same page and format the input data appropriately. I made a change for the single and multiple deletes to call back to this same page, make the delete and then refresh the list. You can change that, but you should definitely have both delete But, here's the biggest problem while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value='".$rows['id']."'></td>"; The variable you are assigning the query result to is $row, but you are referencing $rows Here's a complete rewrite. There could be some minor typos to resolve, but the logic is much more solid <?php $con=mysqli_connect("localhost","stradsol","D#v,b5TnQ!D!","stradsol_sales"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //See if any records were selected to be deleted if(isset($_POST['ids'])) { //Force all values to be integers are remove 0 values $deleteIDsList = array_filter(array_map('intval', $_POST['ids'])); //Create and run ONE delete query $query = "DELETE FROM Persons WHERE id IN ($deleteIDsList)"; $result = mysqli_query($con, $query); } //Get list of current records to display $query = "SELECT * FROM Persons"; $result = mysqli_query($con, $query); $output = ''; while($row = mysqli_fetch_array($result)) { $output .= "<tr>\n"; $output .= " <td><input name='ids[]' type='checkbox' id='' value='{$row['id']}'></td>\n"; $output .= " <td>{$row['id']}</td>\n"; $output .= " <td>{$row['date']}</td>\n"; $output .= " <td><a href='config_info.php?id={$row['id']}'>{$row['name']}</a></td>\n"; $output .= " <td>{$row['email']}</td>\n"; $output .= " <td>{$row['contacts']}</td>\n"; $output .= " <td>{$row['requirement']}</td>"; $output .= " <td style='display:none;'>{$row['company_name']}</td>\n"; $output .= " <td style='display:none;'>{$row['address']}</td>\n"; $output .= " <td>{$row['startdate']}</td>\n"; $output .= " <td>{$row['final_details']}</td>\n"; $output .= " <td style='display:none;'>{$row['status']}</td>\n"; $output .= " <td style='display:none;'>{$row['lead_close']}</td>\n"; $output .= " <td><a href='edit_eg1.php?id={$row['id']}'>Edit</a></td>\n"; $output .= " <td><a href='Follow_history.php?id={$row['id']}'>Follow_history</a></td>\n"; $output .= " <td><a href='add_follow.php?id={$row['id']}'>Followup</a></td>\n"; $output .= " <td><a href='?ids[]={$row['id']}'>Delete</a></td>\n"; $output .= "</tr>\n"; } mysqli_close($con); ?> <html> <head> <title>Strad Hosting Limited -Web Hosting</title> <script language="javascript"> function validate() { var chks = document.getElementsByName('ids[]'); for (var i=0; i<chks.length; i++) { if (chks[i].checked) { return true; } } //No records were checked alert("Please select at least one."); return false; } </script> </head> <body> <form name='form1' method='post' action='' onSubmit='return validate();'> <table border='1' style='background-color: white;'> <tr> <th></th> <th>id</th> <th style='padding-left: 11px;'>Lead Generated Date </th> <th>name</th> <th>email</th> <th>contacts</th> <th>requirement</th> <th style='display:none;'>Company name</th> <th style='display:none;'>Address</th> <th>Next Follow-Up date</th> <th>Final_Details</th> <th style='display:none;'>Status</th> <th style='padding-left: 12px; display:none;'>Lead Closed Date</th> <th>EDIT</th> <th>Follow-up History</th> <th>Add Follow-up</th> <th>Delete Record</th> </tr> <?php echo $output; ?> <tr><td><input name='delete' type='submit' id='delete' value='Delete'></td></tr> </table> </form> <br><br> <a href="index2.php">[ Back To Home ]</a> </body> </html>
-
Have you identified that doing them as they are selected is causing performance or balancing issues? No need to over-engineer something for a perceived problem. I can't imagine that so many users are going to be ranking items in such volume that it would be a problem. Well, not unless you had something such as YouTube or Facebook - in which case there will be developers and architects that would be designing the process. But, I will answer your question nonetheless with my suggestions: It is certainly possible to "save up" these selections and then submit them at one time. But, it adds a lot more complexity and potential for errors. I would not store them in a flat file as that would be worse from a performance impact. Instead, you could store the selections in a cookie or in the session data. So, every time the user clicks to make a rating make an AJAX call to a PHP page and pass the ID of the records being rated and the rating. That PHP page will take that data and add to an array in either the cookie or session data. Then it can check to see how many records are in the array. If more than a certain number the page would additionally use that data to insert the necessary data into the database. But, now comes the problems with such an approach. The user will close the browser at some point. Any unsaved ratings could be lost. If they are in the session, they will definitely be lost. If they are in a cookie they will likely still be in the cookie when the user returns. But, what would happen when the user views one of the records that they previously rated? In addition to pulling the user's rating from the database you would have to also check the cookie to see if any of the items being displayed on the page have already been rated. The same applies as the user navigates from page to page. While showing records and the user's rating you have to pull from the database and the cookie/session - otherwise it would seem as if the user's rating was not saves (which it hasn't been yet). Lastly, many/most applications with a rating system show the cumulative rating of items. So, if 10 people rated an item at 5 and another 10 rated it at 4, a cumulative rating of 4.5 would be displayed to users viewing that record. By not saving the ratings as people make them, this would rarely be accurate. You could include a single user's unsaved ratings in the calculation when displaying a page (again, more complexity) but it would be very, very difficult to take into account other users' unsaved rankings for that record. Let's take YouTube as an example. Say you post a new video. As people view your video and rate it those rating would not get updated until the user's happen to hit whatever magical number of ratings you have defined. They may not even hit that number in that day. So, there could be hundreds or thousands of ratings that go unsaved for a long period. Of course, you could implement a timer within the JavaScript code to save all unsaved ratings after X minutes. But, that again adds more complexity and room for errors.
-
If you want help, please provide the information requested. Jazzman requested that you post the code for the form page and the uploader page and you just linked to the tutorial. How do we know that there isn't a typo or that something else isn't quite right in your code. We can't help fix something if you aren't going to share it with us.
-
That is nowhere near how the process works for file uploads. Here is a good tutorial you can review: http://www.tizag.com/phpT/fileupload.php Go read that, then write your code. If you have problems then post back.
-
Both errors appear to be due to the same problem, I don't see where $con is defined before this line is executed: $result = mysqli_query($con, "SELECT '".$dev_id."', . . .
-
How is the ID any more/less secure than the hash since they are both serving the same purpose? I really think you are adding complexity that serves no real purpose. But I still don't understand your problem. Are you saying that when the page is submitted you want the names of all the chefkboxes - even the ones that are not checked? If so, there better ways to accomplish this. But, you could populate a hidden field with the values, but that's a hack IMO. Instead you should save the criteria that was used to select the values for the form. So,if you were including all records where Surname='smith' then you should save that criteria in a hidden field and use it on the processing page.
-
The fact that you may have built a custom function to prevent some SQL Injections doesn't mean you should do that. There are already built-in functions and/or processes to prevent SQL Injection which you should use. I also don't know why you are escaping so many different values. It looks like you are trying to escape the data for output to an HTML page more so than to prevent SQL Injection. Those are two different things and should be implemented separately. If you escape content for HTML purposes before storing int he database you lose the ability to use the data for other purposes. You should store the data in the database exactly as the user submitted it - only escaping to prevent SQL Injection using the appropriate functions/processes that already exist. Then, when you are outputting the data you should escape as needed based upon the mode of output: HTML, XML, etc. Again, you should use the appropriate escape functions such as htmlentities() to accomplish that.
- 3 replies
-
- sql injection
- login
-
(and 1 more)
Tagged with:
-
Um, no. That doesn't do anything to prevent SQL injection since most SQL injection is due to the use of quote marks in the content. You shouldn't create your own solution anyway. Either use the built-in functions of the platform you are using or use prepared statements. With mysqli_ extention you can use mysqli_real_escape_string or you can use prepared statement. Prepared statements are the best option, but take a little more time to learn. It is beyond the capability to try and instruct you in the use of prepared statements in a forum post. But, there are plenty of tutorials available. Here is the manual for it though: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php FYI: You should never modify a password using something like that. Any time you modify a password you risk making it less secure. You should only need to hash it
- 3 replies
-
- sql injection
- login
-
(and 1 more)
Tagged with:
-
Hmm, your data shows a one-to-one relationship between the data in the two tables. As for more security, no it doesn't add any security. How you configure your tables should be completely dependent upon the nature and structure of the data, not based upon any preconceived notions. As for why the query I provided didn't work for you is an unknown. I actually created two tabled with the exact same configuration and data you supplied and I received the correct results.
-
I'm not clear on what you are asking. But, let's step back a second. What security risk do you think exists by using the primary ID of the records in the database? That's kind of the whole point of having primary IDs. If there is a security risk it is because you created one. But, as to your code, you are using the hash as the name of the fields. You should probably make the names of the fields an array and use the hash as the values. If you need the IDs of the items that are checked you will need to run a query on the values that are POSTed. So, let's say your fields are created more like this (note the field names and values): <div style="width:1500px;height:20px;"> <div style="width:20px;height:12px;float:left;"><input type="checkbox" name="items[]" value="03c2e7e41ffc181a4e84080b4710e81e"></div> <div style="width:90px;height:12px;float:left;"><a href="UserShelvesUpdate.php?ID=03c2e7e41ffc181a4e84080b4710e81e">New</a></div> </div> <div style="width:1500px;height:20px;"> <div style="width:20px;height:12px;float:left;"><input type="checkbox" name="items[]" value="a39e9eea66930fe0050d56a28bafab72"></div> <div style="width:90px;height:12px;float:left;"><a href="UserShelvesUpdate.php?ID=a39e9eea66930fe0050d56a28bafab72">Desmond</a></div> </div> Now, when the form is posted you will have a POST array value of $_POST['items'] which contains the MD5 value of all the checked items. Note, if no items are checked then that array index will not exist. You can then use that data like so: if(!isset($_POST['items'])) { //No items were checked } else { //Create a comma separated string of the hash values (enclosed in single quotes) $hashListString = "'" . implode("', '", $_POST['items']) . "'"; //Create & Run query to get IDs $query = "SELECT id FROM table_name WHERE hash IN ({$hashListString})"; $result = mysql_query($query); }
-
I have no idea what your problem may be. The code worked for me when I tested it. The comma in the error message definitely looks out of place, but I don't see anything in the code to account for it. The only advice I can offer is to add some debugging to the script to see what is and is not happening. EDIT: I do see one problem in that the code should delete the previous file before renaming a new one. But, based on your error messages that isn't the problem. <?php ini_set('display_errors', 1); error_reporting(E_ALL ^ E_NOTICE); //Define locations for uploads and final file $path_to_uploads = "uploads/"; $final_image = "images/webcam.jpg"; //Path to save the most recent //Get the files in the upload directory $uploaded_files = glob("{$path_to_uploads}*"); echo "<b>Debug:</b> Found " . count($uploaded_files) . " files in '{$path_to_uploads}'<br>\n"; //Create var to detect recent files $recent_date = 0; //Iterate through all uploads foreach($uploaded_files as $file) { $file_date = filectime($file); echo "<b>Debug:</b> File: '$file', Date: {$file_date}<br>\n"; //If file is newer, rename it else delete it if($recent_date < $file_date) { echo "<b>Debug:</b> File is newer than previous image. Delete prev. image and rename the file<br>\n"; if(is_file($final_image)) { unlink($final_image); } rename($recent_file, $final_image); $recent_date = $file_date; } else { echo "<b>Debug:</b> File is NOT newer than previous file. Delete the file<br>\n"; unlink($file); } } ?> <html> <head> <title>Webcam Test</title> </head> <body> <iframe src="http://www.cypresshi...ges/webcam.jpg" width="640" height="360" frameborder="0" scrolling="no"> </iframe> </body> </html>
-
The above error message is what displays when I go to that page. Why is there a comma in the path? You've not stated the location of the images or uploads directories, nor have you shared what you are currently using in the code for those two locations. So, not much we can do to help at this point.
-
@KubeR, What the others are getting at is that you are trying to solve the wrong problem. It 'appears' you have made some decisions based upon your current knowledge and your comfort zone. There are many reasons why your current method of storing that data is problematic. Your current problem is just the tip of the iceberg. You need to revise your database schema to do this properly. If you provide details on what the information is that you are storing and the business rules around it, we can help to provide a revised schema. Otherwise, you are going to be hard pressed to find anyone (knowledgeable) on this forum to help you since doing so would only enforce a bad behavior.
-
To test your code before putting it online. It is much, much faster to develop locally than to have to download a file (or files), make some edits, copy the file(s) back up to the server - THEN see if it works. It is very easy to set up a local web server for testing. If you will be creating your pages on a Windows machine, you can use XAMPP. Just download the lite version and extract to the root of one of your drives (e.g. C:\XAMPP\, D:\XAMPP\, etc.). Then find the find the executable xampp-control.exe and run it. In the dialog that opens click the buttons to start the Apache web serrver and the MySQL server. You now have a fully functioning PHP and MySQL web server.
-
That will not work for two reasons. 1) If there are other images in that directory that are used for the site they will end up getting deleted. 2) After determining the most current image, the logic will delete the current webcam.jpg then replace it with the current image. But, if there are no new uploads, the webcam.jpg IS the most current image. So, the logic would delete that image and then try to rename the most current image (which would have just been deleted!). You should create a separate folder just for the purpose of uploading the images to. As far as your paths, where is the images folder in relation to where the php file is located? In my tests the php file was in the same folder as the images and uploads folders. [Site_Root_Folder] | | - [ImageTest] | - testpage.php | - [images] | - [uploads] For my values I just defined the path starting with the folder name with nothing before it. E.g. $path_to_uploads = "uploads/";
-
@donlizard, The code I posted was a working example. Just change the values of the two variables at the top pf the script and then change the HTML at the bottom to what you want. Note: the script assumes that the files in the upload directory are ONLY the ones being uploaded by the webcam. It will process all the files in that directory - either moving them to be the new current image or deleting them.