I want to save a image file to server folder and save its path to mysql - mysql

The problem is that the image is not moved to UPLOAD_DIR path, but the path of that file is successfully inserted in server.
<?php
$con=require_once("connection.php");
define('UPLOAD_DIR', 'http://hpms.hostei.com/images/');
$image= $_REQUEST['image']; //byte image data received
$image = str_replace('data:image/png;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);//
print $success ? $file : 'Unable to save the file.';
$code=0;
if($r=mysql_query("insert into images values('','$file')"))
{
$code=1;
}
print(json_encode($code));
mysql_close();
?>

Hi awais khan sar,
You can use the $_FILES server variable. $_REQUEST is used for GET and POST both method
but you are uploading images i have also this problem and solved with this type. you can
create post method from any mobile device then save it into folder using
move_uploaded_file() if any query then tell me, Thanks Hiren kubavat.

Related

phpmyadmin import csv file. How to skip error line

I´m trying to import about 3gb csv files to phpmyadmin. Some of them contains more terminated chars and then importing stops because of wrong fields.
I have two colums which i want to fill. Im using : as terminanting char but when there is more of them in line it just stops. I cannot manage csv files they are too big. I want to skip error lines or look for other solutions. How can i do this ?
csv files looks like this
ahoj123:dublin
cat:::dog
pes::lolko
As a solution to your problem, I have written a simple PHP file that will "fix" your file for you ..
It will open "test.csv" with contents of:
ahoj123:dublin
cat:::dog
pes::lolko
And convert it to the following and save to "fixed_test.csv"
ahoj123:dublin
cat:dog
pes:lolko
Bear in mind that I am basing this on your example, so I am letting $last keep it's EOL character since there is no reason to remove or edit it.
PHP file:
<?php
$filename = "test.csv";
$handle = fopen($filename, "r+") or die("Could not open $filename" . PHP_EOL);
$keep = '';
while(!feof($handle)) {
$line = fgets($handle);
$elements = explode(':', $line);
$first = $elements[0];
$key = (count($elements) - 1);
$last = $elements[$key];
$keep .= "$first:$last";
}
fclose($handle);
$new_filename = "better_test.csv";
$new_handle = fopen("fixed_test.csv", "w") or die("Could not open $new_filename" . PHP_EOL);
fwrite($new_handle, $keep);
fclose($new_handle);

Unable to open file for reading [filename.pdf] yii2 swiftmailer

I am trying to send an email with attachment when I used var_dump($filename)it returns the filename and gettype($filename) it returns string. but when I am trying to send an attachment it still returns Unable to open file for reading [filename.pdf] even if $file_attachment was looped I tried to change UploadedFile::getInstancesByName('file_attachment'); to UploadedFile::getInstanceByName('file_attachment'); but nothing happened. Please help me.
This is my controller
if(Yii::$app->request->isPost){
$email = Yii::$app->request->post('email');
$message = Yii::$app->request->post('message');
$file_attachment = UploadedFile::getInstancesByName('file_attachment');
if($file_attachment){
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message);
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach($filename);
}
//$mail->send();
//echo gettype($filename);
// var_dump($filename);
$mail->send();
}else{
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message)
->send();
}
}
This is the view
<?php
echo FileInput::widget([
'name' => 'file_attachment',
'attribute' => 'file_attachment',
'options' => ['multiple' => true]
]);
?>
The baseName property of yii\web\UploadedFile contains the original filename but the file is not present on the server under its original filename. You need to use tempName property that contains path to the uploaded file on server.
Your for each cycle that attaches files to mail should look like:
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach(
$file->tempName,
['fileName' => $filename]
);
}
It might also be a good idea to check hasError property of yii\web\UploadedFile before attempting to attach file to see if the upload was successful.
Also make sure that you've set 'enctype' => 'multipart/form-data' in you form options when you are not using ActiveForm with ActiveField::fileInput() otherwise the files might not be uploaded.

display BLOB pdf directly on webpage as download link

