I have PHP code for downloading pdf files from mysql database.
The code is working fine in firefox mozilla and google chrome but not in IE 10, it show garbage in the screen.
I have debugged the code with some headers utilities to examine the headers request, it appear the headers is not sending back to the user agent (IE browser) it just blank.
<?php
ob_start();
$company =$_GET['company'];
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
if($id <= 0)
{
die('The ID is invalid!');
}
else
{
$dbLink = new mysqli('localhost', 'sqldata', 'sqldata', 'balhaf');
if(mysqli_connect_errno())
{
die("MySQL connection failed: ". mysqli_connect_error());
}
$query = "SELECT mime, name, size, data FROM $company WHERE id = $id";
$result = $dbLink->query($query);
if($result)
{
if($result->num_rows == 1) {
$row = mysqli_fetch_assoc($result);
$size = $row['size'];
$filename = $row['name'];
$data = $row['data'];
$mime = $row['mime'];
ini_get('zlib.output_compression');
ini_set('zlib.output_compression', 'Off');
header('Content-Type: application/pdf');
while (#ob_end_clean());
header('Content-Disposition: attachment; filename='.($filename));
header('Content-Length:'.($size));
echo $data;
exit();
}
else
{
echo 'Error! No image exists with that ID.';
}
mysqli_free_result($result);
}
else
{
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
mysqli_close($dbLink);
}
}
else
{
echo 'Error! No ID was passed.';
}
?>
Related
I cannot update the values in my table with this code, if the update is successful the page should redirect in ('Location:ui.php'), how can this be achieved?
<?php
ob_start();
include('dbconnect.php');
$code=$_GET['stallcode'];
if(isset($_POST['submit']))
{
$pcost = $_POST['pcost'];
$tcost = $_POST['tcost'];
$cash = $_POST['cash'];
$change = $_POST['change'];
if (($cash == '0'))
{
$pstatus="0";
}
else
{
$pstatus="1";
}
$updated=mysql_query("UPDATE tbl_stallowner SET
paymentstatus='$pstatus', penaltycost='$pcost', totalcost='$tcost', cash='$cash', change='$change'
WHERE stallcode='$code'")or die();
if($updated)
{
$msg="Successfully Updated!!";
header('Location:ui.php');
}
} //update ends here
ob_end_flush();
?>
As you redirects users by checking if($updated) is true, this will not work, you should check the number of affected rows instead using mysql_num_rows.
Also remember to exit; after header() to stop the execution.
$num_rows = mysql_num_rows($updated);
if($num_rows > 0)
{
$msg="Successfully Updated!!";
header('Location:ui.php');
exit;
}
Tip: You should not be using MySQL as it has already been deprecated, use MySQLi instead.
You want to use mysqli, not it's predecessor, mysql. Mysql is vulnerable and open to exploitation, here's what you should write in each of your files:
dbconnect.php
<?php
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
updatestallowner.php (or whatever you named it)
<?php
ob_start();
require('dbconnect.php');
$code = mysqli_real_escape_string($conn, $_GET['stallcode']);
if(isset($_POST['submit'])){
$pcost = mysqli_real_escape_string($conn, $_POST['pcost']);
$tcost = mysqli_real_escape_string($conn, $_POST['tcost']);
$cash = mysqli_real_escape_string($conn, $_POST['cash']);
$change = mysqli_real_escape_string($conn, $_POST['change']);
if ($cash == '0') {
$pstatus="0";
} else{
$pstatus="1";
}
$sql = "UPDATE tbl_stallowner SET paymentstatus='$pstatus', penaltycost='$pcost', totalcost='$tcost', cash='$cash', change='$change' WHERE stallcode='$code';";
$result = mysqli_query($conn, $sql);
if($result) {
$msg="Successfully Updated!!";
header('Location: ui.php');
exit;
} else {
die("Error updating!");
}
}
?>
Good luck!
I have a PHP login page on a website in the following form:
<?php
$logincorrect = 'notdefined';
$SubmitLogin = 'no';
session_set_cookie_params (3600, $httponly = true);
session_start();
if (isset($_POST['SubmitLogin'])==TRUE)
{
$SubmitLogin = 'yes';
$email = strtolower($_POST['email']);
$passwrd = md5($_POST['nametag']);
}
if($SubmitLogin == 'yes')
{
$link = mysql_connect ('address.website.com', 'restricteduser', 'password_here');
if (!$link)
{
echo '<p style="color:red">* Error: Could not connect to database.</p> ';
}
$email = mysql_real_escape_string(strip_tags($email),$link);
$passwrd = mysql_real_escape_string(strip_tags($passwrd), $link);
$selectDB = mysql_select_db ('database', $link);
if (!$selectDB)
{
echo('<p style="color:red">* Error: Could not select database.</p> ' );
mysql_close($link);
}
$passwrdcheck = mysql_query
(" SELECT * FROM tablename WHERE email = '$email' AND passwrd = '$passwrd'");
if (!$passwrdcheck)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
if(mysql_num_rows($passwrdcheck) == 0)
{
$logincorrect = 'no';
echo '<p style="color:red">Login details incorrect. Please try again.</p>';
}
else
{
$logincorrect = 'yes';
if($profile = mysql_fetch_array($passwrdcheck));
{
if($profile = mysql_fetch_array($passwrdcheck));
{
$ID = $profile['ID'];
$languages = mysql_query
(" SELECT * FROM translanguages WHERE ID = '$ID' ");
if (!$languages)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
$expertise = mysql_query
(" SELECT * FROM transexpertise WHERE ID = '$ID' ");
if (!$expertise)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
$tracking = mysql_query
(" SELECT * FROM transtracking WHERE ID = '$ID' ");
if (!$tracking)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
if($profile2 = mysql_fetch_array($languages))
{ if($profile3 = mysql_fetch_array($expertise))
{ if($profile4 = mysql_fetch_array($tracking))
{
$_SESSION['profile'] = $profile;
$_SESSION['profile2'] = $profile2;
$_SESSION['profile3'] = $profile3;
$_SESSION['profile4'] = $profile4;
//echo "Login successful. If you are not automatically redirected, please click <a href='profile.php'> here </a>.";
header ("Location: ./profile.php"); exit;
}
}
}
}
}
}
}
?>
This works fine from my PC and my android phone. However, it does not work from my ipad. I have tried chrome and safari on the ipad and the result is the same: when clicking the 'SubmitLogin' button, the login page just appears to refresh instead of connecting to the database and checking the entered information. No error messages are shown.
I have racked my brain for days, but can't work out why this would be. Any ideas? Thanks!
Edit:
The 'directing back to the login page' part of profile.php is as follows:
$loggedin = 'no';
session_set_cookie_params (3600, $httponly = true);
session_start();
if(isset($_SESSION['profile']) AND isset($_SESSION['profile2']) AND isset($_SESSION['profile3']) AND isset($_SESSION['profile4']))
{
$profile = $_SESSION['profile'];
$profile2 = $_SESSION['profile2'];
$profile3 = $_SESSION['profile3'];
$profile4 = $_SESSION['profile4'];
$loggedin = 'yes';
}
else
{
session_destroy();
header ("Location: ./login.php");
exit;
}
I am trying to upload a CSV file which contains the fields stated in the link below [see CSV example] via a web form. The user can browse their computer by clicking the upload button, select their CSV file and then click upload which then imports the CSV data into the database in their corresponding fields. At the moment when the user uploads their CSV file, the row is empty and doesn't contain any of the data that the CSV file contains. Is there a way i could solve this so that the data inside the CSV file gets imported to the database and placed in its associating fields?
CSV example:
http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-04-10at145431_zps80a42938.png
uploads.php
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
upload_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'vario007', 'spineless');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$filedata= file_get_contents($_FILES ['uploaded_file']['tmp_name']); //this imports the entire file.
// Create the SQL query
$query = "
INSERT INTO `Retail` (
`date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
)
VALUES (
'{$date}', '{$order_ref}', '{$postcode}', '{$country}', '{$quantity}', '{$packing_price}', '{$dispatch_type}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
try this
<?php
if(isset($_FILES['uploaded_file'])) {
if($_FILES['uploaded_file']['error'] == 0) {
$dbLink = new mysqli('localhost', 'root', 'vario007', 'spineless');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
$file = $_FILES ['uploaded_file']['tmp_name'];
$handle = fopen($file, "r");
$row = 1;
while (($data = fgetcsv($handle, 0, ",","'")) !== FALSE)
{
if($row == 1)
{
// skip the first row
}
else
{
//csv format data like this
//$data[0] = date
//$data[1] = order_ref
//$data[2] = postcode
//$data[3] = country
//$data[4] = quantity
//$data[5] = packing_price
//$data[6] = dispatch_type
$query = "
INSERT INTO `Retail` (
`date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
)
VALUES (
'".$data[0]."', '".$data[1]."', '".$data[2]."', '".$data[3]."', '".$data[4]."', '".$data[5]."', '".$data[6]."', NOW()
)";
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
$row++;
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
fgetcsv() in third argument in separator to you want to save in csv file. Ex: comma,semicolon or etc.
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$filedata= csv_to_array($_FILES ['uploaded_file']['tmp_name']);
foreach($filedata as $data)
{
$sql = "INSERT into table SET value1='".$data['value1']."'......";
}
Hi I am facing a unique issue with my PHP script.Here is my code. After writeToDB() is executed I dont see the echo ("<script> top.location.href=www.facebook.com</script>");
Can someone let me know why my script stops executing after writing to db?
<?php
function writeToDB($access_token,$uid,$username,$birthday,$gender,$age)
{
/* Database Connection */
$user = "xxxx";
$password = "xxxx";
$host = "xxxxxxxxxxxxxxxxxx";
//connect to database, where tsnames.ora is setup
$connect_obj = oci_connect($user, $password, $host);
if ($connect_obj) {
error_log("connected okay");
} else {
$err = OCIError();
echo "Oracle connection error " . $err[text];
return;
}
$select_query = "SELECT USER_ID FROM FBTABLE WHERE USER_ID= '$uid'";
$select_sql_stmt = oci_parse($connect_obj, $select_query);
//execute statement
try {
$r = oci_execute($select_sql_stmt, OCI_DEFAULT);
if (!$r) {
$p = oci_error($select_sql_stmt);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
$user_id_in_db = null;
while (oci_fetch($select_sql_stmt)) {
$user_id_in_db = oci_result($select_sql_stmt, 'USER_ID');
}
// User already exists in db so update instead of insert
if ($user_id_in_db != null) {
$query ="UPDATE FBTABLE SET ACCESS_TOKEN='$access_token' WHERE USER_ID='$uid'";
} else {
$query = "INSERT INTO FBTABLE(ACCESS_TOKEN, USER_ID,USER_NAME,BIRTHDAY,GENDER,AGE)
VALUES
('$access_token','$uid','$username','$birthday','$gender','$age')";
}
//create sql statement
$sql_statement = oci_parse($connect_obj, $query);
//execute statement
try {
$r = oci_execute($sql_statement, OCI_DEFAULT);
if (!$r) {
$p = oci_error($sql_statement);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
//Commit transaction
$committed = oci_commit($connect_obj);
//Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = oci_error($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
//close the connection
$oci_free_statement($sql_statement);
if (oci_close($connect_obj)) {
echo " oci connection not closed!!!";
}
//close the connection
$oci_free_statement($sql_statement);
}
?>
<html>
<body>
<?php
$access_token = $_GET['access_token'];
$uid = $_GET['uid'];
$username = $_GET['username'];
$birthday = $_GET['birthday'];
$gender = $_GET['gender'];
$age = $_GET['age'];
echo $username;
writeToDB($access_token,$uid,$username,$birthday,$gender,$age);
echo ("<script> top.location.href=www.facebook.com</script>");
?>
</body>
</html>
i think error is in $oci_free_statement($sql_statement); must be oci_free_statement($sql_statement); extra $ before oci_free_statement
http://php.net/manual/en/function.oci-free-statement.php
no any error show because of error_display is off
Your JavaScript code should be
echo ("<script> top.location.href='http://www.facebook.com';</script>");
It's happen because writeToDB() causes error. You don't see this error because error_display is off or error_reporting = 0
Also maybe you didn't install OCI8. So when you call oci_connect it will cause error.
Thanks.
you are not using quotes around the string:
www.facebook.com should be 'www.facebook.com'
im having a problem with my code in uploading and displaying images.. well I am planning to redirect the page after the upload process is done so I used a header function but gave warning and errors and unfortunately failed the upload.. how can I remove it? here's the code..
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
the header function supposedly directs me to another page that would make a gallery.. here is the code..
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
while($row = mysql_fetch_assoc($image))
{
foreach ($row as $img) echo '<img src="img.php?id='.$img["id"].'">';
}
mysql_close();
?>
I have also a problem with my gallery .. some help will be GREAT! THANKS! :D
The header() function must be called before any other echo or die calls which produce output.
You may could buffer your outputs if you need the output, but in your case it makes no difference because the output will never be shown to the user. The browser will read the redirect and navigate to the second page.
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con) {
// this output is okay the redirect will never be reached.
die('Could not connect to the database:' . mysql_error());
// remember after a die this message will never be shown!
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel) {
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION"; // same here with the die!
}
//file properties//
$file = $_FILES['image']['tmp_name'];
// OUTPUT
// echo '<br />';
// removed out commented code
for($count = 0; $count < count($_FILES['image']); $count++)
{
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]);
// OUTPUT
// echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
// you may better use a die if you want to prevent the redirection
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results) // use die
echo "Problem uploding the image. Please check your database";
// OUTPUT
// echo "";
}
}
mysql_close($con);
header('Location: fGallery.php');
?>
Above I marked every output for you and also removed all outcomments lines.
You've got a header error because you printed out <br /> before the header function. In order to use the header function you can't print out any information before it. That's why you're getting the error.
Regarding your gallery the foreach loop is unnecessary. You can change the code to this:
while($row = mysql_fetch_assoc($image)) {
echo '<img src="img.php?id='.$row["id"].'">';
}
You can use ob_start() to get data in buffer.