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
Related
window.addEventListener("load", () => {
var uploader = new plupload.Uploader({
runtimes: "html5",
browse_button: "upload",
url: "../upload.php",
chunk_size: "10mb", // <<<<<<< Here is my problem
filters: {
max_file_size: "100gb",
.... THIS CODE HERE DOESN'T MATTER .....
});
This is my upload.php
function verbose ($ok=1, $info="") {
if ($ok==0) { http_response_code(400); }
exit(json_encode(["ok"=>$ok, "info"=>$info]));
}
if (empty($_FILES) || $_FILES["file"]["error"]) {
verbose(0, "Failed to move uploaded file.");
}
$filePath = __DIR__ . DIRECTORY_SEPARATOR . "videos";
if (!file_exists($filePath)) { if (!mkdir($filePath, 0777, true)) {
verbose(0, "Failed to create $filePath");
}}
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
$dateformat = date("Y-m-d-H:i:s");
$fileSize = $_FILES["file"]["size"]; // <<<<< HERE IS MY PROBLEM
$title = pathinfo($fileName,PATHINFO_FILENAME);
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$out = #fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
$in = #fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
}else{
echo "err";
}
#fclose($in);
#fclose($out);
#unlink($_FILES['file']['tmp_name']);
}else{
verbose(0, "Failed to open output stream");
}
if (!$chunks || $chunk == $chunks - 1) {
$rename = 'videos/'.generateKey($pdo); // simple function to generate random string ( 123asdjjn124 and so on)
$databaseName = str_replace('videos/','', $rename); // remove videos/ from the string
rename("{$filePath}.part", $rename);
$stmt = $pdo->prepare("INSERT INTO videos(title,size,date,link) VALUES(:title,:size,:date,:link)");
$stmt->bindParam(':title',$title,PDO::PARAM_STR);
$stmt->bindParam(':size',$fileSize,PDO::PARAM_STR); // <<<<< HERE IS MY PROBLEM
$stmt->bindParam(':date',$dateformat,PDO::PARAM_STR);
$stmt->bindParam(':link',$databaseName,PDO::PARAM_STR);
$stmt->execute();
}
verbose(1, "Upload OK");
Now when I upload a file, everything is entered beautifully but the size of the "chunk_size" is always entered instead of the correct size of the file. Does anyone have an idea why this is so? It also makes no difference if I change the file size, it always takes the "chunk_size".
Any advice is helpful
Here I have another screenshot to illustrate how I mean it. https://prnt.sc/QW-zXtrb6RuY
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
my view looks:
<form action="<?php echo site_url('Admin/addBrandsProcess'); ?>" class="dropzone" >
</form>
my Controller looks:
public function addBrandsProcess()
{
$query = $this->db->query('SELECT width, height FROM brandimage');
foreach ($query->result() as $row)
{
$width= $row->width;
$height= $row->height;
}
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$targetPath = getcwd() . './assets/images/brand/';
$targetFile = $targetPath . $fileName ;
move_uploaded_file($tempFile, $targetFile);
$config['image_library'] = 'gd2';
$config['source_image'] = $targetPath . $fileName ;
$config['overwrite'] = TRUE;
$config['create_thumb'] = FALSE;
$config['thumb_marker'] = '_thumb';
$config['maintain_ratio'] = FALSE;
$config['width'] = $width;
$config['height'] = $height;
$config['quality'] = '100%';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$this->db->insert('brands',array('image' => $fileName));
}
}
This code working well in local server, but not in live server. Here my problem is image is not uploaded to the target folder. Here the image name is get saved in the table brands. But image is not uploaded in the target path $targetPath = getcwd() . './assets/images/brand/';.
How can I solve this problem. What all changes have to make.
I am developing a smart tv app that plays live streams. App itself works fine, when i provide a valid xml playlist to it.
But when i use php to generate xml file (wich also generates fine), it doesnt work.
I get an error:
TypeError: 'null' is not an object (evaluating 'this.XHRObj.responseXML.documentElement')
Here is my php file that generates videoList.xml, it works 100%.
In short words, this script checks if MAC address in database, and if it is, then it writes videoList.xml with walid live streaming links.
SamsungAPI.php
<?php
$MAC = $_GET['MAC'];
require_once('../config.php');
//Remove brackets form array
$_INFO = preg_replace('/[{}]/', '', $_INFO);
$mysqli = new mysqli($_INFO['host'], $_INFO['db_user'], $_INFO['db_pass'], $_INFO['db_name']);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="SELECT * FROM users WHERE admin_notes = '$MAC' ";
$rs=$mysqli->query($sql);
$rows=mysqli_num_rows($rs);
if ($rows == 1) {
//MAC FOUND
$row = mysqli_fetch_array($rs);
$username = $row['username'];
$password = $row['password'];
$file = "videoList.xml";
$txt_file = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . '/get.php?type=starlivev3&username=' . $username . '&password=' . $password . '&output=hls');
$rows = explode("\n", $txt_file);
if(empty($rows[count($rows)-1])) {
unset($rows[count($rows)-1]);
$rows=array_map('trim',$rows);
}
$handle = fopen($file, "w+") or die('Could not open file');
fwrite($handle, "<?xml version=\"1.0\"?>"."\n");
fwrite($handle, "<rss version=\"2.0\">"."\n");
fwrite($handle, "<channel>"."\n");
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(',', $data);
//replace _ with spaces
$row_data[0] = str_replace('_', ' ', $row_data[0]);
//generate playlist content
fwrite($handle, "<item>"."\n");
fwrite($handle, "<title>{$row_data[0]}</title>"."\n");
fwrite($handle, "<link>{$row_data[1]}</link>"."\n");
fwrite($handle, "<description> Reserved for EPG </description>"."\n");
fwrite($handle, "</item>"."\n");
}
fwrite($handle, "</channel>"."\n");
fwrite($handle, "</rss>");
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
//MAC NOT FOUND
echo "MAC NOT FOUND";
}
mysqli_close($mysqli); // Closing Connection
?>
Then in samsung smart tv videoplayer app, i have xml parser like this:
Server.js
var Server =
{
/* Callback function to be set by client */
dataReceivedCallback : null,
XHRObj : null,
url : "http://myvalidhost.com/samsungAPI.php?MAC=02000027000b"
}
Server.init = function()
{
var success = true;
if (this.XHRObj)
{
this.XHRObj.destroy(); // Save memory
this.XHRObj = null;
}
return success;
}
Server.fetchVideoList = function()
{
if (this.XHRObj == null)
{
this.XHRObj = new XMLHttpRequest();
}
if (this.XHRObj)
{
this.XHRObj.onreadystatechange = function()
{
if (Server.XHRObj.readyState == 4)
{
Server.createVideoList();
}
}
this.XHRObj.open("GET", this.url, true);
this.XHRObj.send(null);
}
else
{
alert("Failed to create XHR");
}
}
Server.createVideoList = function()
{
if (this.XHRObj.status != 200)
{
Display.status("XML Server Error " + this.XHRObj.status);
}
else
{
var xmlElement = this.XHRObj.responseXML.documentElement;
if (!xmlElement)
{
alert("Failed to get valid XML");
}
else
{
// Parse RSS
// Get all "item" elements
var items = xmlElement.getElementsByTagName("item");
var videoNames = [ ];
var videoURLs = [ ];
var videoDescriptions = [ ];
for (var index = 0; index < items.length; index++)
{
var titleElement = items[index].getElementsByTagName("title")[0];
var descriptionElement = items[index].getElementsByTagName("description")[0];
var linkElement = items[index].getElementsByTagName("link")[0];
if (titleElement && descriptionElement && linkElement)
{
videoNames[index] = titleElement.firstChild.data;
if(linkElement.firstChild.data.substring(0,4) !="http"){
alert("asdasdasd "+linkElement.firstChild.data.substring(0,4));
var rootPath = window.location.href.substring(0, location.href.lastIndexOf("/")+1);
var Abs_path = unescape(rootPath).split("file://")[1]+linkElement.firstChild.data;
videoURLs[index] = Abs_path;
}
else{
videoURLs[index] = linkElement.firstChild.data;
}
videoDescriptions[index] = descriptionElement.firstChild.data;
}
}
Data.setVideoNames(videoNames);
Data.setVideoURLs(videoURLs);
Data.setVideoDescriptions(videoDescriptions);
if (this.dataReceivedCallback)
{
this.dataReceivedCallback(); /* Notify all data is received and stored */
}
}
}
}
Does anyone have any idea why doesnt it accept my generated xml file?
Regards
M
I figured it out, in php headers content type was wrong.
Changed
header('Content-Type: application/octet-stream');
to
header('Content-Type: application/xml');
Now it works perfect!
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>';
}
}