I have a table in MySQL database. It consists of many columns. The last column is BLOB column and it is storing pdf files. I want to call particular columns of the table. The BLOB column is the last one. I want the <td> elements to say Download and on click of the anchor tag I want the pdf to get downloaded. Somebody please help. The values of the Copy Column is going to be pdf files.
$result= mysql_query("SELECT Name, Type, No, Copy from table1 Join table2 where username='{$_SESSION['username']}' AND table1.UserID=table2.UserID") or die(mysql_error());
$fields_num = mysql_num_fields($result);
echo "<table class='table table-hover'>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Number</th>";
echo "<th>Copy</th>";
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>".$row['Name']."</td><td>".$row['Type']."</td><td>".$row['No']."</td><td>"."<a href=''>Download</td></tr>";
}
}
echo "</table>";
Usually I save my files in a folder and just adding the path into a column in my database and to download I use the following PHP code.
I call it downloadPop_Up.php:
<?php
$data = $_REQUEST['data'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
//header("Content-disposition: attachment; filename=\"" . basename($data) . "\"");
header("Content-disposition: attachment; filename=\"" . basename($data) . "\"");
readfile($data);
?>

Number of times a file (e.g., PDF) was accessed on a server

I have a small website with several PDFs free for download. I use StatCounter to observe the number of page loads. It also shows me the number of my PDF downloads, but it considers only those downloads where a user clicks on the link from my website. But what's with the "external" access to the PDFs (e.g., directly from Google search)? How I can count those? Is there any possibility to use a tool such as StatCounter?
Thanks.
.htaccess (redirect *.pdf requests to download.php):
RewriteEngine On
RewriteRule \.pdf$ /download.php
download.php:
<?php
$url = $_SERVER['REQUEST_URI'];
if (!preg_match('/([a-z0-9_-]+)\.pdf$/', $url, $r) || !file_exists($r[1] . '.pdf')) {
header('HTTP/1.0 404 Not Found');
echo "File not found.";
exit(0);
}
$filename = $r[1] . '.pdf';
// [do you statistics here]
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"$filename\"");
readfile($filename);
?>
You can use a log analyzer to check how many times a file was accessed. Ask you hosting provider if they provide access to access logs and a log analyzer software.
in php, it would be something like (untested):
$db = mysql_connect(...);
$file = $_GET['file'];
$allowed_files = {...}; // or check in database
if (in_array($file, $allowed_files) && file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
mysql_query('UPDATE files SET count = count + 1 WHERE file="' . $file . '"')
readfile($file);
exit;
} else {
/* issue a 404, or redirect to a not-found page */
}
You would have to create a way to capture the request from the server.
If you are using php, probably the best would be to use mod_rewrite.
If you are using .net, an HttpHandler.
You must handle the request, call statcounter and then send the pdf content to the user.

Why is this Perl CGI script failing to upload images correctly?

I have this code:
use CGI;
use File::Basename;
use Image::Magick;
use Time::HiRes qw(gettimeofday);
my $query = new CGI;
my $upload_dir = "../images"; #location on our server
my $filename=$query->param("img");
my $timestamp = int (gettimeofday * 1000);
my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' );
$filename = $name ."_".$timestamp. $extension;
#upload the image
my $upload_filehandle =$query->param("img");
open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!";
binmode UPLOADFILE;
while ( <$upload_filehandle> )
{
print UPLOADFILE;
}
close UPLOADFILE;
Then I do resize for the image. My problem is that the image is not uploaded. I have an empty file having the name of $filename. I omitted the part related to resize and I still have the code. So I'm sure that the file is not being uploaded correctly. Am I missing any library?
Any help?Plz..
You need to change
my $upload_filehandle =$query->param("img");
to
my $upload_filehandle =$query->upload("img");
according to this tutorial.
Hope it helps.
I figured out why: As pointed out in the CGI.pm docs, the form's encoding type must be multipart/form-data. When I added that, everything worked.
added this "ENCTYPE='multipart/form-data'" instead of encoding.
> <form action="/post.pl" method="post" ENCTYPE='multipart/form-data'>
and it worked