Jump to content

Bottyz

Members
  • Posts

    107
  • Joined

  • Last visited

Posts posted by Bottyz

  1. You  are getting that notice because there is not a array index 3 in $alloweddomains. This is because your for loop is most likely iterating one too many times, due to you adding one to $domains in the condition. 

    If  $alloweddomains is an array, then use a foreach loop instead

    // loop over each allowed domain
    foreach($alloweddomains as $domain) {
    	if((stristr($_SERVER['HTTP_REFERER'], $domain))) {
    		$allowed = 1;
    	}
    } 
    

    You are getting that notice because $contents is an empty string. What type of value should $contents be?

     

    Thanks for your detailed answer, I've replaced my code with the above and its no longer causing an error and the download still works so I'm assuming it works as intended :)

     

    With regards to the unicode_replace_entities function. This is being passed a user inputted message from a message box on a contact form on the website. Its called as follows:

    function previous_request_value($str) {
    	if (isset($_REQUEST[$str]) )
    		return $_REQUEST[$str];
    	else
    		return '';
    	}
    
    $message_body = trim(previous_request_value('message_body'));
    $message_body=nl2br(htmlspecialchars(stripslashes($message_body), ENT_QUOTES, 'UTF-8'));
    $oUnicodeReplace = new unicode_replace_entities();
    $message_body = $oUnicodeReplace->UTF8entities($message_body);
    

    Then the full class for unicode_replace_entities is:

    class unicode_replace_entities {
    	public function UTF8entities($content="") {
    		$contents = $this->unicode_string_to_array($content);
    		$swap = "";
    		$iCount = count($contents);
    		for ($o=0;$o<$iCount;$o++) {
    		      $contents[$o] = $this->unicode_entity_replace($contents[$o]);
    		      $swap .= $contents[$o];
    		}
    		return mb_convert_encoding($swap,"UTF-8"); //not really necessary, but why not.
    	}
    
    	public function unicode_string_to_array( $string ) { //adjwilli
    		$strlen = mb_strlen($string);
    		$array = "";
    		while ($strlen) {
    		      $array[] = mb_substr( $string, 0, 1, "UTF-8" );
    		      $string = mb_substr( $string, 1, $strlen, "UTF-8" );
    		      $strlen = mb_strlen( $string );
    		}
    		return $array;
    	}
    	
    	public function unicode_entity_replace($c) { //m. perez
    		$h = ord($c{0});   
    		if ($h <= 0x7F) {
    		        return $c;
    		} else if ($h < 0xC2) {
    		        return $c;
    		}
               
    		if ($h <= 0xDF) {
    			$h = ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
    		        $h = "" . $h . ";";
    			return $h;
    		} else if ($h <= 0xEF) {
    			$h = ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);
    			$h = "" . $h . ";";
    			return $h;
    		} else if ($h <= 0xF4) {
    			$h = ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);
    			$h = "" . $h . ";";
    			return $h;
    		}
            }
    }
    

    As you can tell some of this is not my code, and I can't confess to fully understanding all of it.

  2. For a start the session_start needs to go above everything else.

    The blank page would normally mean you've missing a semi colon or similar (best to check error logs for specifics) my guess would be the missing semi-colon from:

    mail($to, $subject, $message, $headers)

    should be:

    mail($to, $subject, $message, $headers);
  3. Just a thought, have you added 

    <?php session_start(); ?>

    at the beginning of your email.php?

     

    You'll also want to keep the user on that page for a few seconds before redirecting to index.html as you'll want them to see the notice you've written, so add

    header ("refresh: 5; url=index.html");

     instead of 

    header("Location: index.html");
  4. Oh and I'm also getting a very similar PHP notice for the below, again I think the culprit is the $o variable.

    		class unicode_replace_entities {
    		    public function UTF8entities($content="") {
    		        $contents = $this->unicode_string_to_array($content);
    		        $swap = "";
    		        $iCount = count($contents);
    		        for ($o=0;$o<$iCount;$o++) {
    		            $contents[$o] = $this->unicode_entity_replace($contents[$o]);
    		           $swap .= $contents[$o];
    			    }
    			    return mb_convert_encoding($swap,"UTF-8"); //not really necessary, but why not.
    			}
    

    This time the notice is: [28-Jul-2015 06:44:41 America/New_York] PHP Notice:  Uninitialized string offset: 0 in /public_html/contactform.php on line 108

     

     

    Pulling what little hair I have left out over these!

     

    Thanks :)

  5. $domains = count($alloweddomains);
    for($y=0;$y<$domains+1;$y++) {
    	if((stristr($_SERVER['HTTP_REFERER'], $alloweddomains[$y]))) {
    		$allowed = 1;
    	}
    } 

    Hi all,

     

    Probably a really easy one for you to solve, but I'm a little stumped. I've recently upgraded to php 5.4 and have started getting a few php notices and I'm going through them one by one, but I'm stuck fixing the following:

     

    [29-Jul-2015 06:54:21 America/New_York] PHP Notice:  Undefined offset: 3 in /public_html/filedownload.php on line 25

     

    I've attached the code and I believe its referring to the $y variable.

     

     

     

    Any ideas or assistance is always appreciated.

  6. I'll post some of the code below, but I'm not 100% sure how it all works as JSON is involved (Which i'm only just getting familiar with), so please bear with me.

     

    upload.html - client side where file upload is requested and form where title is entered by users.

     

    <form id="fileupload" action="server/php/" method="POST" enctype="multipart/form-data">
    
    <!-- The template to display files available for upload -->
    <script id="template-upload" type="text/x-tmpl">
    {% for (var i=0, file; file=o.files[i]; i++) { %}
        <tr class="template-upload fade">
            <td class="preview"><span class="fade"></span></td>
            <td class="name"><span>{%=file.name%}</span></td>
            <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
    
    // my additional code here:
    	<td class="caption"><label>Photo Title: <input name="title[]" required></label></td>
            {% if (file.error) { %}
                <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
    
    // end of my code
            {% } else if (o.files.valid && !i) { %}
                <td>
                    <div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="bar" style="width:0%;"></div></div>
                </td>
                <td class="start">{% if (!o.options.autoUpload) { %}
                    <button class="btn btn-primary">
                        <i class="icon-upload icon-white"></i>
                        <span>{%=locale.fileupload.start%}</span>
                    </button>
                {% } %}</td>
            {% } else { %}
                <td colspan="2"></td>
            {% } %}
            <td class="cancel">{% if (!i) { %}
                <button class="btn btn-warning">
                    <i class="icon-ban-circle icon-white"></i>
                    <span>{%=locale.fileupload.cancel%}</span>
                </button>
            {% } %}</td>
        </tr>
    {% } %}
    </script>
    

     

    server/php/index.php - called by the form submission above (not sure if you need to see this part but thought it may help)

     

    
    session_start();
    error_reporting(E_ALL | E_STRICT);
    require('upload.class.php');
    
    $upload_handler = new UploadHandler();
    
    header('Pragma: no-cache');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Content-Disposition: inline; filename="files.json"');
    header('X-Content-Type-Options: nosniff');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE');
    header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');
    
    switch ($_SERVER['REQUEST_METHOD']) {
        case 'OPTIONS':
            break;
        case 'HEAD':
        case 'GET':
            $upload_handler->get();
            break;
        case 'POST':
            if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
                $upload_handler->delete();
            } else {
                $upload_handler->post();
            }
            break;
        case 'DELETE':
            $upload_handler->delete();
            break;
        default:
            header('HTTP/1.1 405 Method Not Allowed');
    }
    
    

     

    server/phpupload.class.php - Stores the classes which are probably causing the issue. I've tried to crop out most of the non relevant code. I've marked my edited code so you can see what I've changed as originally this script had no sort of mysql connection.

     

    class UploadHandler
    {
        protected $options;
    
        function __construct($options=null) {
            $this->options = array(
                'script_url' => $this->getFullUrl().'/',
                'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/img/',
                'upload_url' => $this->getFullUrl().'/img/',
                'param_name' => 'files',
                // Set the following option to 'POST', if your server does not support
                // DELETE requests. This is a parameter sent to the client:
                'delete_type' => 'DELETE',
                // The php.ini settings upload_max_filesize and post_max_size
                // take precedence over the following max_file_size setting:
                'max_file_size' => null,
                'min_file_size' => 1,
                'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
                // The maximum number of files for the upload directory:
                'max_number_of_files' => null,
                // Image resolution restrictions:
                'max_width' => null,
                'max_height' => null,
                'min_width' => 1,
                'min_height' => 1,
                // Set the following option to false to enable resumable uploads:
                'discard_aborted_uploads' => true,
                // Set to true to rotate images based on EXIF meta data, if available:
                'orient_image' => true,
                'image_versions' => array(
                    // Uncomment the following version to restrict the size of
                    // uploaded images. You can also add additional versions with
                    // their own upload directories:
                    'large' => array(
                        'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/img/',
                        'upload_url' => $this->getFullUrl().'/img/',
                        'max_width' => 1920,
                        'max_height' => 1200,
                        'jpeg_quality' => 95
                    ),
                    'thumbnail' => array(
                        'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/thumbs/',
                        'upload_url' => $this->getFullUrl().'/thumbs/',
                        'max_width' => 75,
                        'max_height' => 75
                    )
                )
            );
            if ($options) {
                $this->options = array_replace_recursive($this->options, $options);
            }
        }
    
        protected function getFullUrl() {
            $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
          	return
        		($https ? 'https://' : 'http://').
        		(!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
        		(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
        		($https && $_SERVER['SERVER_PORT'] === 443 ||
        		$_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
        		substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
        }
    
        protected function get_file_object($file_name) {
            $file_path = $this->options['upload_dir'].$file_name;
            if (is_file($file_path) && $file_name[0] !== '.') {
                $file = new stdClass();
                $file->name = $file_name;
                $file->size = filesize($file_path);
                $file->url = $this->options['upload_url'].rawurlencode($file->name);
                foreach($this->options['image_versions'] as $version => $options) {
                    if (is_file($options['upload_dir'].$file_name)) {
                        $file->{$version.'_url'} = $options['upload_url']
                            .rawurlencode($file->name);
                    }
                }
                $this->set_file_delete_url($file);
                return $file;
            }
            return null;
        }
    
        protected function get_file_objects() {
            return array_values(array_filter(array_map(
                array($this, 'get_file_object'),
                scandir($this->options['upload_dir'])
            )));
        }
    
        protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, $title) {
    
    //My code:
    	// connect to db to retrieve next file number
    	include('../../../../../db/gallerypass.php');
    
    	$idstmt = $mysqli->stmt_init();
    	if ($idstmt = $mysqli->prepare("SELECT max(id) FROM gallery")){
    		$idstmt->execute();
    		$idstmt->bind_result($idnum);
    		$idstmt->fetch();
    		$idstmt->close();
    	}
    	// if query errors sends an email
    	if ($mysqli->error) {
    		try {   
    			throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $mysqli->errno);   
    		} catch(Exception $e ) {
    			$mess = "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br>";
    			$mess .= nl2br($e->getTraceAsString());
    			$contact_email = "user@user.com";
    			$message_sub = "Mysqli Query Error [uPFAIL]";
    			$hdrs = "From: " . $contact_email . "\r\n";
    			$hdrs .= "Reply-To: ". $contact_email . "\r\n";
    			$hdrs .= "MIME-Version: 1.0\r\n";
    			$hdrs .= "Content-Type: text/html; charset=UTF-8\r\n";
    			mail($contact_email, $message_sub, $mess, $hdrs);
    		}
    		header("location: http://website.co.uk/");
    		exit();
    	}
    	$mysqli->close();
    
    	$ext = strtolower(substr(strrchr($name, '.'), 1));
    	if ($ext == 'jpg') {
    		$ext = 'jpeg';
    	}
    	$idnum++;
    	$name = $idnum . '.' . $ext;
    // End My Code
    
            $file = new stdClass();
            $file->name = $this->trim_file_name($idnum, $type, $index);
            $file->size = intval($size);
            $file->type = $type;
            if ($this->validate($uploaded_file, $file, $error, $index)) {
                $this->handle_form_data($file, $index);
                $file_path = $this->options['upload_dir'].$file->name;
                $append_file = !$this->options['discard_aborted_uploads'] &&
                    is_file($file_path) && $file->size > filesize($file_path);
                clearstatcache();
                if ($uploaded_file && is_uploaded_file($uploaded_file)) {
                    // multipart/formdata uploads (POST method uploads)
                    if ($append_file) {
                        file_put_contents(
                            $file_path,
                            fopen($uploaded_file, 'r'),
                            FILE_APPEND
                        );
                    } else {
                        move_uploaded_file($uploaded_file, $file_path);
                    }
                } else {
                    // Non-multipart uploads (PUT method support)
                    file_put_contents(
                        $file_path,
                        fopen('php://input', 'r'),
                        $append_file ? FILE_APPEND : 0
                    );
                }
                $file_size = filesize($file_path);
                if ($file_size === $file->size) {
                	if ($this->options['orient_image']) {
                		$this->orient_image($file_path);
                	}
                    $file->url = $this->options['upload_url'].rawurlencode($file->name);
                    foreach($this->options['image_versions'] as $version => $options) {
                        if ($this->create_scaled_image($file->name, $options)) {
                            if ($this->options['upload_dir'] !== $options['upload_dir']) {
                                $file->{$version.'_url'} = $options['upload_url']
                                    .rawurlencode($file->name);
                            } else {
                                clearstatcache();
                                $file_size = filesize($file_path);
                            }
                        }
                    }
                } else if ($this->options['discard_aborted_uploads']) {
                    unlink($file_path);
                    $file->error = 'abort';
                }
                $file->size = $file_size;
                $this->set_file_delete_url($file);
            }
    // My Code:
    	// connect to db to record file name & caption
    	include('../../../../../db/gallerypass.php');
    
    	$null = NULL;
    	$address = $_SERVER['REMOTE_ADDR'];
    	$recordimgstmt = $mysqli->stmt_init();
    	if ($recordimgstmt->prepare("INSERT INTO gallery VALUES (?, ?, ?, ?)")) {
    		$recordimgstmt->bind_param('isss', $null, $name, $title, $address);
    		$recordimgstmt->execute();
    		$recordimgstmt->close();
    	}
    	// if query errors sends an email
    	if ($mysqli->error) {
    		try {   
    			throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $mysqli->errno);   
    		} catch(Exception $e ) {
    			$mess = "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br>";
    			$mess .= nl2br($e->getTraceAsString());
    			$contact_email = "user@user.com";
    			$message_sub = "Mysqli Query Error [uAIMGDB]";
    			$hdrs = "From: " . $contact_email . "\r\n";
    			$hdrs .= "Reply-To: ". $contact_email . "\r\n";
    			$hdrs .= "MIME-Version: 1.0\r\n";
    			$hdrs .= "Content-Type: text/html; charset=UTF-8\r\n";
    			mail($contact_email, $message_sub, $mess, $hdrs);
    		}
    		exit();
    	}
    	$mysqli->close();
    // End My Code
    
            return $file;
        }
    
        public function get() {
            $file_name = isset($_REQUEST['file']) ?
                basename(stripslashes($_REQUEST['file'])) : null;
            if ($file_name) {
                $info = $this->get_file_object($file_name);
            } else {
                $info = $this->get_file_objects();
            }
            header('Content-type: application/json');
            echo json_encode($info);
        }
    
        public function post() {
            if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
                return $this->delete();
            }
            $upload = isset($_FILES[$this->options['param_name']]) ?
                $_FILES[$this->options['param_name']] : null;
            $info = array();
            if ($upload && is_array($upload['tmp_name'])) {
                // param_name is an array identifier like "files[]",
                // $_FILES is a multi-dimensional array:
                foreach ($upload['tmp_name'] as $index => $value) {
                    $info[] = $this->handle_file_upload(
                        $upload['tmp_name'][$index],
                        isset($_SERVER['HTTP_X_FILE_NAME']) ?
                            $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
                        isset($_SERVER['HTTP_X_FILE_SIZE']) ?
                            $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
                        isset($_SERVER['HTTP_X_FILE_TYPE']) ?
                            $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
                        $upload['error'][$index],
    // My code to pass the input title
    	$_REQUEST['title']
    // end of my code
                    );
                }
            } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
                // param_name is a single object identifier like "file",
                // $_FILES is a one-dimensional array:
                $info[] = $this->handle_file_upload(
                    isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
                    isset($_SERVER['HTTP_X_FILE_NAME']) ?
                        $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ?
                            $upload['name'] : null),
                    isset($_SERVER['HTTP_X_FILE_SIZE']) ?
                        $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ?
                            $upload['size'] : null),
                    isset($_SERVER['HTTP_X_FILE_TYPE']) ?
                        $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ?
                            $upload['type'] : null),
                    isset($upload['error']) ? $upload['error'] : null
                );
            }
            header('Vary: Accept');
            $json = json_encode($info);
            $redirect = isset($_REQUEST['redirect']) ?
                stripslashes($_REQUEST['redirect']) : null;
            if ($redirect) {
                header('Location: '.sprintf($redirect, rawurlencode($json)));
                return;
            }
            if (isset($_SERVER['HTTP_ACCEPT']) &&
                (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
                header('Content-type: application/json');
            } else {
                header('Content-type: text/plain');
            }
            echo $json;
        }
    
    
    
    }
    
    

     

    I also edited the main javascript file:

     

    $('#fileupload').bind('fileuploadsubmit', function (e, data) {
    	var inputs = data.context.find(':input');
    	if (inputs.filter('[required][value=""]').first().focus().length) {
    		return false;
    	}
    	data.formData = inputs.serializeArray();
    });
    

     

     

    As you can see from above I thought that js may be serializing the data so I did try to use unserialize() around the title variable but this didn't change anything either.

     

    Anyone with a better understanding able to help? I'd very much appreciate it.

     

     

  7. hi all,

     

    i'm attempting to use the file upload script by blueimp: https://github.com/blueimp/jQuery-File-Upload in order to upload and store images for an image gallery. I've added a mysql script to store a title for each image to retrieve when showing them in the gallery.

     

    now my problem is that when I try to store the title all it stores (when looking through phpmyadmin) is the word 'array'. I've tried a few variations of trying to extract the information such as var_dump or printr and all I seem to manage to get out of it is string(5). I'm not great with my knowledge on arrays so if someone can offer any ideas on how to extract the title, that would be great, thanks!

  8. Hi all,

     

    I have a database which contains customer details. We have a php script which pulls the records from the database and puts them into a table on the page. Currently, it fetches all the customer records. This wasn't such a problem when there was only a few customers in the db but this is a bit higher now! Is there any way I can modify the script to only show 20 per page and add links to page 2 etc along the bottom, which can be clicked to show the next 20 and so on?

     

    I can post my current code if need be, Thanks.

  9. multi_query and prepared statements are not compatible.... prepared statement MUST consist of only a single SQL statement..  as stated on the manual

     

    http://www.php.net/manual/en/mysqli.prepare.php

     

    Hi mikosiko,

     

    I figured that one out only a couple of days ago when sifting through the php manual. I forgot to update everyone here. But thanks for the confirmation! I just call each myslqi with a new connection using a pre-set dbconnect file.

     

     

  10. if your trying to get to a client machine then PHP doesn't strike me as the best option to take, I'd look at JAVAScript or AJAX options for the big files, and use <object> containers in the HTML for the likes of PDF Files, which will allow the users to download the files or view them live using existing commercial plugins.

     

    The problem is that all of the files are stored outside of the www root. We don't want the software etc to be downloaded without the right permissions, and we don't want the url openly available. I don't think I can do that with <object> containers. I've never used AJAX, but that is a type of javascript isn't it? So would it fall foul of people that don't have javascript enabled browsers? If not, I'll certainly have a closer look.

     

    Thanks for you comments thus far.

  11. If you're just trying to get a file from a remote server onto your PHP webserver, I would go with ftp if you can.

     

    Hi muddy,

     

    No, I use cURL for that. This is a download script in a login area for some of our customers. The script is for software zip files mainly, but the occassion pdf is used. I think it has to be something wrong with the connection to the website. The files need to be secured so that they can't be stolen.

     

    Is there anything else I can use to stop the connection dropping or anything other than php that is reliable and easy to use as an alternative?

  12. Hi all,

     

    Guessing no one can help with the problem? Or suggest any ideas?

     

    Anyways, I'm not sure if it is a problem with php but rather a problem with the setup of the host server? I just tried implementing the following code with the exact same results:

     

    /* Execution Time Unlimited */
    	set_time_limit(0);
    
    	/*
    	|----------------
    	| Header
    	| Forcing a download using readfile()
    	|----------------
    	*/
    
    	header('Content-Description: File Transfer');
    	header('Content-Type: ' . $file_mime_type);
    	header('Content-Disposition: attachment; filename=' . $file);
    	header('Content-Transfer-Encoding: binary');
    	header('Expires: 0');
    	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    	header('Pragma: public');
    	header('Content-Length: ' . $file_size);
    	ob_clean();
    	flush();
    	readfile($file_path);
    	exit;
    

     

    I'm running out of options now, and not sure what else to pursue. Does anyone have any alternatives they could suggest? Thank you.

  13. Hi all,

     

    I've tried many, many variations of php download script using readfile() fread() fpassthru() etc... but none seem reliable. I can download small files perfectly fine, but say I have a 30 or 90mb zip file the download ocassionally bombs out and says the download is complete even though the full file hasn't been transferred.

    I have tired it on several browsers with pretty much the same issue. The interesting bit for me is that if I download the same file across different browsers (whether or not they start at the same time or not) on my computer the download stops at the same time (not same point into download) for each browser.  Its as if the connection is being reset on my website on a global basis...

     

    The important part of my script as it is at the moment:

     

    // resumable download?
    $is_resume = TRUE;
    
    //Gather relevant info about file
    $size = filesize($path);
    $fileinfo = pathinfo($path);
    
    @ini_set('magic_quotes_runtime', 0);
    set_time_limit(0);
    apache_setenv('no-gzip', '1');
    mb_http_output("pass");
    
    // required for IE, otherwise Content-disposition is ignored
    if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
    	  
    //workaround for IE filename bug with multiple periods / multiple dots in filename
    //that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
    $filename = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ?
    preg_replace('/\./', '%2e', $fileinfo['basename'], substr_count($fileinfo['basename'], '.') - 1) :
    $fileinfo['basename'];
    
    $file_extension = strtolower($fileinfo['extension']);
    
        //This will set the Content-Type to the appropriate setting for the file
        switch($file_extension) {
            case 'zip': $ctype='application/zip'; break;
            case 'pdf': $ctype='application/pdf'; break;
            default:    $ctype='application/force-download';
        }
    
        //check if http_range is sent by browser (or download manager)
        if($is_resume && isset($_SERVER['HTTP_RANGE'])) {
            list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);
            if ($size_unit == 'bytes') {
                //multiple ranges could be specified at the same time, but for simplicity only serve the first range
                //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
                list($range, $extra_ranges) = explode(',', $range_orig, 2);
            } else {
                $range = '';
            }
        } else {
            $range = '';
        }
    
        //figure out download piece from range (if set)
        list($seek_start, $seek_end) = explode('-', $range, 2);
    
        //set start and end based on range (if set), else set defaults
        //also check for invalid ranges.
        $seek_end = (empty($seek_end)) ? ($size - 1) : min(abs(intval($seek_end)),($size - 1));
        $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);
    
        //add headers if resumable
        if ($is_resume) {
            //Only send partial content header if downloading a piece of the file (IE workaround)
            if ($seek_start > 0 || $seek_end < ($size - 1)) {
                header('HTTP/1.1 206 Partial Content');
            }
    	header('Accept-Ranges: bytes');
            header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size);
        }
    
        header("Cache-Control: cache, must-revalidate");  
        header("Pragma: public");
        header('Content-Type: ' . $ctype);
        header("Content-Disposition: attachment; filename=\"".$filename."\"");
        header('Content-Length: '.($seek_end - $seek_start + 1));
    
        //open the file
        $fp = fopen($path, 'rb');
        //seek to start of missing part
        fseek($fp, $seek_start);
    
        //start buffered download
        while(!feof($fp)) {
            //reset time limit for big files
            set_time_limit(0);
            print(fread($fp, 1024*);
            flush();
            ob_flush();
        }
        fclose($fp);
    exit();
    

     

    I did have the following section in replace of the above fread section up until this morning (but same issue):

     

    // http headers for zip downloads
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$filename."\"");
    header("Content-Transfer-Encoding: binary");
    header('Content-Length: '.$size);
    ob_end_flush();
    @readfile($path);
    

     

    I have tried different headers and so forth, but all generally seem to bomb out occassionally before the download completes. But they don't bomb out at a particular point in the file size (ie at 25mb). Just seems to work and then die at the same time across different browsers, even when they are started at different times.

     

    Very strange and I've spent days modifying the script and still no answers. Sometimes the files download fine, but bomb out too many times for it to be satifactory to leave.

     

    Any help or pointers would be much appreciated.

  14. Hi all,

     

    I would like to perform two queries in a mysqli statement before closing the connection. I'm using prepared statements and I've read on the php.net you can perform a multi-query using mysqli->multi_query.

    My problem is that I'm only finding useful examples on how to select and fetch results not using prepared statements. I'm a bit lost with how to do this to update two tables. Currently i'm using two seperate connections to do the queries but want to combine these together:

     

    Query one (updates their password and resets number of logins to force password change on next login):

     

                    //reset logins to force the user to change password upon next login
    	$loggedin = '0';
    
    	// connect to db for mysqli
    	require('../db/db.php');
    
    	// updates password and number of logins
    	$insert_stmt = $mysqli->stmt_init();
    	if ($insert_stmt->prepare("UPDATE users SET their_password=?, loggedin=? WHERE their_username=?")) {
    		$insert_stmt->bind_param('sss', $their_password, $time, $user_email);
    		$insert_stmt->execute();
    		$insert_stmt->close();
    	}
    	// if query errors sends an email
    	if ($mysqli->error) {
    		try {   
    			throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $mysqli->errno);   
    		} catch(Exception $e ) {
    			$mess = "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
    			$mess .= nl2br($e->getTraceAsString());
    			$contact_email = "webmaster@website.com";
    			$message_sub = "Mysqli Forgotten Password Query Error [uPASSWORD01]";
    			$hdrs = "From: " . $contact_email . "\r\n";
    			$hdrs .= "Reply-To: ". $contact_email . "\r\n";
    			$hdrs .= "MIME-Version: 1.0\r\n";
    			$hdrs .= "Content-Type: text/html; charset=UTF-8\r\n";
    			mail($contact_email, $message_sub, $mess, $hdrs);
    		}
    		header("refresh: 10; forgotpass.php");
    		die('ERROR: Unable to reset password. Please check you details and try again or report this error to us using our contact us form.<br><br>We will redirect you back to the forgotten password form in 10 seconds.');
    		exit();
    	}		
    	$mysqli->close();
    

     

    Query two (updates a reset log - to keep track on our user password resets):

     

    // change status
    		$resetstatus = "Successful Reset";
    
    		// connect to db for mysqli
    		require('../db/db.php');
    
    		// inserts a new record
    		$null = NULL;
    		$insert_stmt = $mysqli->stmt_init();
    		if ($insert_stmt->prepare("INSERT INTO passwordresets VALUES (?, ?, ?, ?, ?)")) {
    			$insert_stmt->bind_param('issss', $null, $user_email, $time, $userip, $resetstatus);
    			$insert_stmt->execute();
    			$insert_stmt->close();
    		}
    
    		// if query errors sends an email
    		if ($mysqli->error) {
    			try {   
    				throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $mysqli->errno);   
    			} catch(Exception $e ) {
    				$mess = "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
    				$mess .= nl2br($e->getTraceAsString());
    				$contact_email = "webmaster@website.com";
    				$message_sub = "Mysqli Forgotten Password Query Error [uARESETLOG01]";
    				$hdrs = "From: " . $contact_email . "\r\n";
    				$hdrs .= "Reply-To: ". $contact_email . "\r\n";
    				$hdrs .= "MIME-Version: 1.0\r\n";
    				$hdrs .= "Content-Type: text/html; charset=UTF-8\r\n";
    				mail($contact_email, $message_sub, $mess, $hdrs);
    			}
    			header("refresh: 10; forgotpass.php");
    			die('ERROR: Unable to reset password. Please check you details and try again or report this error to us using our contact us form.<br><br>We will redirect you back to the forgotten password form in 10 seconds.');
    			exit();
    		}		
    		$mysqli->close();
    

     

    Any ideas would be greatly appreciated. Thank you

  15. Hi all,

     

    I've just started upgrading from procedural style mysql statements to object orientated style mysqli prepared statements. I was just hoping someone could look over my registration page statement code and tell me if there are any bits that are unecessary or a security issue (All of the code does already work - just want it checking) :P

     

    The reason I would like them checked over is because I've never touched OOP or mysqli in my life as I haven't been doing php all that long. I've had my own mysql statements running great for a couple of years but I want to keep with the times! If they are ok, then I'll go on to convert the remainder of the site :)

     

    First of all I include the mysqli database connection script before each mysqli statements (as php auto drops the connection once the script has finished - a little annoying as it increases the code. But I can see the resources advantages.  ::)):

     

    ../db/dbauth.php (outsite www root):

    	$mysqli = new mysqli($hostname_lh, $username_lh, $password_lh, $database_lh);
    
    	if (mysqli_connect_errno()) {
    		$mess = "There was a mysqli connection error! Mysqli Error: " . mysqli_connect_error();
    		$contact_email = "webmaster@website.com";
    		$message_sub = "Mysqli Connection Error";
    		$hdrs = "From: " . $contact_email . "\r\n";
    		$hdrs .= "Reply-To: ". $contact_email . "\r\n";
    		$hdrs .= "MIME-Version: 1.0\r\n";
    		$hdrs .= "Content-Type: text/html; charset=UTF-8\r\n";
    		mail($contact_email, $message_sub, $mess, $hdrs);
    		exit();
    	}
    

     

    The above will send an email if there are any connection problems. This file has to be called before each mysqli statement... is there an easier way of doing this? I don't want to have it in my file as it contains the password/database details. Do I have to include the file each time I use mysqli in a file as I have been doing? Some files contain upto 4-5 mysqli statements, so i'm effectively including the dbauth.php file 4-5 times.

     

    Anyways to the statements:

     

    First prepared statement is for populating a countries drop down box:

    // connect to db for mysqli
    require_once('../db/dbauth.php');
    
    // populates countries drop down
    $countrystmt = $mysqli->stmt_init();
    if ($countrystmt = $mysqli->prepare("SELECT country FROM countries")){
    $countrystmt->execute();
    $countrystmt->bind_result($option);
    while ($countrystmt->fetch()) {
    	// records stored in $option
    	echo "<option value='" . $option . "'";
    	if ($user_country == $option) {
    		echo " selected";
    	}
    	echo ">" . $option . "</option>";
    }
    $countrystmt->close();
    }
    $mysqli->close();
    

     

    This one checks the db to see if the user already exists:

    	// connect to db for mysqli
    	require_once('../db/dbauth.php');
    
    	// checks if the username is in use
    	$result = $mysqli->stmt_init();
    	if ($result->prepare("SELECT their_username FROM users WHERE their_username=?")){
    		$result->bind_param("s", $their_username);
    		$result->execute();
    		$result->store_result();
    		$row_count = $result->num_rows;
    		$result->close();
    	}
    	// if query errors sends an email
    	$mysqli->close();		
    
    	// if the name exists it gives an error
    	if ($row_count != NULL) { //..... .... .... 
    

     

     

    next one inserts a new user into the db (after some santitising of inputs):

    	// connect to db for mysqli
    	require_once('../db/dbauth.php');
    
    	// inserts a new user
    	$null = NULL;
    	$insert_stmt = $mysqli->stmt_init();
    	if ($insert_stmt->prepare("INSERT INTO members VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
    		$insert_stmt->bind_param('issssssssssssiiiiisiis', $null, $user_name, $user_companyname, $user_email, $user_1stline, $user_address2, $user_town, $user_county, $user_postcode, $user_country, $user_tel, $their_username, $null, $zero, $zero, $zero, $zero, $zero, $user_serial, $zero, $zero, $zero);
    		$insert_stmt->execute();
    		$insert_stmt->close();
    	}
    
    	// if query errors sends an email
    	if ($mysqli->error) {
    		try {   
    			throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $mysqli->errno);   
    		} catch(Exception $e ) {
    			$mess = "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
    			$mess .= nl2br($e->getTraceAsString());
    			$contact_email = "webmaster@website.com";
    			$message_sub = "Mysqli Registration Query Error [uAU01]";
    			$hdrs = "From: " . $contact_email . "\r\n";
    			$hdrs .= "Reply-To: ". $contact_email . "\r\n";
    			$hdrs .= "MIME-Version: 1.0\r\n";
    			$hdrs .= "Content-Type: text/html; charset=UTF-8\r\n";
    			mail($contact_email, $message_sub, $mess, $hdrs);
    		}
    		header("refresh: 10; registration.php");
    		die('ERROR: Unable to add you as a new user. Please report this error to us using our contact us form.<br><br>We will redirect you back to the registration form in 10 seconds.<br><br><div style="margin: auto; text-align: center;"><img src="http://static.website.com/images/loading.gif" alt="loading"></div>');
    		exit();
    	}		
    	$mysqli->close();
    

     

    If the script above errors then it will send an error email to the webmaster (me) and also give a friendly error to the user before redirecting back to a registration page.

     

    I've got a similar error and refresh method for the other statements further up, but didn't think I should overload everyone with loads of similar code!  ;)

     

    Anyways,  muchos help always appreciated!!! :) :)

     

     

  16. Hi all,

     

    I'm currently rewriting our contact us form using the php Pear Mail package. It allows both html based emails and text based emails, and displays the relevant version based on the end recipients broswer capabilities.

     

    I have the html version working perfect, however the text based version spits out the whole message without line breaks. Since some of the computers in our building only except text emails (due to security) it needs to be laid out so that it is legible. I've searched around and tried various options but the emails are still arriving without breaks.

     

    So as an example:

     

    A User Inputs the following message using a textarea on the php form:

     

    Hi there,

     

    Great website, need help with such and such though.

     

    Regards

     

    Bob

     

     

    The email message gets collected and included in a html message. Then a duplicate text based message is made like so (Code so far):

     

    	$plaintxt = '-----------------------------------------' . "\n";
    	$plaintxt .= Website Enquiry' . "\n";
    	$plaintxt .= '-----------------------------------------' . "\n";
    	$plaintxt .= 'A visitor to our website has submitted the following enquiry:' . "\n\n";
    	$plaintxt .= 'Name: ' . $visitor_name . "\n";
    	$plaintxt .= 'Company Name: ' . $visitor_companyname . "\n";
    	$plaintxt .= 'Email Address: ' .  $visitor_email . "\n";
    	$plaintxt .= 'Telephone Number: ' . $message_telephone . "\n\n";
    	$plaintxt .= 'Subject of Enquiry: ' . $msg_subject . "\n";
    	$plaintxt .= 'Enquiry: ' . "\n\n";
    	$plaintxt .= $message_body . "\n\n";
    	$plaintxt .= '-----------------------------------------' . "\n\n";
    	$plaintxt .= 'User IP Address:' . $ip . "\n";
    	$plaintxt .= 'User Browser Info:' . $httpagent . "\n";
    	$plaintxt .= 'Date/Time Submitted:' . $time . "\n";
    
    	$crlf = "\n"; 
    	$headers = array('From' => $contact_from_email, 'Return-Path' => $contact_from, 'Subject' => $subject, 'To' => $contact_to);
           
    	// Creating the Mime message
    	$mime = new Mail_mime($crlf);
           
    	// Setting the body of the email
    	$mime->setTXTBody($htmlmessage); //Text version of the email
    	$mime->setHTMLBody($plaintxt); // HTML version of the email
    

     

    "\n"; - These were suggested by users on the pear mail manual.

     

    Then once sent and opened you'd expect to see:

     

    -----------------------------------------

    Website Enquiry

    -----------------------------------------

    A visitor to our website has submitted the following enquiry:

    Name: Bob

    Company Name: Someplace Ltd

    Email Address: bob@someplace.com

    Telephone Number: 01234 567890

    Subject of Enquiry: help

    Enquiry:

     

    Hi there,

     

    Great website, need help with such and such though.

     

    Regards

     

                    Bob

     

    -----------------------------------------

    User IP Address: 123.456.789.012

    User Browser Info: Mozilla

    Date/Time Submitted: 29th September 2011 09:56

     

    However when opened in all the email applications I have (Outlook, Gmail, Live Mail, Hotmail, Yahoo) it looks like this:

     

    -----------------------------------------Website Enquiry-----------------------------------------A visitor to our website has submitted the following enquiry:Name: BobCompany Name: Someplace LtdEmail Address: bob@someplace.comTelephone Number: 01234 567890Subject of Enquiry: helpEnquiry: Hi there,Great website, need help with such and such though.RegardsBob-----------------------------------------User IP Address: 123.456.789.012User Browser Info: MozillaDate/Time Submitted: 29th September 2011 09:56

     

    Yet if you look at the source of the email. The line breaks are there. Am I missing something?

     

  17.  

    I had a similar issue with htmlentities the other day, and xyph gave me some good pointer here.

     

    The doctype must be correct, the content-type and also htmlentitieshas a second parameter that can be set to which i never knew about which determines its character set.

     

    Hi Freelance,

     

    Thanks for the pointer... I think it was something to do with the UTF8 encoding. I searched for a while on the php net site. And Found a very good function which is good at converting all special characters to their &#number; entities. It works great for the script, I've in cluded it below i case anyone else would like to use it:

     

    
    //$message_body variable is the content from the textarea on the contact form. It can contain any character a user can input.
    
    	class unicode_replace_entities {
    	    public function UTF8entities($content="") {
    	        $contents = $this->unicode_string_to_array($content);
    	        $swap = "";
    	        $iCount = count($contents);
    	        for ($o=0;$o<$iCount;$o++) {
    	            $contents[$o] = $this->unicode_entity_replace($contents[$o]);
    	           $swap .= $contents[$o];
    		    }
    		    return mb_convert_encoding($swap,"UTF-8"); //not really necessary, but why not.
    		}
    
    	    public function unicode_string_to_array( $string ) { //adjwilli
    	        $strlen = mb_strlen($string);
    	        while ($strlen) {
    	            $array[] = mb_substr( $string, 0, 1, "UTF-8" );
    	            $string = mb_substr( $string, 1, $strlen, "UTF-8" );
    	            $strlen = mb_strlen( $string );
    	        }
    	        return $array;
    	    }
    
    		public function unicode_entity_replace($c) { //m. perez
    		    $h = ord($c{0});   
    		    if ($h <= 0x7F) {
    		        return $c;
    		    } else if ($h < 0xC2) {
    		        return $c;
    		    }
               
    		    if ($h <= 0xDF) {
    		        $h = ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
    		        $h = "&#" . $h . ";";
    		        return $h;
    		    } else if ($h <= 0xEF) {
    				$h = ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);
    				$h = "&#" . $h . ";";
    			    return $h;
    		    } else if ($h <= 0xF4) {
    		        $h = ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);
    		        $h = "&#" . $h . ";";
    		       return $h;
    		    }
    		}
    	}
       
    	$message_body=trim(previous_request_value('message_body')); // retrieves the user input from the textarea and trims spaces.
    	$message_body=nl2br($message_body); // converts all carriage returns etc to html line breaks (<br />). Not important for anything other than the way I create a html email to send via Pear Mail.
    	$oUnicodeReplace = new unicode_replace_entities();
    	$message_body = $oUnicodeReplace->UTF8entities($message_body); // calls the function to convert to entity numbers.
    
    
    	$message_body=str_replace('<br />', '<br>', $message_body); // changes all the <br /> created by nl2br to <br>, not important for anything other than the way i create my html emails.
    	$message_body=str_replace('<br>', '<br>', $message_body); // same as above comment
    	$message_body=str_replace('<br />', '<br>', $message_body); // same as above comment
    

     

    Thinking about the above way I use the function and build a html email using pear mail. Should I be santising the input further or doing something to prevent xss? I'm not overly clued up on sanitisation and I've looked about, but there are mixed messages. Some people say you have to escape user inputted strings, some say you don't. Any comments would be appreciated!

     

     

  18. Hi all,

     

    Just a quick query really. We have a contact script on our website which has a message box for the enquiry. Once a user submits their message, the message is checked for malicious code, then converted to html format for use in a pear mail html email. Everything works great except two symbols which never get converted correctly, they always turn into ?? rather than the symbols themselves.

     

    The symbols in question are marks in the code below....

     

    function cndstrips($str) {
    		if (get_magic_quotes_gpc()) {                        
    		return htmlentities(utf8_decode(html_entity_decode(nl2br(stripslashes($str)))));
    		} else {
    		return htmlentities(utf8_decode(html_entity_decode(nl2br($str))));
    		}
    	}
    
    	$message_body=trim(previous_request_value('message_body'));
    	$message_body=str_replace('-', '-', $message_body);
    	$message_body=str_replace('‘', '&#39;', $message_body); // This Symbol
    	$message_body=str_replace('”', '&#34;', $message_body); // This Symbol too!
    	$message_body=cndstrips($message_body);
    	$message_body=str_replace('<br />', '<br>', $message_body);
    	$message_body=str_replace('<br>', '<br>', $message_body);
    	$message_body=str_replace('<br />', '<br>', $message_body);
    

     

    I have attempted to convert them to their relevant html entity numbers (by str_replace) but this doesn't work. Is there an easier way to do the above? I'm not the best with sanitising code as you may see!!

     

    Thanks in advance.

  19. You need to send from whatever email server handles joebloggs.com (smtp.europe.secureserver.net). Otherwise, since server1.host.com knows that it doesn't handle that domain's email traffic, then it will include a Sender: header which triggers the "on behalf of" reaction.

     

    Thanks for the reply, would mail.joebloggs.com (as set in my dns a records) be what I'm looking to use? Or do I need to put something else? It is all sent via the php mail() function so doesn't use smtp.

     

     

  20. Hi all,

     

    Our webhost has upgraded to a more secure mail server and since then all the enquiries we receive from our own website don't have our name to them.

     

    For example:

     

    Before the mail server was changed our emails from our contactus.php would come in as Joe Bloggs Ltd <"enquiries@joebloggs.com">. With all the usual subject/message.

     

    Now it comes through as ourusername@server1.host.com On Behalf Of enquiries@joebloggs.com

     

    This wouldn't be a problem, except this happens on any of the successfully registered etc emails which come from our regirstration area on the website (as it uses a very similar script method). So our customers sometimes block the email as its coming from a random address.

     

    The script works as so:

     

    	$contact_to_email="enquiries@joebloggs.com";
    	$contact_subject="Alert: ";
    	$contact_from_email="enquiries@joebloggs.com";
    
    	$visitor_name_and_email="$visitor_name (" . $visitor_email . ")";
    	$contact_from_email="$contact_from_name <$contact_from_email>";
    	$message_subject="Website Enquiry";
    
    	//message
    
    	$headers = "From: " . $contact_from_email . "\r\n";
    	$headers .= "Reply-To: ". $contact_from_email . "\r\n";
    	$headers .= "MIME-Version: 1.0\r\n";
    	$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    
                    mail($contact_to_email, $contact_subject." $message_subject", $message, $headers);
    

     

    I've stripped out input verification etc to make it easier to read. Is there anything I can do to the script above to cure the issue?

     

    Ta!

×
×
  • 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.