PHP & ZipArchive() - Failed to load PDF document - javascript

Good afternon, i have a form that in determined field it open a window or windows to display a specific PDF. The folder where is the path, it can there is just a PDF or a ZIP file with multiples PDF's inner according to the input filled value.
This is blur() event part on the whole my code that calls the windows and pass the values to the "arquivo.php" and "pdf.php", one is to check if is just a PDF or a ZIP, if was a PDF this return on my form informing that is a PDF just and after open just a window to display, this part is ok
JavaScript/HTML code:
///////////PASS THE VALUES TO "arquivo.php"////////////////
$.post("arquivo.php", {nprocesso: document.getElementById("processo").value}, function(data){
$( "#content3" ).html( data ); /*<-- return in this content if is a PDF or a ZIP(when is a zip it returns how many PDF's there are inner ZIP file too)*/
////////////THIS PART IS TO CREATE JUST A WINDOW OR MULTIPLES WINDOWS PASSING THE VALUES RETURNED IN THE "content3" TO "pdf.php" TO DISPLAY IT/THEM//////////////////
setTimeout(function(){
if(document.getElementById("content3").innerText == "PDF"){
window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}else{
var QuantPDF = Number(document.getElementById("content3").innerText.slice(Number(document.getElementById("content3").innerText.lastIndexOf(','))+1, document.getElementById("content3").innerText.length));//Number(document.getElementById("content3").innerText.replace(/[^0-9]/g, ""));
var NomesPDFS = []; NomesPDFS = document.getElementById("content3").innerText.slice(3, document.getElementById("content3").innerText.length-2).split(',');
if(QuantPDF > 1){
for(var i = 0; i < QuantPDF; i++){
window.open("pdf.php/"+document.getElementById("processo").value+"/"+NomesPDFS[i], '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}
}else{
window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}
}
document.getElementById('closeBtn').click();
}, 1000);
}
This is the "arquivo.php", where check if is just a PDF or a ZIP file, and extract if was a zip
Arquivo.php code:
<?php
session_start();
//////////THIS PART CHECK THAT FILE IS A PDF AND RETURN TO MY JAVASCRIPT CODE/////////
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.pdf')){
echo 'PDF';
$_SESSION['file'] = "PDF";
}else{
//////////THIS PART CHECK THAT FILE IS A ZIP AND RETURN TO MY JAVASCRIPT CODE/////////
echo 'ZIP';
$_SESSION['file'] = "ZIP";
$zip = new ZipArchive;
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.zip';
///////////////////////////////////////////////////////////////////
if($zip->open($path) === true){
//////////THIS PART IT OPENS THE ZIP AND EXTRACT/////////
if(!file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'])){
mkdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], 0777, true);
}
for($i = 0; $i < $zip->numFiles; $i++){
$zip->extractTo('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], array($zip->getNameIndex($i)));
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
$files = scandir($path); array_shift($files); array_shift($files);
$file = array(); $filename = array();
///////NOW I CATCH THE PDF's NAMES AND THE QUANTITY AND RETURN TO JAVASCRIPT CODE///////
$file[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
$filename[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
$nomes_pdfs = array();
$nomes_pdfs[$i] = substr(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), 0, strpos(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), '.pdf')).',';
echo $nomes_pdfs[$i];
}
$zip->close();
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
$files = scandir($path);
array_shift($files); array_shift($files); $_SESSION['quantidade_pdf'] = count($files);
echo $_SESSION['quantidade_pdf'];
}
}
?>
My problem actually is partially on "pdf.php" where the window load with the values returned of the "content3". When is a single PDF, the window display normally, but when is a ZIP file with multiples PDF's, the first PDF display correctcly, but starting in the second and on, it doesn't display. show a this error: "Failed to load PDF document".
pdf.php code:
<?php
header ('Content-type: text/html; charset=utf-8');
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf') && is_file('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf')){
$processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
$file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
$filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}else{
/////////////////////HERE IS THE PART WHEN IS A ZIP////////////////////////
///////*This part it's only to check if the folder extract exists*/////////
function folder_exist($folder){ $path = realpath($folder); return ($path !== false AND is_dir($path)) ? $path : false; }
chdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/');
$folder = '/'.substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/')).'/';
if(FALSE !== ($path = folder_exist($folder))){
/////*Here start the part where the code catch the PDF's and display*/////
$pasta = substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/'));
$processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
$file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
$filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}else{
die('<h2 style="background-color:#FA5858"><center>Não foi encontrado a inicial do processo. Verifique se o mesmo encontra-se na pasta.</center></h2>');
}
}
?>
What i'm doing wrong ? I've already checked the folder, the file is in and the name and the path is the same that the code are putting to display

