PHP - Logging Successful File Downloads
So, I have a script that works downloading a file - excerpt below:
Code: [Select] header("Pragma: public"); header("Expires: 0"); header('Content-type: "application/octet-stream"'); header("Cache-Control: private",false); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $f = "Content-Disposition: attachment; filename=\"".$myfile['downloadname'].".".$myfile['ext']."\""; header($f); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($file)); ob_clean(); flush(); readfile("$file"); exit(); I record elsewhere in a mysql database when the script is started. In addition, I'd like to be able to record whether the download completes (successfully or otherwise). As it is, the script can run and the user press cancel and it looks like a download but isn't. Is this possible? If so, how? Your help, as ever, gratefully received. Similar TutorialsIs there a way (in PHP) to prompt to download file regardless of it's type? I have taken someone's suggestions and put files in a folder with HTAccess protection. ALL I want to do is just grab the files and prompt download (regardless of what the type of file is), is there an easy way to do this in PHP. I'm creating a CSV file on the fly for download in the backend - a stock management function. The script works fine extracting from the database fine and creates the CSV. But the next step of the script is to download the file using: header('Content-type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $filename . '"'); This works, in as much as it downloads the file specified by $filename but when I open the file it's empty and the File Size in properties is 0. But if I go into my FTP and download the file it contains all the data as expected? Anyone have any ideas whats wrong? Thoughts I've had: File size too large would using ob_start('ob_gzhandler'); help? Or is there an INI setting? File encoding needs to be set? UTF8? Content Type should be text/csv? Thanks I have a function to writes data I want to make sure it was successful. my function: Code: [Select] function save_ini_file($filename,$content) { $File = "ini_files/". $filename . ".ini"; echo $File; $Handle = fopen($File, 'w'); $info = $content; fwrite($Handle, $info); fclose($Handle); return true; } the if statement that calls the function. Code: [Select] if(!save_ini_file($serial,$data)) { echo "did not write"; }else{ echo "did write"; } the file is being created but I am getting the "did not write" echoed I would like to be able to add a yes/no to a field in a 'user' database when a logged in user clicks on a link to download a file. The site I have built stores docs and applications. and my client would like to know which user has downloaded a certain application (clicked on a button to 'download' and installer file. Is this possible? I am new so please forgive me if my questions are very very simplistic in nature. After my user logs in successfully, how can I have the new screen to display their name? I capture their name in the code already. I'm using a templated PHP script where the (video) Upload Form info (title, description, etc.) is displayed (after the upload) on a page below the video. Hi guys, I'm running the following code: Code: [Select] $result = shell_exec("su user; scp /path/to/file/text.txt user@domain:/path/to/file/text.txt"); Now, the file get's transferred correctly. However, I need to put in place a check to check if the transfer was successful. $result seems to return the same whether the transfer was successful or not. I want to send an email to state whether the file transfer was successful so what do I need to do to check this? Thanks! I am running an UPDATE query which runs successfully, but my code throws an error saying that the UPDATE did not occur?! Specifically, I get a "MEMBER_UPDATE_FAILED_2126" Here is my code... // ************************ // Update Last Activity. * // ************************ if ((isset($_SESSION['loggedIn'])) && ($_SESSION['loggedIn'] == TRUE)){ // Initialize variables. $loggedIn = 1; $memberID = 19; // For Test Purposes // $memberID = (isset($_SESSION['memberID']) ? $_SESSION['memberID'] : ''); // ************************ // Update Member Record. * // ************************ // Connect to the database. require_once(WEB_ROOT . 'private/mysqli_connect.php'); // Build query. $q = "UPDATE member SET logged_in=?, last_activity=now() WHERE id=? LIMIT 1"; // Prepare statement. $stmt = mysqli_prepare($dbc, $q); // Bind variables to query. mysqli_stmt_bind_param($stmt, 'ii', $loggedIn, $memberID); // Execute query. mysqli_stmt_execute($stmt); // Verify Update. if (mysqli_stmt_affected_rows($stmt)!==1){ // Update Failed. $_SESSION['resultsCode'] = 'MEMBER_UPDATE_FAILED_2126'; // Redirect to Display Outcome. header("Location: " . BASE_URL . "/members/results.php"); // End script. exit(); }//End of UPDATE MEMBER RECORD // Close prepared statement. mysqli_stmt_close($stmt); // Close the connection. mysqli_close($dbc); }//End of UPDATE LAST ACTIVITY This was working earlier, so what is going on?! Thanks, Debbie we have already see the facility in website gmail and facebook that when user log-in successfully then its redirects the page to another page automatically, can someone tell me how to redirect the page when log-in becomes successful ?
User tries to Log-in -> create session variable -> now redirect the page
I can verify user account details and set the session variable at the same time, but how to reload the page so that it finds the session and reload itself and then redirect the page to new page ??
Thanks for sparing your time here !!
I'm using a templated PHP script and have successfully added a link (to an image) Hello, I'm trying to store the match I get in $result to a variable so that I can easily compare its other values against other values. Here is my code.. //loop through new orders array foreach ( $orders as $order ) { //compare job number and line item against database information for a match if ( array_search ( $order[ 'job_number' ], array_column ( $result, 'job_number' ) ) !== false && array_search ( $order[ 'line_item' ], array_column ( $result, 'line_item' ) ) !== false ) { $db_match = key($result); echo '<br><br>'.$db_match.'<br><br>'; echo 'Job: ' . $order['job_number'] . '/Line Item: ' . $order['line_item'] . ' was found<br>'; //new order which doesn't exist in database } else { echo 'Job: ' . $order['job_number'] . '/Line Item: ' . $order['line_item'] . ' was not found<br>'; } } When I do $db_match = key($result); I get 0 each time and when I do: $db_match = array_search ( $order[ 'job_number' ], array_column ( $result, 'job_number' ) ) !== false && array_search ( $order[ 'line_item' ], array_column ( $result, 'line_item' ) ) !== false; I get 1 each time...which I assume is the number of matches which meet that criteria instead of the array key I found a match on. Edited May 8, 2020 by mongoose00318Not sure if I'm putting this in the correct spot, but, Can anyone give me a link or an idea of how to fix Drive-By downloads I have on a site I have created? Everything I search for online brings up how to repair an issue someone may have gotten on their computer from a drive-by download, but nothing talks about repairing it on the actual site itself. I don't have any injections or anything, but doing a check on my site from the norton site shows that I have 1 Threat and it's on a contact form page due to Drive-By Downloads, is this from the php tags on the form not being stripped or from the javascript possibly? Some old lady submitted my site to http://safeweb.norton.com/report/show?url=gotmine.com, now I have to fix it I guess. Any help would be great, Thanks. Hi ! I am currently trying to develop a PHP application in which my server downloads a file and the user can do the same almost simultaneously. I already think about the problem "If the user downloads fastly than the server...", but it's not a problem at this moment. To do so, I used the header and readfile functions of php. Here is my code : Code: [Select] header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$data['name'].'";'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.$data['size']); readfile($remoteFile); I must to use the Content-length header to set the proper size of the file and not the size that is downloaded when the user clicks on the link. However, after some seconds or minutes, download is stopped and I need to restart... If you think about a solution, even if it didn't use the header(); function, please tell me. Thank you in advance... 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: Code: [Select] // 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*8)); 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): Code: [Select] // 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. Not sure exactly what my problem is here, but i have looked at this at least a hundred times and I just can't figure out what is going on. Everything works great except for the sending the email part. It displays the error "There was a problem sending the mail". The form field checking works fine, the insert into mysql works fine - - but it won't send the email. I have tried using double quotes and single quotes for the email information ($to, $subject, etc...) I have even eliminated the form data from the email information and it still doesn't send. I am hopelessly stuck at this point Any ideas?? Code below: <html> <body bgcolor = 'blue'> <div align = 'center'> <h1>test FORM</h1> </div> <p> <?php If ($_POST['submit']) //if the Submit button pressed { //collect form data $fname = $_POST['FName']; $lname = $_POST['LName']; $email = $_POST['Email']; $tel = $_POST['Tel']; $mess = $_POST['Mess']; $errorstring = ""; if (!$fname) $errorstring = $errorstring."First Name<br>"; if (!$lname) $errorstring = $errorstring."Last Name<br>"; if (!$email) $errorstring = $errorstring."Email<br>"; if ($errorstring !="") echo "<div align = 'center'><b>Please fill out the following fields:</b><br><font color = 'red'><b>$errorstring</b></font></div>"; else { $fname = mysql_real_escape_string($fname); $lname = mysql_real_escape_string($lname); $email = mysql_real_escape_string($email); $tel = mysql_real_escape_string($tel); $mess = mysql_real_escape_string($mess); $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mec", $con); $sql="INSERT INTO formtest (FName, LName, Title, Tel, Email, Mess) VALUES ('$fname','$lname','$title','$tel','$email','$mess')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } $to = 'myemailaddress'; $subject = 'test form'; $message = 'Hello'; $headers = 'From Me'; $sent = mail($to, $subject, $message, $headers); if($sent) {print "Email successfully sent";} else {print "There was an error sending the mail";} mysql_close($con); } } ?> <p> <form action= 'testmecform.php' method= 'POST'> <table width = '640' border = '0' align = 'center'> <tr> <td align = 'right'><b>First Name</b></td> <td><input type = 'text' name = 'FName' value = '<?php echo $fname; ?>' size = '25'></td> <td><div align = 'right'><b>Telephone</b></div></td> <td><input type = 'text' name = 'Tel' value = '<?php echo $tel; ?>' size = '25'></td> </tr> <tr> <td align = 'right'><b>Last Name</b></td> <td><input type = 'text' name = 'LName' value = '<?php echo $lname; ?>' size = '25'></td> <td> </td> <td> </td> </tr> <tr> <td align = 'right'><b>Email</b></td> <td><input type = 'text' name = 'Email' value = '<?php echo $email; ?>' size = '25'></td> <td> </td> <td> </td> </tr> <tr> <th colspan = '4'><b>Please enter any additional information he </b></th> </tr> <tr> <th colspan = '4'><textarea name = 'Mess' cols = '50' rows = '10'><?php echo $mess; ?></textarea></th> </tr> <tr> <th colspan = '4'><b>Please make sure all information is correct before submitting</b></th> </tr> <tr> <th colspan = '4'><input type = 'submit' name = 'submit' value = 'Submit Form'></th> </tr> </table> </form> </body> </html> I have a page that functions like this:
The user begins by loading ajaxtest.php, then using a drop-down menu, selects a user, after which a DIV on ajaxtest.php is populated with the user's selction to getuser.php?q=John%Doe
Here's a visual representation of what is currently happening, along with the part I don't understand.
getuser.php consists largely of a a large HTML table which interacts through PHP with my SQL database. Several of the fields in this table are editable, and after the user changes one of these fields, he can press an "update" button, which calls an AJAX script in update.js and runs update.php, which contains all my SQL queries to update the database, without the user being redirected to this update.php page. All of this is processing perfectly - the user makes some sort of edit, hits "update", and the database gets updated without any redirection or refresh.
Here's what I can't figure out though. Once the user makes a change, and hits "update," the database updates, but the end user doesn't see those changes that he made. I can't just do a simple page refresh, because the action is taking place on getuser.php, but getuser.php is loaded inside of a #DIV on ajaxtest.php. If I use something like window.location.reload(), this just refreshes ajaxtest.php and puts the user back to the starting point of having to select a user. This is not what I want. I don't want to refresh ajaxtest.php, I want to "refresh" ajaxtest.php with getuser.php?q=John%Doe insidethe DIV on ajaxtest.php.
It seems like this is very common - several forums have this capability, where a user has a page loaded, adds a comment, and sees that comment immediately without a full page refresh. I just don't know how to do it, and I've tried at lengths to search the web for an answer with no luck.
Can someone walk me through how to do this?
This upload form code works successfully, where a file is chosen, renamed and stored in the 'upload' folder, Hi, Firstly, apologies if this is in the wrong place in the forum to post this. I have a website, I use PHP in various places to pull/push info from/to a mySQL database, i'm fairly happy with PHP and its uses. I've recently started to use the Google checkout widget on the site for a proposed webstore (to go live at a later date), this has the ability to 'sell' download URL's or keys. I like the idea of a customer being able to purchase multiple MP3 downloads and them being given a URL that gives them the links for the MP3's selected. This is probably beyond anything i've ever done with PHP though so I need to understand the architecture........I understand that, given a list of items from the store, I can run a query to display a list of stored URL's for those items - and I'm sure I can find code that will give me a random URL that will 'expire' after an amount of time. My question is, how to get the list of items ordered from the google checkout?? I'm sure this has something to do with API's - but I don't know what they are, presumably there is some kind of table in Google that I can tap into to get the product info?? any help would be very much appreciated. ....oh, and i'm sure people are going to ask "why are you using Google checkout", the answer being, for me, it seems simple, effective and free! (but i'm open to suggestions.) Darren Hi, I have downloads that are available for users. They can click the links to download the file. Once they do this, I have a query that updates the number of downloads that file has received. I need to create a query that adds up all the rows Total Downloads. So for example: i have 3 rows: Name - Total Downloads First - 2 Second - 23 Third - 7 Using the query for these rows would give me an amount of 32. Any idea how to do this? I don't want to have to create a new column to find the total number of downloads. Any other ways? I can seem to login it tells me to check my password and username but i dont know the username and password are correct
here is my whole code
<?php //start the sessoin session_start(); //connect to db require "scripts/connect.php"; $username = $_POST['username']; $password = $_POST['password']; $username = mysqli_real_escape_string($db,$username); $password = mysqli_real_escape_string($db,$password); if(isset($_POST['loginbtn'])){ if(!empty($username) && !empty($password)){ //sql command $getstaff = "SELECT * FROM `users` WHERE `username` = '$username'"; //execute the query $query = mysqli_query($db,$getstaff); //get the number of rows $num_rows = mysqli_num_rows($query); if($num_rows != 0){ //get the info $rows = mysqli_fetch_assoc($query); //setting the data in indivaul variables $dbusername = $rows['username']; $dbpassword = $rows['password']; //getting the password the user enter and making it hash //in order for it to match in the database $password = md5($password); if($dbusername === $username && $dbpassword === $password){ //create the session $_SESSION['username'] = $username; //redircet them to the control panel header("location: controlpanel.php"); }else $msg = "Please check your username or password"; }else $msg = "User does not exist"; }else $msg = "Please enter your username and password"; } ?>This is where it is giving me a hard time if($dbusername === $username && $dbpassword === $password){ //create the session $_SESSION['username'] = $username; //redircet them to the control panel header("location: controlpanel.php"); }else $msg = "Please check your username or password";Any ideas why its not letting me enter |