Uploading files to FTP using PHP - php

please, I really need your help. i have problems with uploading files to FTP server with using a PHP form. this form was o.k., but my hosting provider recently changed the version of PHP and from this moment, I have big problems. the communication with database is working, but file transfer not. please, can anyone advise me? thank you very much for your help!
the form:
<? include('./config.php'); ?>
<?
$spojeni = #MySQL_Connect($se, $uz, $he);
$db = #MySQL_Select_DB($DB);
?>
<FORM METHOD="POST" action="ins_info.php" enctype="multipart/form-data">
<TABLE>
<TR><TD><u><b>Upload a file:</b></u></TD></TR>
<TR>
<TD><b>Title:</b></TD>
<TD><INPUT TYPE="TEXT" NAME="titulek_form"></INPUT></TD>
</TR>
<TR>
<TD><b>Date:</b></TD>
<TD><INPUT TYPE="TEXT" NAME="datum_form"></INPUT></TD>
</TR>
<TR>
<TD><b>File:</b></TD>
<TD><INPUT TYPE="FILE" ACCEPT="*/*" SIZE="33" NAME="soubor"></INPUT></TD>
</TR>
<TR>
<TD><INPUT TYPE="SUBMIT" NAME="Odeslat" VALUE="Add to database"></INPUT></TD>
</TR>
</TABLE>
</FORM>
and the file ins_info.php: (the file from a form gets a new name, for example info1234.pdf -- but now is working only writing to a database -- the result is, that I get info1234. (without file on FTP and without filetype in a database)
<? include('./config.php') ?>
<?
#Set_Time_Limit(0);
$INI_ADMIN_PASSWORD = $_GET[INI_ADMIN_PASSWORD];
$INI_ftp_server = $_GET[INI_ftp_server];
$INI_info_path = $_GET[INI_info_path];
$INI_server_info_path = $_GET[INI_server_info_path];
$INI_server_tmp_path = $_GET[INI_server_tmp_path];
$INI_ftp_user = $_GET[INI_ftp_user];
$INI_ftp_pass = $_GET[INI_ftp_pass];
$spojeni_ftp = $_GET[spojeni_ftp];
$soubor = $_FILES["soubor"]["name"];
$titulek_form = $_POST["titulek_form"];
$datum_form = $_POST["datum_form"];
$DatumInt = $_POST["DatumInt"];
$MaxID = $_POST["MaxID"];
$prenos_info = $_POST["prenos_info"];
$vloz_info = $_POST["vloz_info"];
$jmeno = $_POST["jmeno"];
$vyber2 = $_POST["vyber2"];
$datum2 = $_POST["datum2"];
$nazev = $_POST["nazev"];
$soubor_name = $_POST["soubor_name"];
$cislo = $_POST["cislo"];
$jmeno = $_POST["jmeno"];*
IF($PASSWORD==$INI_ADMIN_PASSWORD):
$spojeni = #MySQL_Connect($se, $uz, $he);
$db = #MySQL_Select_DB($DB);
$vyber2 = #MySQL_Query("SELECT Max(ID) FROM info");
$MaxID = #MySQL_Result($vyber2, 0) +1;
$titulek_form = HTMLSpecialChars($titulek_form);
$datum_form = HTMLSpecialChars($datum_form);
$datum2 = Explode(".", $datum_form);
$DatumInt = MkTime(0,0,0, $datum2[1], $datum2[0], $datum2[2]);
$jmeno = "info";
$i = 1;
do
{
if($i==1) $jmeno_old = $jmeno;
$jmeno = $jmeno_old;
$nazev = Explode(".", $soubor_name);
SRand((double)MicroTime()*1e6);
$cislo = Rand (1, 9999);
// $nazev[0] .= $cislo;
$jmeno .= $cislo.".".$nazev[1];
$i++;
}
While(#File_Exists("$INI_info_path$jmeno"));
$vloz_info = #MySQL_Query("INSERT INTO info VALUES ('$MaxID', '$titulek_form', '$datum_form', '$jmeno', '$DatumInt')");
// *** FTP start
#chdir("$INI_server_tmp_path"); // docasny adresar
$spojeni_ftp = #ftp_connect("$INI_ftp_server"); // pripojeni k FTP serveru
#ftp_login($spojeni_ftp, "$INI_ftp_user", "$INI_ftp_pass"); // prihlaseni k FTP serveru
$prenos_info = #ftp_put($spojeni_ftp, "$INI_info_ftp_path$jmeno", "$soubor", FTP_BINARY); // kam se ma soubor ulozit
#chdir("$INI_server_home_path"); // nastaveni domovskeho adresare
#ftp_close($spojeni_ftp); // odhlaseni od FTP serveru
// *** FTP end
Header("Location: status.php?prenos_info=$prenos_info&vloz_info=$vloz_info");
?>
<?
ELSE:
Echo "<p>Error</b></p>";
ENDIF;
?>
folders have 777 rights. I'm be doubtful about POST and GET methods in the beginning of the file.

Related

Updating new image still showing the old image

(I wanted to upload a new image with the same name as previous.
All code is working well...
but when i try to fetch image it show the previous image)
Any Solution????
Mysql Table
My Code
<?php
include "nav.php";
$id = $_GET['id'];
$id = base64_decode($id);
$q = "select * from slider where id =".$id;
include "js.php";
include "db.php";
$r = mysqli_query($con,$q);
$row = mysqli_fetch_assoc($r);
?>
<div style = "width:70%;margin-left:13%;">
<form method = "post" enctype="multipart/form-data">
<br>
<center>
<input type = "text" value="<?php echo $row["text"];?>" name = "title" placeholder="Title" style = "width:100%;" required>
<br>
<br>
<input type="file" name = "m" class="form-control-file" accept="image/x-png,image/gif,image/jpeg" id="exampleFormControlFile1" required>
<input class = "btn btn-primary" type = "submit" name = "submit" value="Submit">
</center>
</form>
</div>
<?php
if(isset($_POST["submit"])){
$t =$_POST['title'];
$allow = array('jpg');
$temp =explode(".",$_FILES['m']['name']);
$extension= end($temp);
$newfilename=$row['id'] .".".$extension;
if($extension=="jpg")
{
$upload_file=$newfilename;
move_uploaded_file($_FILES['m']['tmp_name'] , "slider/".$upload_file);
}
else
{
echo "<script>alert('Image should be in jpg');</script>";
exit();
}
$q = "update slider set text= '".$t."' where id= ".$row['id'];
$r = mysqli_query($con,$q);
header('location:slider.php');
exit();
}
?>
'''
Here how can i use unlink funtion????
or can any one me the code to delete the old image and create and upload a new image with the same name
if you need to update the image in ftp but with the same name in database, first fetch the data from the database for that row and store the value of the image in a variable like this :
// write your sql query here
$upload_file=$old_file_name; // value should be fetch from database.
then unlink the image from the ftp using:
unlink('/path/imagename.png'); // set your path and change the name and extension
once you unlink the image upload the new image and remove while uploading it. so it can remove existing file from ftp and upload new image with old name.
here is the solution .....
(It will delet the old pic and upload the new one in folder....)
<?php
//delet the previous img
unlink("slider/" . $oldimage);
// If upload button is clicked ...
if (isset($_POST['submit'])) {
// Get image name
$title=$_POST['title'];
$filename = $_FILES['image']['name'];
$filetmpname = $_FILES['image']['tmp_name'];
//folder where images will be uploaded
$folder = 'slider/';
//function for saving the uploaded images in a specific folder
move_uploaded_file($filetmpname, $folder.$filename);
//inserting image details (ie image name) in the database
$sql = "UPDATE slider SET image='$filename',text='$title' where id=$id";
$qry = mysqli_query($con, $sql);
if( $qry) {
echo "</br>image uploaded";
}header('Location:slider.php');
}
?>
got uploading idea from here
https://medium.com/#mauricemuteti2015/how-to-upload-and-insert-image-into-mysql-database-using-php-and-html-32633a06d372

mikehaertl/phpwkhtmltopdf wrapper - Works when running PHP file from command line

I have made the following file:
test.php
<?php
require 'vendor/autoload.php';
use mikehaertl\wkhtmlto\Pdf;
$htmlString = <<<EOT
<!DOCTYPE html>
test
</html>
EOT;
$pdf = new Pdf($htmlString);
$pdf->setOptions(array(
'orientation' => 'landscape'
));
$pdf->saveAs('new.pdf');
?>
When I run from the command line (Ubuntu 12.x):
sudo php test.php
I get a file that shows up in my directory and works as intended. However now take the following file where I am trying to apply the above to a real world scenario - note: when I echo $htmlString I get a valid and expected string.
testPDF.php
<?php
// Start session and check if user is logged in
session_start();
if(!isset($_SESSION['permission']))
{
die('Please login.');
}
// Dependencies
require 'vendor/autoload.php';
use mikehaertl\wkhtmlto\Pdf;
require 'database.php';
// Initialize
$client = $db->real_escape_string($_GET['client']);
$start_date = $db->real_escape_string($_GET['start_date']);
$end_date = $db->real_escape_string($_GET['end_date']);
$jobs = array();
$htmlString = '';
// Get list of jobs from DB & save to array
$query = "SELECT somecolumns FROM mydatabase WHERE start_date > '{$start_date}' AND end_date < '{$end_date}' AND client = '{$client}'";
if(!$result = $db->query($query))
{
die('There was an error running the query [' . $db->error . ']');
}
while($r = mysqli_fetch_assoc($result))
{
$jobs[] = $r;
}
// Loop through jobs array and formulate HTML string
foreach($jobs as $value)
{
$id = $value['id'];
$name = $value['name'];
$tech = $value['tech'];
$time_closed = $value['time_closed'];
$time_total = $value['time_total'];
$time_charged = $value['time_charged'];
$description = $value['description'];
$htmlString = $htmlString . <<<EOT
<h4 style="text-align: center;">{$id} - {$name}</h5>
<table id="simple-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="width: 180px;">Date</th>
<th>Description</th>
<th style="width: 50px;">Duration</th>
<th style="width: 150px;">Time Charged</th>
<th style="width: 150px;">Technician</th>
</tr>
</thead>
<tbody id="jobs_start">
<tr>
<td>{$time_closed}</td>
<td>{$description}</td>
<td>{$time_total}</td>
<td>{$time_charged}</td>
<td>{$tech}</td>
</tr>
</tbody>
</table>
EOT;
}
$pdf = new Pdf($htmlString);
$pdf->setOptions(array(
'orientation' => 'landscape'
));
$pdf->saveAs('new.pdf');
?>
When I try to run the above by browsing to testPDF.php as a logged in user, I get nothing. No file is generated and no error/warning in the error logs. I've tried using $pdf->send() as well but no success.
My initial thought that this is a permissions issue, however I've tried setting testPDF.php to owner root and permission 755 but it still does not resolve the issue.
The issue is that when sending a HTML string to the pdf object, it looks for the tag to determine if it's html.
The first example has a HTML tag, while the 2nd file does not have any html tag thus is fails, silently.
https://github.com/mikehaertl/phpwkhtmltopdf/blob/master/src/Pdf.php

Hiding url in php error

I am trying to hide video (videos/mymovie.mp4) URL so as to make video downloading difficult. I am using session id and video path to get a encrypted token. Below is my code for sublime player (video.php).
<?php
include('movie_url.php');
echo '<video id="'.$movieId.'" class="sublime" poster="'.$cover_image_path.'" width="935" height="526" title="'.$movie_title.'" data-autoresize="fit" preload="none">
<source src="moviesessionurl.php?video='.$hash.'" />
</video>';
?>
movie_url.php contains
<?php
//Connect to database
include("config.php");
session_start();
$sid = session_id();
$movieId = $_SESSION['movie_id'];
$sql = "SELECT * FROM `movies` WHERE intMovieID = ".$movieId;
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_row($result);
$movie_title = $row[1];
$movie_desc = $row[7];
$trailer_path = $row[8];
$movie_path = $row[9];
$cover_image_path = $row[10];
$still_image_path = $row[11];
$poster_image_path = $row[12];
$movie_duration = $row[16];
$hash = md5($movie_path.$sid);
$_SESSION[$hash] = $movie_path;
mysqli_close($con);
?>
And moviesessionurl.php contains
<?php
/* start the session */
session_start();
$path = $_SESSION[$_GET['video']];
echo $path;
?>
when i run the moviesessionurl.php directly in browser i get the correct video url. But when I run video.php which contains sublime player the video doesn't play! Gives the error "Cant play video"
Please help me get this done.
That won't work, it is looking for video content at the url moviesessionurl.php I would reccomend fetching the url through an AJAX request. Then dynamically creating the video element once the URL has been retreived.

Loading an image from a MySQL database with PHP

I have a question about loading an image from a MySQL database.
I have my database set up named 'demo' with one table 'contacts'. This has the 4 columns 'id', 'name', 'email' and 'image'. I can insert images with a HTML page I created. I also can achieve all my information with another HTML page I created, but the inserted BLOB images won't pop up, instead I see some huge bunch of characters (seems to besome encoding/decoding problem).
Heres the php-script that should get the data:
<?php
/*db information*/
$localhost="localhost";
$username="riko";
$password="QdTkCd12!";
$database="demo";
/*connect to database*/
mysql_connect($localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
/*prepare query*/
$query="SELECT * FROM contacts";
/*execute query*/
$result=mysql_query($query);
/*Number of rows delivered*/
$num=mysql_numrows($result);
/*Closing connection*/
mysql_close();
?>
<!-- Create a table to hold the data -->
<table border="1">
<tr>
<th>Image</th>
<th>Name</th>
<th>E-Mail</th>
</tr>
<?php
//Iterating over all rows in our table
$i=0;
while ($i < $num) {
//Get the first name, last name, mail and the image from the result
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$email=mysql_result($result,$i,"email");
$data =mysql_result($result,$i,"image");
?>
<tr>
**HERE I WANT TO ECHO THE IMAGE INTO MY TABLE BUT I ONLY GET A BUNCH OF CHARACTERS**
<td><img src="<?php echo $data ?>" height="100" width="100"></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $first." ".$last; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif">E-Mail
</tr>
<?php
$i++;
}
?>
Can anyone tell me where my fault is? This is the php-script where I insert the images:
<?php
$localhost="localhost";
$username="riko";
$password="QdTkCd12!";
$database="demo";
$first=$_POST['first'];
$last=$_POST['last'];
$email=$_POST['email'];
mysql_connect($localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO contacts VALUES ('','$first','$last','$email', '$data')";
mysql_query($query);
mysql_close();
}
header("Location: connect.php");
die();
?>
I really don't know what's wrong here.
I think you need to prefix the value in the src attribute with content information:
echo '<img src="data:image/png;base64,' . $data . '" />';
Make sure the database blob field contains base64 encoded data.

Converting HTML in PHP File to PDF File [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have a php file which queries a database and then writes and updates the html accordingly.
I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:
FPDF error: Unable to create output file: Entry Report
I suspect the problem is because I am passing a php file instead of a html file:
<?php
require('html2fpdf.php');
if(isset($_POST['link'])){
$url = $_POST['link'];
$nm = $_POST['nm'];
convert($url, $nm);
}
function convert($link, $name){
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen($link,"r");
$strContent = fread($fp, filesize($link));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output($name);
echo ("PDF file generated successfully!");
}
?>
Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...
Or is there a direct way to convert a php file into a pdf file...
EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...
I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?
Here is the php page:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
$sectionTwo = array();
$sectionThree = array();
$sectionFour = array();
$sectionFive = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$section = $row['sectionId'];
switch($section){
case '1':
$sectionOne[] = $row;
break;
case '2':
$sectionTwo[] = $row;
break;
case '3':
$sectionThree[] = $row;
break;
case '4':
$sectionFour[] = $row;
break;
case '5':
$sectionFive[] = $row;
break;
default:
break;
}
}
}else{
//error - sql failed
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("Testers/viewentryreport.php");
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
?>
<h3>Fatigue and Recovery</h3>
<?php
foreach($sectionTwo as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Illness and Injury</h3>
<?php
foreach($sectionThree as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Training Sessions</h3>
<?php
foreach($sectionFour as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>General Feedback</h3>
<?php
if(count($sectionFive)>0){
foreach($sectionFive as &$value){
echo($value['question'].' : '.$value['answer']);
}
}else{
$sectionFive = "User didn't leave any feedback";
echo("User didn't leave any feedback");
}
echo("<br/>");
?>
</body>
</html>
<?php
}
?>
and html2pdfconverter.php
<?php
require('html2fpdf.php');
if(isset($_POST['link'])){
$url = $_POST['link'];
$nm = $_POST['nm'];
convert($url, $nm);
}
function convert($link, $name){
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen($link,"r");
$strContent = fread($fp, filesize($link));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output($name);
echo ("PDF file generated successfully!");
}
?>
EDIT #TIMFERRIS
I changed my convert function to this based on #TimeFerris' answer:
function convert($link, $name){
$pdf=new HTML2FPDF();
$pdf->AddPage();
$content = file_get_contents( $link ); //shorter than what you did
ob_start();
echo $content;
$pdf->WriteHTML( ob_get_contents() );
ob_end_clean();
$pdf->Output($name);
echo ("PDF file generated successfully!");
}
The PDF file is created but still blank
I recently done this by using TCPDF. TCPDF is a further developed version of FPDF.
See this link for an expample regarding converting to PDF. Also, here you can find more examples. Example 61 could also come in quite handy.
Sample code which TCPDF uses:
$html = '<h1>HTML Example</h1>
<div style="text-align:center">IMAGES<br />
<img src="../images/logo_example.png" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/tiger.ai" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/logo_example.jpg" alt="test alt attribute" width="100" height="100" border="0" />
</div>';
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
One thing that you could do is run the PHP file, but use output buffering to capture the contents that the PHP script is writing out. Then, save those contents to an .html file and pass that file to the converter.
The php file you are supplying has to run through a parser before it's valid html code.
$content = file_get_contents( $filename ); //shorter than what you did
ob_start();
echo $content;
$pdf->WriteHTML( ob_get_contents() );
ob_end_clean();

Categories