I am trying to create thumbnails from pdf uploads using Imagick. I wrote a script that's supposed to do it, but, it only uploads the file without creating a thumbnail.
This will certainly make some of you roll your eyes, but, PHP is completely uncharted territory to me. Could anyone help me out? Thanks!
<?php
include 'includes/session.php';
include 'includes/slugify.php';
if(isset($_POST['add'])){
$name = $_POST['name'];
$slug = slugify($name);
$category = $_POST['category'];
$price = $_POST['price'];
$description = $_POST['description'];
$filename = $_FILES['photo']['name'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$allowed = array('pdf', 'doc', 'docx', 'odc', 'jpg');
$conn = $pdo->open();
$stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM products WHERE slug=:slug");
$stmt->execute(['slug'=>$slug]);
$row = $stmt->fetch();
if($row['numrows'] > 0){
$_SESSION['error'] = 'document already exists';
}
else{
if(!in_array($ext, $allowed)) {
$_SESSION['error'] = 'Filetype not allowed';
}
else{
if(!empty($filename)){
$new_filename = $slug.'.'.$ext;
copy($_FILES['photo']['tmp_name'], '../documents/'.$new_filename);
}
else{
$new_filename = '';
creating a thumbnail
$img = new Imagick($filename[0]);
$img-> setImageFormat('jpg');
$convert = $slug. '.' .$jpg;
$img-> writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert);
}
try{
$stmt = $conn->prepare("INSERT INTO products (category_id, name, description,
slug, price, photo) VALUES (:category, :name, :description, :slug, :price, :
photo)");
$stmt->execute(['category'=>$category, 'name'=>$name,
'description'=>$description,
'slug'=>$slug, 'price'=>$price, 'photo'=>$new_filename]);
$_SESSION['success'] = 'document added successfully';
}
catch(PDOException $e){
$_SESSION['error'] = $e->getMessage();
}
}
}
$pdo->close();
}
else{
$_SESSION['error'] = 'Fill up product form first';
}
header('location: documents.php');
?>
It looks like your call to $img->writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert) is incorrect: you're passing two strings (the filename of an uploaded image and what looks like a destination filename) but the Imagick documentation indicates you should be passing only a destination filename (along with an optional Boolean).
So this:
$img-> writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert);
Should probably be:
$img-> writeImages('../images/'.$convert);
Also, it's hard to tell whether the two chunks of PHP that you posted come one after the other, but if they do, then your logic for when to create the images looks faulty:
if(!empty($filename)){
// Do some stuff
} else {
// Write the images
}
The problem here is that the block of code that writes the images only executes when $filename is empty. Shouldn't it write the images if $filename is not empty?
Last but not least, the Imagick writeImages() function returns a Boolean indicating whether it was successful. You should store this result and log it to see what the result is. You should also confirm that your destination filename ('../images/'.$convert) is correct, and that the path exists and is writable.
Related
I have a process for deleting post entries in a PHP app. I want to delete the image associated with the post, if an image exists.
The post itself is deleted from the database successfully, but the image is not deleted from the image folder.
Here's delete_post.php:
if (isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
if (isset($_POST['result'])) {
if ($_POST['result'] == 'true') {
$delete_img = $pdo->prepare("SELECT image FROM posts WHERE id = ?");
$delete_img->execute([$post_id]);
$img_row = $delete_img->fetch();
$img = $img_row['image'];
if (file_exists($img)) {
unlink($img);
}
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$post_id]);
}
}
}
...the form handler
<?php include '../../inc/config.php';
if (isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
if (isset($_POST['result'])) {
if ($_POST['result'] == 'true') {
$delete_img = $pdo->prepare("SELECT * FROM posts WHERE id = ?");
$delete_img->execute([$post_id]);
$img_row = $delete_img->fetch();
$filename = $_SERVER['DOCUMENT_ROOT']. '/' .$img_row['image'];
if (file_exists($filename)) {
unlink($filename);
}
$get_gallery_img = $pdo->prepare("SELECT * FROM files WHERE post_id = ?");
$get_gallery_img->execute([$post_id]);
while ($row = $get_gallery_img->fetch()) {
$galleryName = $_SERVER['DOCUMENT_ROOT'] . '/' . $row['file_name'];
unlink($galleryName);
}
$delete_gallery = "DELETE FROM files WHERE post_id = ?";
$stmt = $pdo->prepare($delete_gallery);
$stmt->execute([$post_id]);
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$post_id]);
}
}
}
...and the Javascript that executes the form handler.
<script>
$(document).ready(function() {
$('#post<?=$id?>').on('click', function() {
bootbox.confirm("Are you sure you want to delete this post?", function(result){
$.post("inc/form_handlers/delete_post.php?post_id=<?=$id?>", {result:result});
if(result) {
location.reload();
}
});
});
});
</script>
I've tried moving the statement for deleting the image to just below the $_GET['post_id'] if statement, as well as just below the the $_POST['result'] if statement. I know it needs to be above the delete post statement since the path to the image is in the image column of the database - neither worked.
I have tried the unlink statement in another PHP file to make sure that it works - it does. So far I haven't found where I am going wrong, but I continue to look.
Since I'm still new to both PHP I am not sure where I should focus, or more to the point, what I am missing.
In case it helps someone else it was a path issue. Here's the final PHP:
if (isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
if (isset($_POST['result'])) {
if ($_POST['result'] == 'true') {
$delete_img = $pdo->prepare("SELECT * FROM posts WHERE id = ?");
$delete_img->execute([$post_id]);
$img_row = $delete_img->fetch();
$filename = $_SERVER['DOCUMENT_ROOT']. '/' .$img_row['image'];
unlink($filename);
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$post_id]);
}
}
}
The part to note is $filename = $_SERVER['DOCUMENT_ROOT']. '/' .$img_row['image']; - using document root was the missing link.
I hope this helps any with a similar issue.
i am using filedrop.js fo an Image Upload Script.
I fund a script here : https://tutorialzine.com/2011/09/html5-file-upload-jquery-php
In the Prject is a file_post.php which i wanted to change to save some informations (like the Filename) into a Database.
This is my post_file.php :
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/tmp/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
//My added code
include('/var/www/html/board/SSI.php');
$userName = $context['user']['name'];
$content_id = $_COOKIE["contentid"];
$pic_name = $pic['name'];
$pic_code = $content_id;
$pic_path = $pic_name;
$db_host = "******";
$db_name = "******";
$db_user = "******";
$db_pass = "******";
$db = mysqli_connect("$db_host","$db_user","$db_pass","$db_name") or die("Error " . mysqli_error($db));
$stmt = $db->prepare("INSERT INTO `User_pics` (content_id, path, user_id, user_name) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $pic_code,
$pic_path,
$context['user']['id'],
$context['user']['name']);
$stmt->execute();
$stmt->close();
//end of my added code
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
After i added the mysqli part the Success message is not shown anymore.
On the Image Upload the Progressbar stops at about 50%. The files are Uploaded and the informations are ssaved into the DB, but i got no success respons and this i need to handle the next steps. pleas help!
Thanks.
thanks for interrests,
two days i worked fo a soulution, after i asked here i found the Answer ;)
The Problem was the Include of the SSI.php which is encoded in UTF-8.
This was the reason for an Error in the Json encoded Response.
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
My soulution was:
I created a cookie for User ID and User name so i was able to remove the Include. After this every thing works great. If someone has the Same Error simply create a cookie where you are showing your Upload Form, after Upload delet them.
Thanks to the Community and have a nice Day ;)
Recently I am learning single page application, but I got a problem, the project I am working on is inside a folder that contain many folders, php js are folders in side the main folder, and each contain its type of files, the problem is that one of the php file called getmax.php gives me the maximum id ,I want to use this max(id) in a js file called module.js in order to give the new module the next id , the module.js should gives this id to another php file called insert.php ,the connection between the module.js and insert.php is working properly if I set the id manually . but I could not figure out how can I make it use the max(id) from the getmax.php file.
note: I noticed lately I'm using MySQL and I should used mysqli I will fix it later.
the getmax.php is:
<?php
// alle relevanten Tabellen abfragen und als json zurückgeben.
$json["status"] = "running";
$details[] = "started get_tables ";
// Include confi.php
include_once('confi.php');
//var_dump($_POST);
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];
$username = $user["username"];
$password = $user["password"];
if($password and $username){
$mySQLstring = "SELECT username, password, id, create_user FROM tbl_user where username = '$username' ;";
$json["statement"][] = $mySQLstring;
$qur = mysql_query($mySQLstring);
//var_dump ( $qur );
if ($qur){
$max = mysql_fetch_assoc($qur);
}
if ($max){
$json["max"] = $max;
if ($max["password"] == $password){
$json["username"] = $username;
$json["id"] = $max["id"];
$json["create_user"] = $max["create_user"];
$json["status"] = "ok";
$tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
//$tables = array("class");
foreach($tables as $table){
if ( $table == 'module' ){
$statement ='SELECT create_user, MAX(id) FROM tbl_'.$table;
//$statement .= ' GROUP BY create_user' ;
$statement .= ' WHERE create_user = 19 ' ;
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
}
$json = array("status" => "ok", "data" => $result);
}
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
PHP and JS are run on the server and client respectively, and as such you cannot call methods/functions of one from the other. AJAX exists to pass values between JS and serverside code.
I'm trying to log some data for my website using PDO from a PHP file. I have the following code which is called by by a javascript library, D3. The call works fine, but when I run this code I get an "internal server error".
What am I doing wrong? I have been following a guide on a website and I am basically using the same principles as them. If anyone can help I'd appreciate it. Thanks a lot in advance, my code is pasted below. (Of course the database information is something valid)
$hostname="xxxx";
$username="xxxxxx";
$pw="xxxxxxxx";
$dbname="xxxx";
try {
$pdo = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
//Gets IP for client.
$ip = get_client_ip();
//An email, format of string.
$email = "test#test.dk";
//An int, in this case 19.
$prgm_name = $_GET["prgm"];
//Piece of text, format of string of course.
$prgm_options.=$prgm_name;
$prgm_options.= " - ";
$prgm_options.=$_GET["gene"];
$prgm_options.=" - ";
$prgm_options.=$_GET["data"];
//Datasize, int.
$data_size = 0;
//Timestamp.
$now = "NOW()";
//Table name.
$STAT_TABLE = "stat";
$query = $pdo->prepare("INSERT INTO $STAT_TABLE (ip, email, prgm, options, datasize, date) VALUES (:ip, :email, :prgm_name, :prgm_options, :data_size, :now);");
$query->execute(array( ':ip'=>'$ip',
':email'=>'$email',
':prgm_name'=>$prgm_name,
':prgm_options'=>'$prgm_options',
':datasize'=>'$datasize',
':now'=>$now));
Try the following Code to Insert
$count = $pdo->exec("INSERT INTO $STAT_TABLE(ip, email, prgm, options, datasize, date) VALUES ('$ip','$email',$prgm_name,'$prgm_options','$datasize',$now)))");
/*** echo the number of affected rows ***/
echo $count;
I like to bind each parameter individually. I think it gives you more control over data types and sizes.
try {
$sth = $pdo->prepare("INSERT INTO...");
$sth->bindParam(":ip", $ip, PDO::PARAM_STR, 16);
$sth->bindParam(":email", $email, PDO::PARAM_STR, 30);
// etc...
$sth->execute();
} catch (Exception $e) {
print_r($e);
}
Basically I am trying to create a photo slideshow that will display specific photos depending on the userid. These photos will be stored in the directory of my web server space. Currently I have a html (not changed into php) file with basic html layout, css style sheet and an external js file that has my code that makes the photos fade in and out. I have added php at the bottom of my html. This is what I have:
$user_id = $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
and in my javscript, the code I had before for the array of photos:
// List of images for user one
var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";
which I have now commented out and replaced it with this:
var userphoto = <? echo json_encode($galleryarray); ?>;
I am hoping to be able to change the src of photodisplay with the new array:
photodisplay[x].attr("src", userphoto[x]);
Sorry if my problem is not clear at all. I am very confused myself. :( hopefully someone can help!
$user_id = (int) $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") {
$dirname = str_replace('..', '.', $dirname); //only remove this if you know why it's here
$pattern = "*{.jpg,.png,.jpeg,.gif}"; //valid image extensions
return glob($dirname . DIRECTORY_SEPARATOR . $pattern, GLOB_BRACE);
}
echo "var galleryarray = ".json_encode(returnimages()).";\n";
?>
Also, you should use <?= json_encode($ret) ?> because the PHP short tag (<?) is deprecated, but <?= is not, and is the equivalent of <?php echo.