I have a client that uses a website builder that does not offer the ability to edit the code or access the database but hey want to track the downloads of a file.
I setup a system in which I host the file elsewhere, and their website has an <a> link to a page on the host site with a very simple script to insert a record to track the download, as well as download the file.
This is the php script in the page on my site, download-agreement.php:
<?php
$db = new mysqli('localhost', 'username', 'password', 'database');
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$file_path = 'agreement.pdf';
$stmt = $db->prepare("INSERT INTO `download_log` (`date`) VALUES (CURRENT_TIMESTAMP())");
if ($stmt===false) {
error_log($db->error);
}
$result = $stmt->execute();
if ($result===false) {
error_log($stmt->error);
}
$stmt->close();
$db->close();
error_log("Downloaded: " . date("Y-m-d H:i:s"));
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename=agreement.pdf');
readfile($file_path);
?>
And the link I have placed on their site:
https://www.host.com/theirdirectory/download-agreement.php
If link is visited directly, it works properly - the error_log() executes and the record is inserted.
If the link is visited after being clicked on their website, only the file downloads. The error_log() is not executed and the record is not inserted.
I am at a bit of a loss as I cannot even get an error. And thoughts or ideas would be appreciated.
EDIT
This seems to be an issue with Chrome for Desktop (which doesn't really make any sense). This works properly on all browsers except for Chrome for Desktop (it works on chrome for mobile), tested on all with caching disabled on multiple computers.
Thanks to everyone for all of the help, the issue turned out to be the elements in the "GoDaddy Website Builder" on the client's website where the link was stored.
I am still not sure what exactly the issue was but my solution was to make this work I had to use an HTML Section that allowed me to write in the link manually as an html code block - which happens to render as an iframe in their builder, differently from other pre-built elements such as buttons with links etc. It seems that there may be some caching happening on their end (as esqew mentioned there may be) or something going on behind the scenes with those elements that is behaving differently in different browsers.
Related
I should start by saying that I am not super familiar with deploying apps. Most of my web development has been through a framework that handles everything for me, or it's been done locally. Now that I'm trying to deploy a personal project, I'm having issues.
I have a PHP website that I have deployed on Heroku. I have been having one issue after another with sessions (everything is working perfectly locally, but breaks on Heroku). I have solved most of the issues by going through about a million other posts. I'm using Memcachier, I'm making sure there is a favicon, I went through and added "exit();" after each header("location: ... ") call, etc.
Finally, I have sessions working almost perfectly except on one page. I have on this page the following code:
<?php
include('header.php');
include('functions.php');
//if id is set, flag as help needed
if(isset($_GET['id'])) {
flagHelped($_GET['id'], 1);
}
//if cancel is set, unflag as help needed
if(isset($_GET['cancel'])){
flagHelped($_GET['cancel'], 0);
}
//start the session and store userID in variables.
session_start();
$userID = $_SESSION['user_id'];
//grab all pets attached to this user.
$pets = getPets($userID);
?>
<!-- create table of pets -->
<div class='container bg-white'>
<table class='table'>
<tr><th>Picture</th><th>Pet Type</th><th>Pet Name</th><th>Zip Code</th><th> Profile </th></tr>
<?php
if($pets != null){
foreach($pets as $pet){
echo "<tr>";
echo "<td><img style='width:150px' src=\"".$pet["pictureLink"]."\"></td>";
echo "<td>".$pet["type"]."</td>";
echo "<td>".$pet["name"]."</td>";
echo "<td>".$pet["zipCode"]."</td>";
if($pet["needsHelp"] == 0){
echo "<td><button class = 'btn btn-success'>Request An Angel</button></td>";
}
else{
echo "<td><button class = 'btn btn-danger'>Cancel Request</button></td>";
}
echo "</tr>";
}
}
?>
</table>
<?php
include('footer.php');
?>
flagHelped() looks like this:
function flagHelped($petId, $status){
echo "in flag helped";
$connection = new mysqli(//credentials here);
$connection->query("UPDATE Pets Set `needsHelp`=".$status." where `petId`=".$petId.";");
$connection->close();
return;
}
It's a pretty simple page that prints a list of pets associated with the user that is logged in, and prints a button that redirects back to the current page as a get request with a URL variable.
The first time the pages loads (with no URL variable), there is no issue. After clicking a button, it calls the flagHelped() method, gets all the way through, saves properly to the database and returns. However, session_start() doesn't seem to do anything on return and it never gets to getPets();
I have put debugging print statements pretty much everywhere, and I have reordered the page in different ways. If I set the session before calling flagHelped(), I am able to print the $userID variable, but once I return from that function (which is in functions.php), $userID is no longer valid. Since I didn't need any of the session variables for that function, I decided I would just call the session variables after I returned. But even that isn't working.
Again, I'm sorry if I'm asking a dumb question here, I've been at it for hours and I'm at my wit's end.
Side Note: I am aware that there might be security risks on this page. This is for an application I built in less than 16 hours at a hackathon, so I'm not worried about the security risks. I'm purposely putting up how far I got before the code turn-in time. The database is filled with fake data and I have a disclaimer where I link to it saying not to use real information because of potential risks.
Edit: Adding pictures:
First time going through page (no URL variable) with echo statements
Second time going thorugh page (with URL variable) with echo statements
Ok, so I finally figured it out. I'm posting here in case any one else runs into this issue and comes across my post.
This worked locally and not on heroku and I couldn't figure out why. It turns out it's because I was trying to store images locally on heroku's server. When I stored them locally in my own project, they would stay in the folder that I saved them. When I stored them locally on heroku (if a user uploaded a picture on the heroku url while deployed), once my application slept after 30 minutes of inactivity, it would delete the picture.
What was happening was that my project couldn't find that image, and for whatever reason, that caused a session invalidation. Locally, all worked fine (even without being able to find the image), it only stopped working once deployed on heroku. I manually deleted those records from the database, and that page worked perfectly again.
(Now I'm looking into heroku storage options for projects to help permanently solve the problem.)
I have an automated archive of several (media) websites' frontpage, written in php. Specifically, I am copying the html in the <body> tag twice a day, I have a copy of all their css and js files, so I can recreate the frontpage from any point in the past. Now, I came to a problem with one of those websites, as they load the main slider content (most important news) with an ajax call. I would like this ajax call to be executed before I parse the data, not just a blank div. By looking around, I found out they use a wordpress plugin named lof-jslidernews2, but I can't find the specific ajax call to see the url and make curl request. Any ideas how to achieve this?
The website: http://fokus.mk/
My code (had to parse manually like this, because of some problems with DomDocument and not-valid html):
// ...
if($html = file_get_contents ($row['page_url'])) {
$content = strstr($html, '<body');
$content = str_before($content, '</body>') . '</body>';
$filename = date('YmdHis') . $row['page_name'];
if($success = file_put_contents ('app/webroot/files/' . $filename, $content)) {
// ....
** There is nothing illegal about my project, I am not stealing content, just freezing frontpages for later comparison. I have consulted a lawyer about this. :)
I don't know why, but the guy that actually solved my problem deleted his answer. So, here it is:
He suggested using an emulator, specifically Mink. It was easy to install (using composer) and did the job on the first try. Awesome library.
Mink is an open source browser controller/emulator for web applications, written in PHP 5.3.
I am having an issue with a site that I am moving onto a new server. This site is connected to a SQL Server database, and is working correctly in it's current location. However, the new location is having problems with a single mssql_execute. Here is a sample of the code:
function get_customer_select_info() {
$link = get_db_link();
$customer_all_command_text = "dbo.Customer_All";
$customer_all_stmt = mssql_init($customer_all_command_text, $link);
$search = "%";
mssql_bind($customer_all_stmt, "#parm1", $search, SQLVARCHAR, false, false, 15);
$result = mssql_execute($customer_all_stmt);
mssql_free_statement($customer_all_stmt);
return $result;
}
Calling the above function results in
Unable to load the webpage because the server sent no data.
Error code: ERR_EMPTY_RESPONSE
from Chrome.
get_db_link retrieves a new connection to the database, or returns the current one if it already exists. It is functioning correctly. I have tried just closing the link and creating a new one if one already exists, which had no effect on the error.
This is not a problem connecting to the database because before this stored procedure is executed, three others are called and executed correctly.
Another complication is that running a trace on the given database results in this stored procedure getting called on the database and being successful!
Commenting out the mssql_execute makes the page load correctly (minus the information that this function returns).
Again, the same exact code on the current server works correctly, but the code on the new server is causing problems. I can't obtain any debugging information from apache or php because it is not actually sending anything.
If you facing ERR_EMPTY_RESPONSE then i will suggest you to follow these steps
Refresh page and restart browser
Clean your cache and browser cookies
Check internet connection
Update Google Chrome
Check router
I am also sharing video tutorial where you will find the complete solution of given steps to resolve your problem here is the link
http://vimeo.com/60824619
Best of luck
Im pulling the binary data out of my mySql database and want to display it as a image.
I do not want to make a separate page for it to display the image (this would involve a extra call to the databae among other things)
I simply want to be able to do
Pretty much but the $Image variable is in its longblob format and I need to convert it.
THanks in advance.
I know this is not a specific answer to your question, but consider that by removing that database call, you are dramatically increasing your server load, increasing the size of each page and slowing down the responsiveness of your site.
Consider any page stackoverflow. Most of it is dynamic, so the page cannot be cached. but the users' thumbnail is static and can be cached.
If you send the thumbnail as a data URI, you are doing the DB lookup and data transfer for every thumbnail on every page.
If you send it as a linked image, you incur a single DB lookup for when the image is first loaded, and from then on it will be cached (if you send the correct HTTP headers with it), making your server load lighter, and your site run faster!
I do not want to make a separate page for it to display the image
You can base64 encode your image data and include it directly into the markup as a data URI. In most cases, that's not a good idea though:
It's not supported by IE < 8
It (obviously) sizes up the HTML page massively.
It slows down rendering because the browser has to load the resource first before it can finish HTML rendering
Better build a separate script, and make that one extra call.
You could probably do this using Base64-encoded Data URIs.
I'm not sure if it's possible to do straight into a img-tag, but you can do it by setting a background-image for a div.
Basically you change the regular
.smurfette {
background: url(smurfette.png);
}
to
.smurfette {
background: url(data:image/png;base64,iVBORw0KGgo [...] P6VAAAAAElFTkSuQmCC);
}
Data URIs are supported in:
* Firefox 2+
* Safari – all versions
* Google Chrome – all versions
* Opera 7.2+
* Internet Explorer 8+
Info borrowed from Robert Nyman: http://robertnyman.com/2010/01/15/how-to-reduce-the-number-of-http-requests/
$_GET the result into a separate variable i.e. $myvar = $_GET['Id']; before you process the $imageResult line e.g.:
$myid = $_GET['Id'];
$ImageResult = "select player.Image from player where Id = '$myid'";
thanks for the answers, ive decided to go with a separate GetImage.php page but now cant seem to do the simplest of tasks
$ImageResult = "select player.Image from player where Id = " . $_GET['Id'];
$result = mysql_query($ImageResult) or die ("data recovery failed -3");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
But this returns just a broken link and cannot work out what I have missed out
I am using CodeCharge Studio to finish a large PHP application. This question isn't really CCS related, but a bit more general. I have a web form that is supposed to allow CRUD capabilities with a certain SQL Server table, but the Inserts keep failing without throwing any errors. What would be the best way to debug this?
When I'm having trouble with dynamically generated SQL queries, I typically echo out the query and try running that query on the console for the DB. Or alternatively, you could write a simple PHP function that writes out strings to a file, and that way you don't have to display the query directly on your page, but instead in a log file.
See what the actually query is and then try doing that query directly on the DB. Then you know whether it's a PHP issue or a DB issue.
Then go from there, depending on the outcome.
If the query looks OK, double check that the user running the query has insert rights to the database.
I've been caught out by that before.
You can monitor all sql queries in mysql as shown in this site, once you enable logging, run the query manually and see why its failing..this should be good starting point.
In addition to what's mentioned before, I can add my recent discovery:
trigger_error(print_r($your_var,1),E_USER_ERROR);
So you can output and debug your variable, even if it's a complex script with redirects, where simple echo would not help.
Dmitri.
You should try using FirePHP and log all the SQL to your Firebug:
An Example would be:
$sql = "SELECT * FROM table"
if (!mysql_query($sql)) {
// In un successfull log to FireBug
FB::error($data, "SQL error: ".mysql_error());
}
You can also implement the FB::error call from your own function, so you can later deactivate this behaviour modifying your function:
function log_error($data, $msg){
//dont forget to deactivate in case the application goes live!
FB::error($data, $msg);
}
if (!mysql_query($sql)) {
// In un successfull log to FireBug
log_error($data, "SQL error: ".mysql_error());
}
Most of the database connection classes in CodeCharge have a 'debug' flag which will automatically write all the page's database commands at the top of the page.
For example, in an old PHP project of mine, 'Common Files' the file 'db_mysql.php' (line 27):
public $Debug = 0; ## Set to 1 for debugging messages.
Change to '1' and publish that file. Load the web page. Change back and re-publish when done.
I've used this in CCS for PHP and ASP projects, and is likely in the other languages (not sure if or where to find in .NET projects).