Related

Returning array values (image file names to javascript) from php

Hi I have a php file which is reading all the image files in a directory as so:
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
and I want to get the resulting array in javascript. This code is not working. Any idea why?
<script type = "text/javascript">
$(function() {
$.getJSON('fileNames.php', function(data) {
console.log('yaa');
$(data).each(function(key, value) {
console.log(value);
});
});
});
</script>
getJson performs an ajax call, which will read the contents of the file as its written/displayed, so your echo "filename:" . $file . "<br>"; is becoming part of that meaning your json is becoming invalid
comment out that line and you should be fine
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
//echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
The method wants nothing but valid json to be echo'd/displayed

IIS8+PHP+samba folder can t read or write on folder

So basically i build an webpage(php+js) on xampp that lets users fill a form and in that form they can upload multiple images.
The site was working fine so i upload it to production on the server with IIS8.
The form works great but i cant upload or view the images i uploaded.
The images are being uploaded to a samba drive, in xampp i had no issue it worked how it was suppose too on IIS I'm getting an error saying i don't have permissions. i don't know what I'm doing wrong
this is the code to get the images
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['id'])){
$id = $_POST['id'];
$directory = '\\\\server\\'.$id.'\\';
$directory = '\\\\server\\'.$id.'\\';
$local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
$img_arr = array();
if($local){
$x=1;
}else{
$x=0;
}
foreach($local as $item)
{
$image = $item;
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
$img_arr [] = array('mime'=> mime_content_type($image),'imgDt'=> $imageData);
}
}
if ($x==0){
$response = [
'status'=>'falhou',
'values' => $local
];
}else{
$response = [
'status'=>'sucesso',
'values' => $img_arr
];
}
header('Content-Type: application/json');
echo json_encode($response);
?>
and this is the code to add images
if (!file_exists('\\\\server\\'.$tmstp)) {
mkdir('\\\\server\\'.$tmstp);
}
$uploadDir = '\\\\server\\'.$tmstp.'\\';
if(!empty($_FILES['anex'])){
foreach ($_FILES['anex']['name'] as $key=>$ficheiro) {
$fileName = basename($_FILES['anex']['name'][$key]);
$tmpname = $_FILES['anex']['tmp_name'][$key];
$targetFilePath = $uploadDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
$allowTypes = array('jpg', 'png', 'jpeg', 'gif');
if(in_array($fileType, $allowTypes)){
if(file_exists($targetFilePath)) {
//chmod($targetFilePath,0755); //Change the file permissions if allowed
unlink($targetFilePath); //remove the file
}
if(move_uploaded_file($tmpname, $targetFilePath)){
$uploadedFile = $fileName;
if ($i=0){
$anex=$fileName;
$i++;
$uploadStatus = 1;
$hf=true;
}
else{
$anex=$anex .';' . $fileName;
$uploadStatus = 1;
$hf=true;
$rspimg = 'Upload fotos com sucesso';
}
}else{
$uploadStatus = 0;
$rspimg = 'Ouve um erro com o UPLOAD das imagens';
}
}else{
$uploadStatus = 0;
$rspimg = 'Só JPG, JPEG, PNG ou GIF';
}
}
}else{
$hf = false;
}
i already tried creating a virtual folder on IIS and it still doesn't work

