Jump to content

yathrakaaran

New Members
  • Posts

    5
  • Joined

  • Last visited

Posts posted by yathrakaaran

  1. Hi Everyone, this is a very old code. I know I have to change the 'addslashes' method in this code. I also just changed the code using 'mysqli'. There are two files to upload the images to a gallery, preexport.php and export.php. The upload works up to five images. if I choose 6 or more and press add images, the browser refreshes itself and the upload won't happen. All the fields on the form clears itself and no errors shows up...can you please take a look and help me correct this problem? Here are the two files...

     

    export.php

    <?php
    include("config.inc.php");
    
    if ($_SERVER['REQUEST_METHOD'] == "POST") 
    {
    
     include("config.inc.php");
        if(!$_POST) {
        header("Location: preexport.php");
        exit();
    } 
    
     
        // initialization
        $result_final = "";
        $counter = 0;
    
    // List of our known photo types
        $known_photo_types = array(
                            'image/pjpeg' => 'jpg',
                            'image/jpeg' => 'jpg',
                            'image/gif' => 'gif',
                            'image/bmp' => 'bmp',
                            'image/x-png' => 'png'
                        );
       
    // GD Function List
        $gd_function_suffix = array(
                            'image/pjpeg' => 'JPEG',
                            'image/jpeg' => 'JPEG',
                            'image/gif' => 'GIF',
                            'image/bmp' => 'WBMP',
                            'image/x-png' => 'PNG'
                        );
     
    // Fetch the photo array sent by preexport.php
        $photos_uploaded = $_FILES['photo_filename'];
        $filename[]= $photos_uploaded['name'][$counter];
    	//print_r($photos_uploaded);
      $photo_caption = $_POST['photo_caption'];
    
    // Fetch the photo caption array
        $photo_description = $_POST['photo_description'];
    
    // Fetch the photo caption array
        $photo_keyword = $_POST['photo_keyword'];
         
        while( $counter <count($_FILES['photo_filename']['tmp_name']) ) 
    {
            if($photos_uploaded['size'][$counter] > 0)
            {
                if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types))
                {
                    $result_final .= "File ".($counter+1)." is not a photo<br />";
                }
                else
                {
    			
    			/*print "HHHHHH\n";
    			print "Counter is $counter : ";
    			print $photos_uploaded['name'][0];
    			print $photos_uploaded['name'][1];
    			print "Photo caption is $photo_caption[$counter]"; */
                    mysqli_query(
                        $mysqli,"INSERT INTO
                            gallery_photos (
                        `photo_filename`,
    		    `photo_caption`,
                        `photo_description`,
    		    `photo_keywords`,
                        `category_name`
                        ) VALUES(
    		        '".addslashes($photos_uploaded['name'][$counter])."',
                            '".addslashes($photo_caption[$counter])."',
                            '".addslashes($photo_description[$counter])."',
                            '".addslashes($photo_keyword[$counter])."',
                            '".addslashes($_POST['category'])."')"
                        ) or die(mysqli_error() . 'Photo not uploaded');
                       
                   // $new_id = mysqli_insert_id();
                    $filetype = $photos_uploaded['type'][$counter];
    				
                    $extention = $known_photo_types[$filetype];
                    //$filename = $photo_filename[$counter].".".$extention;
    		//$filename = $new_id.".".$extention;
     
                  //  mysqli_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" );
     
                    // Store the orignal file
    				
                    copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$photos_uploaded['name'][$counter]);
     
                    // Let's get the Thumbnail size
                    $size = GetImageSize( $images_dir."/".$photos_uploaded['name'][$counter] );
                    if($size[0] > $size[1])
                    {
                        $thumbnail_width = 200;
                        $thumbnail_height = (int)(200 * $size[1] / $size[0]);
                    }
                    else
                    {
                        $thumbnail_width = (int)(200 * $size[0] / $size[1]);
                        $thumbnail_height = 200;
                    }
               
                    // Build Thumbnail with GD 1.x.x, you can use the other described methods too
                    $function_suffix = $gd_function_suffix[$filetype];
                    $function_to_read = "ImageCreateFrom".$function_suffix;
                    $function_to_write = "Image".$function_suffix;
     
                    // Read the source file
                    $source_handle = $function_to_read ( $images_dir."/".$photos_uploaded['name'][$counter] );
    				
    				$sharpenMatrix = array
                    (
                        array(-1.2, -1, -1.2),
                        array(-1, 8, -1),
                        array(-1.2, -1, -1.2)
                    );
     
                    // calculate the sharpen divisor
                    $divisor = array_sum(array_map('array_sum', $sharpenMatrix));          
     
                    $offset = 0;
                   
                    if($source_handle)
                    {
                        // Let's create an blank image for the thumbnail
                            $destination_handle = ImageCreateTrueColor ( $thumbnail_width, $thumbnail_height );
                   
                        // Now we resize it
                        ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] );
                    }
     
                    // Let's save the thumbnail
                    $function_to_write( $destination_handle, $images_dir."/tb_".$photos_uploaded['name'][$counter], 100 );
                    ImageDestroy($destination_handle );
                    //
    
               
                   
     
                    $result_final .= "<img src='".$images_dir. "/tb_".$photos_uploaded['name'][$counter]."' /> File ".($counter+1)." Added<br />";
                }
            }
        $counter++;
        }
     
        // Print Result
    echo <<<__HTML_END
     
    <html>
    <head>
        <title>Photos uploaded</title>
    </head>
    <body>
        $result_final
    </body>
    </html>
     
    __HTML_END;
    
    }
    ?>
    

    preexport.php

    <?php
     include 'config.inc.php';
     
      $photo_category_list = '';
     $photo_upload_fields = '';
     $counter = 1;
     
     // If we want more fields, then use, preexport.php?number_of_fields=9
     $number_of_fields = (isset($_GET['number_of_fields'])) ?
       (int)($_GET['number_of_fields']) : 9;
     
     // Firstly Lets build the Category List
     $result = mysqli_query($mysqli,'SELECT category_name FROM gallery_category');
     /*if($result === FALSE) {
        die(mysqli_error()); // TODO: better error handling
    }*/
     while($row = mysqli_fetch_array($result)) {
       $photo_category_list .= <<<__HTML_END
    <option value="$row[0]">$row[0]</option>\n
    __HTML_END;
     }
     mysqli_free_result( $result ); 
     
     // Lets build the Image Uploading fields
     while($counter <= $number_of_fields) {
       $photo_upload_fields .= <<<__HTML_END
    <tr><td>
     Photo {$counter}:
     <input name="photo_filename[]"
    type="file" />
    </td></tr>
    <tr><td>
     Caption:
     <textarea name="photo_caption[]" cols="50"
       rows="1"></textarea>
    </td></tr>
    <tr><td>
     Description:
     <textarea name="photo_description[]" cols="50"
       rows="4"></textarea>
    </td></tr>
    <tr><td>
     Keyword:
     <textarea name="photo_keyword[]" cols="50"
       rows="4"></textarea>
    </td></tr>
    __HTML_END;
       $counter++;
     }
     
     // Final Output
     echo <<<__HTML_END
    <html>
    <head>
    <title> Rajeev lets upload photos!! </title>
    </head>
    <body>
    <form enctype="multipart/form-data"
     action="export.php" method="post"
     name="export_form">
     <table width="90%" border="0"
       align="center" style="width: 90%;">
       <tr><td>
         Select Category
         <select name="category">
         $photo_category_list
         </select>
       </td></tr>
       <!—Insert the image fields here -->
       $photo_upload_fields
       <tr><td>
         <input type="submit" name="submit"
           value="Add Photos" />
       </td></tr>
     </table>
    </form>
    </body>
    </html>
    __HTML_END;
    ?>
    
  2. Copy and paste? Make sure the variables are using the right names.

    requinix, unfortunately copy and pasting did not work for me. Inee to try again. I am a total newbie.

     

     

    Actually, I wonder where you've dug out this addslashes() and mysql_result() stuff. We abandoned that somewhere in the early 2000s together with Netscape Navigator and Java applets.

     

    So whatever book or online tutorial or whatever you're currently using: You'll need a new one which reflects today's technology, not the web as it was back in 2000. Quite a lot has changed since.

     

    Switching to MySQLi is a good start. However, it's not enough to merely append an “i” to the function names and fix some mysql_result() calls. You'll need to unlearn a lot of old nonsense and learn more modern techniques.

    • Printing MySQL error messages directly on the screen may have been acceptable back in the days of personal home pages, but nowadays, people don't want to be greeted with cryptic warnings about your database issues. What are they supposed to do with this information? Debugging is your job, not theirs. In fact, it might not be the best idea to inform the whole world about your server setup and your database structure.
    • addslashes() was never an acceptable way of escaping values. What this incredibly stupid function does is look for some ASCII characters and blindly prepend an ASCII backslash. What if the input is not ASCII? Then you have a problem. Escaping always depends on the character encoding of the input, which is why PHP introduced the mysql_real_escape_string() function back in 2002. The MySQLi equivalent would be mysqli_real_escape_string(). But like KevinM1 already said, a much more secure alternative is to use prepared statements.

     

    A sanitized version of the above code would looks something like this:

    <?php
    
    /*
     * Make MySQLi throw an exception in case on an error. This way we don't have
     * to manually check every single action.
     */
    $mysqli_driver = new mysqli_driver();
    $mysqli_driver->report_mode = MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT;
    
    $database = new mysqli('YOUR_HOST', 'YOUR_USER', 'YOUR_PASSWORD', 'YOUR_DATABASE');
    
    $photos_count_stmt = $database->prepare('
    	SELECT
    		COUNT(*)
    	FROM
    		gallery_photos
    	WHERE
    		category_name = ?
    ');
    $photos_count_stmt->bind_param('s', $category_name);
    $photos_count_stmt->execute();
    
    $photos_count_stmt->bind_result($photos_count);
    $photos_count_stmt->fetch();
    
    // the count is now stored in $photos_acount
    

    Jaques..you are so right about the code being from early 2000 :) It is.. it was from an old tutorial. I now know that I have to learn prepared statements. Thank you for your detailed explanations. Thank you for writing the code.Learning a lot from this single post.

     

    You should use prepared statements, and fetch the results from that. Look at the procedural example in the docs: http://php.net/manual/en/mysqli.prepare.php

    Thank you KevinM1..I will , thank you for the link.

     

     

    I find it easier to add a AS to the COUNT and return it as a normal table column name.  Then you just use normal fetching on the query.

    $total_results = mysqli_query($mysqli,"SELECT COUNT(*) AS `count` FROM gallery_photos WHERE category_name='" . addslashes($category_name) . "'");
    if (!$total_results) {
    die('Could not query:' . mysqli_error());
    }
    $row = mysqli_fetch_assoc($total_results);
    $total_results = $row['count'];
    

    Fastsol...thank you. Your code worked. I need to to see a working example to learn from it. I am not just copying an pasting I promise. Thank you all for answering, you guys know so much. Glad I posted the question here.

  3. Hi Everyone, Sorry I am a complete newbie and am trying to secure my code using MySQLi but I am stuck at mysql_result since there is no equivalent in mysqli. Can someone help me with my code please ?

    $total_results = mysqli_query($mysqli,"SELECT COUNT(*) FROM gallery_photos WHERE category_name='" . addslashes($category_name) . "'");
    if (!$total_results) {
    die('Could not query:' . mysqli_error());
    }
    $total_results = mysql_result($total_results, 0);
    

    When I use this I am getting an error

     

    Warning: mysql_result() expects parameter 1 to be resource, object given in C:\wamp\www\viewgallery.php on line 182

     

    As a solution  I was told to use

    $row = $mysqli_result->fetch_row();
    $the_count = $row[0];  
    

    But I do not know how to add this to my code to make it work. I am sorry if this is too elementary ...

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.