JavaScript Search bar to display results after user input

I have a webpage that displays a list of my local files, and I have a search bar that goes through the list of files and highlights the first match.
However, how can I display the files only when a user searches for a filename. So instead of all the files showing, I'd only like the files that match the search criteria to be returned.
PHP, JavaScript, jQuery is totally an option here if anyone can help in that area.
testexec.php:
<?php
$path = '/var/www/html/'; //get list of files
$files = scandir($path);
//display the links
foreach($files as $file) {
if($file != '.' && $file != '..') {
echo '<div> '.$file.'</div>';
}
}
?>
readfile.php:
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($filename);
exit;
}
?>
//JavaScript for searchbar
function FindNext() {
var str = document.getElementById ("livesearch").value;
if (str == "") {
alert ("Please enter some text to search!");
return;
}
var supported = false;
var found = false;
if (window.find) { // Firefox, Google Chrome, Safari
supported = true;
// if some content is selected, the start position of the search
// will be the end position of the selection
found = window.find (str);
} else {
if (document.selection && document.selection.createRange) { // Internet Explorer, Opera before version 10.5
var textRange = document.selection.createRange ();
if (textRange.findText) { // Internet Explorer
supported = true;
// if some content is selected, the start position of the search
// will be the position after the start position of the selection
if (textRange.text.length > 0) {
textRange.collapse (true);
textRange.move ("character", 1);
}
found = textRange.findText (str);
if (found) {
textRange.select ();
}
}
}
}
if (supported) {
if (!found) {
alert ("The following text was not found:\n" + str);
}
}
else {
alert ("Your browser does not support this example!");
}
}
This is the simplest idea.
Frontend
index.html
$('input').keydown(function(e) {
var str = $(this).val();
alert(str);
$.get("/search.php?query=" + str, function(data) {
$('.result').html(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>File search and download</h3>
<input name="filename" placeholder="file name" class="kw"/>
<div class="result">
</div>
Backend
search.php
<?php
// You need code search file
// after search $files
$str = '';
foreach($files as file) {
$str .= ''.$file.' <br>'
}
return $str;
?>
readfile.php
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($filename);
exit;
}
?>
this really easy. you just need to use event keyup and some code fix
index.php
<input type="text" id="searchbar" placeholder="search file"> <span id="loading" style="display:none;">loading</span>
<div id="result"></div>
<script src="../../vendor/jquery/jquery-3.2.1.min.js"></script>
<script>
$(function(){
$('#searchbar').keyup(function(){//event after user release keyboard
var val = $(this).val();
if(val.length >= 2){//min 2 words to start find
$.ajax({
url: 'search.php',
type: 'POST',
dataType: 'json', //we use json
data: {keyword: val},
beforeSend: function(){
$('#loading').show();
},
success: function(d){
if(d.ok==1){
$('#result').html(d.list);
}else{
alert(d.msg);
}
$('#loading').hide();
},
error: function(d){
alert('error');
$('#loading').hide();
}
});
}
})
});
</script>
search.php
<?php
$path = 'C:/xampp/htdocs/';
$keyword = isset($_POST['keyword']) ? $_POST['keyword'] : '';
$scan = scandir($path);
$result = array('ok'=>0); //prepare output cz we will use json instead text/html
if($scan !== false){
$result['ok']=1;
$list = array();
foreach($scan as $file){
if(is_file($path.$file)){ //only file
if(preg_match('/'.$keyword.'/', $file)) //is file containts keyword?
$list[] = '<div>'.$file.'</div>';
}
}
$result['list'] = count($list) == 0 ? 'no file match': $list;
}else
$result['msg'] = "failed open dir";
echo json_encode($result);
readfile.php
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
$path = 'C:/xampp/htdocs/';
$fullPath = $path.$filename; //you need this
if (file_exists($fullPath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fullPath));
readfile($fullPath);
exit;
}
?>
There are many ways to do that.
I would suggest that:
Make your PHP answer a JSON with the files that match a given criteria. So you will ask to the PHP, passing in POST data ou QUERY string the "text" that is being search. It will give you only the files that matches.
In you html file (could be another PHP as well), you will call ajax (you can use jQuery) to the page above everytime user changes the search text. It's good thing to "throttle" (see lodash/underscore library) (wait some time waiting for more key presses).
After receiving the JSON with the files that matches, build dynamically you table (or another way you want).
search.php:
<?php
header('Content-Type: application/json');
$path = '/var/www/html/'; //get list of files
$files = scandir($path);
$search = $_GET['search'];
$links = array();
foreach ($files as $file) {
if($file != '.' && $file != '..' && strpos(strtolower($file), strtolower($search)) !== false) {
array_push($links, array(
"name" => $file,
"url" => "readfile.php?file=" . urlencode($file)
));
}
}
echo json_encode($data);
?>
index.php / index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-2.2.4.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js">
</head>
<body>
<input id="searchbox" type="text" placeholder="search for files" />
<div id="results">
</div>
<script>
$(function () {
var searchbox = $("#searchbox");
var results = $("#results");
var doSearch = _.throttle(function () {
var searchtext = searchbox.val();
$.ajax({
type: 'get',
url: 'search.php',
dataType: "json",
data: {
search: searchtext
}
}).done(function (response) {
results.html(response.reduce(function (html, item) {
return html + '<div>' + item.name + '</div>';
}, ''));
});
}, 200);
searchbox.on('keydown', doSearch);
});
</script>
</body>
</html>

Ajax (Form Submission) Calls back Error function

I have a "contact us" form and everything is working but my error callback in the ajax runs instead of the success. I ajax is called, the PHP file runs, and I get an email to my localhost (using Mercury).
So why is my success callback not running? I have no idea how to find out what is causing the error especially since everything works.
The only thing I suspect is the file folders. The current structure is this. My html file and php file are in the root directory. The JS file is in a folder.
Here is a screenshot of the network tab in chrome debugger after I press submit
http://i.imgur.com/HfRYjj0.png
My Ajax:
$(document).ready(function(e) {
$("#main-contact-form").on('submit', (function(e) {
e.preventDefault();
$('#sendingemail').fadeIn();
$.ajax({
url : "../sendemail.php",
type : "POST",
data : new FormData(this),
contentType : false,
cache : false,
processData : false,
success : function(data) {
$('#sendingemail').fadeOut();
$('#emailsent').fadeIn();
},
error : function() {
alert("Error");
}
});
}));
});
My PHP:
<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL);
header('Content-type: application/json');
// WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
// WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:
/*$status = array(
'type'=>'Error',
'message'=>'Couldn\'t send the Email at this Time. Something went wrong',
'attachement'=>'Couldn\'t attach the uploaded File to the Email.'
);*/
//Added to deal with Files
require_once ('PHPMailer/class.phpmailer.php');
if (isset($_FILES['uploaded_file'])) {
//require_once('/PHPMailer/class.smtp.php');
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"] / 1024;
//size in KBs
//Settings
$max_allowed_file_size = 10240;
// size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "png");
//Validations
if ($size_of_uploaded_file > $max_allowed_file_size) {
$errors .= "\n Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
}
//------ Validate the file extension -----
$allowed_ext = false;
for ($i = 0; $i < sizeof($allowed_extensions); $i++) {
if (strcasecmp($allowed_extensions[$i], $type_of_uploaded_file) == 0) {
$allowed_ext = true;
}
}
if (!$allowed_ext) {
$errors .= "\n The uploaded file is not supported file type. " . " Only the following file types are supported: " . implode(',', $allowed_extensions);
}
//copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
$upload_folder = "temp/";
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if (is_uploaded_file($tmp_path)) {
if (!copy($tmp_path, $path_of_uploaded_file)) {
$errors .= '\n error while copying the uploaded file';
}
}
}
//--end
$name = #trim(stripslashes($_POST['name']));
$clientemail = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$email = new PHPMailer();
$email -> From = $clientemail;
$email -> FromName = $name;
$email -> Subject = $subject;
$email -> Body = $body;
$email -> AddAddress('root#localhost.com');
//Send to this email
// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION
$email -> isMail();
// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...
if (isset($_FILES['uploaded_file'])) {
if ($email -> AddAttachment($path_of_uploaded_file, $name_of_uploaded_file)) {
//$status[] = 'The Uploaded File was successfully attached to the Email.';
}
}
// NOW, TRY TO SEND THE EMAIL ANYWAY:
try {
$success = $email -> send();
//$status['type'] = 'success';
$status[] = 'Thank you for contacting us. We will reply as soon as possible.';
} catch(Exception $e) {
//$status['type'] ='Error';
$status[] = 'Couldn\'t send the Email at this Time. Something went wrong';
}
// SIMPLY, RETURN THE JSON DATA...
die(json_encode($status));

Image upload with ajax and php is failing (no error log)

The following code I'm using to upload images is failing for some reason...
Here is the HTML
<form id="image_upload" enctype="multipart/form-data" action="uploadImage.php" method="post" name="prof_picture">
<input id="image1" style="display:none;" name="image" accept="image/jpeg" type="file">
<input id="image2" value="Submit" type="submit" style="display:none;">
</form>
PHP (uploadImage.php)
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name'][0]);
echo $filename;
$size=filesize($_FILES['image']['tmp_name'][0]);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'][0], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}
JS
$('#image1').on('change', function() {
$("#image").attr('src',"profile/loading.gif");
$("#image_upload").ajaxForm({
target: '#image'
}).submit();
});
What I know for sure:
1º The php script is being achieved correctly because I failed part of the code on purpose and attained an error message regarding an internal php error.
2º The query is being done correctly (or at least by its syntax).
3º The javascript function related to #image is also working.
I only want to upload one image that the user selects (even if he selects 100 other items). But as I said, I don't even get an error message on the log... Any ideas on this one? Thank you very much!
EDIT
I've changed the code a bit
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)){
if ($size < (MAX_SIZE*1024)){
$image_name=time().$user_id."--pfi-".$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname)){
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}else echo '<span class="imgList">This message appears </span>';
}else echo '<span class="imgList">You have exceeded the size limit!</span>';
}else echo '<span class="imgList">Unknown extension!</span>';
For some reason it now stops at if(move_uploaded_file($_FILES['image']['tmp_name'], $newname)). I've var_dump'ed this and it is indeed "false" but I can't get to understand why. Here is var_dump($_FILES):
array(1) { ["image"]=> array(5) { ["name"]=> string(21) "060424_hubble_big.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpZYaDkm" ["error"]=> int(0) ["size"]=> int(35641) } }
EDIT 2
Warning:
move_uploaded_file(profile/uploads/1388794617.png):
failed to open stream: No such file or directory in
profile/uploadProfilePicture.php on line 37
Warning: move_uploaded_file(): Unable to move '/tmp/phppFfoL4' to
'profile/uploads/1388794617.png' in
profile/uploadProfilePicture.php on line 37
how should I specify $uploaddir or even $newname?
Edit
This is what I used. Notice the commented out conditional statements.
<?php
// include('../sqlconnection.php');
define ("MAX_SIZE","1000000000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
// if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
// {
$uploaddir = "profile/uploads/"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
// mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
// }
Original answer
Ok, I found the problem. Remove all [0] in your PHP and it will now work. Those are used for arrays and since you're only using it for single file uploads, is why it failed.
Sidenote: You may want to add a / at the end of $uploaddir = "profile/uploads"; as in $uploaddir = "profile/uploads/";
The following doesn't have the [0]'s and have tested it as pure PHP with no JS.
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}

Categories

Resources