PHP mkdir doesn't make new directories - php

I'm trying to make a new directory to handle profile pictures, but every time I upload the image, nothing happens as in the new directory is not created and there are no errors whatsoever. I already checked the Apache error log, but didn't notice any error pertaining to my recent code...
Here's a sample of my code
//profile image upload script
if (isset($_FILES['profile_pics'])) {
if (((#$_FILES["profile_pics"] ["type"] == "image/jpeg" || (#$_FILES["profile_pics"] ["type"] == "image/png") || (#$_FILES["profile_pics"] ["type"] == "image/gif")) && (#$_FILES["profile_pics"] ["size"] < 1048576)) ) // LESS THAN ONE MEGABYTE
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$rand_dir_name = substr(str_shuffle($chars), 0, 15);
mkdir("userdata/profile_pics/$rand_dir_name");
else {
}
}
}

You have multiple errors in your PHP, are you sure you did not see any FATAL errors in your apache logs?
Your if query does not close properly
Your else statement is missing a braket
You're suppressing any errors with # - remove them!
Use an absolute path instead of relative path to avoid errors in where you're creating the directory
Here's an example of how it should look:
// array of valid image types
$valid = array( 'image/jpeg', 'image/png', 'image/gif' );
if (isset($_FILES['profile_pics'])) {
// if the file type is in the valid array and the size is less than 1MB
if ( in_array($_FILES['profile_pics']['type'], $valid)
&& ($_FILES["profile_pics"]["size"] < 1048576) )
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$rand_dir_name = substr(str_shuffle($chars), 0, 15);
mkdir($_SERVER['DOCUMENT_ROOT'] . "/userdata/profile_pics/$rand_dir_name");
} else {
print( 'too big or not an image.' );
}
}
EDIT
You should also check the mkdir response.. like this:
$ok = mkdir($_SERVER['DOCUMENT_ROOT'] . "/userdata/profile_pics/$rand_dir_name");
if( !$ok )
{
print('error creating directory, check your permissions');
} else {
print('created directory successfully!');
}

Try to add permission.
mkdir("/path/", 0755);

Related

Video with size greater than 100 mb gets corrupted after chunk upload using php

I am trying to upload videos having file sizes from anywhere between 1 MB to 2 GB from the Unity3D editor. I am doing this by breaking each video into chunks of a byte array of 10 MB each and then uploading the chunks to the local wamp server and then merging them back into one single file. I am labeling each chunk with a serial number based on the queue and all the chunks are uploaded one by one, with the next upload only starting after the first is completed and is successful.
On the server-side, my PHP script looks like this:
define("CHUNK_FILE_EXTENSION", ".part");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$folder_name = isset($_POST['folder_name']) ? trim($_POST['folder_name']) : '';
$target_file_name = isset($_POST['target_file_name']) ? trim($_POST['target_file_name']) : '';
$chunkByteArray = isset($_FILES['chunk_byte_array']) ? $_FILES['chunk_byte_array'] : '';
$currentChunkNumber = isset($_POST['current_chunk_number']) ? trim($_POST['current_chunk_number']) : '';
$totalChunksNumber = isset($_POST['total_chunks_number']) ? trim($_POST['total_chunks_number']) : '';
$startMerge = isset($_POST['start_merge']) ? trim($_POST['start_merge']) : '';
$totalFileSize = isset($_POST['total_file_size']) ? trim($_POST['total_file_size']) : '';
$startRollback = isset($_POST['start_rollback']) ? trim($_POST['start_rollback']) : '';
function targetFileDirectoryPath($folder_name) {
//$tempDir = $_SERVER['DOCUMENT_ROOT']."\\media\\temp\\test\\%s";
$tempDir = $_SERVER['DOCUMENT_ROOT']."\\media\\temp\\test";
return sprintf($tempDir, $folder_name);
}
function chunksFileDirectoryPath($folder_name) {
return CombinePath(targetFileDirectoryPath($folder_name), "chunks");
}
function mergeChunkFiles($targetFileName, $chunkFileDir, $targetFileTempPath) {
$files = array_diff(scandir($chunkFileDir), array('.','..',$targetFileName));
sort($files);
$final = fopen($targetFileTempPath, 'w');
foreach ($files as $file) {
$filePath = CombinePath($chunkFileDir, $file);
if(($filePath != $targetFileTempPath) && (filesize($filePath) > 0)) {
$myfile = fopen($filePath, "r");
$buff = fread($myfile,filesize($filePath));
$write = fwrite($final, $buff);
fclose($myfile);
}
}
fclose($final);
}
if (!empty($currentChunkNumber) && !empty($totalChunksNumber) && !empty($chunkByteArray)) {
$chunkFileDir = chunksFileDirectoryPath($folder_name);
$chunkFilePath = CombinePath($chunkFileDir, $currentChunkNumber.CHUNK_FILE_EXTENSION);
$tempPath = $chunkByteArray['tmp_name'];
if (createDirectory($chunkFileDir)) {
if(move_uploaded_file($tempPath, $chunkFilePath)) {
$responseJson = array(
"status" => 1,
"message" => $currentChunkNumber." uploaded successfully"
);
}
else {
$responseJson = array(
"status" => 2,
"message" => $currentChunkNumber." not uploaded to ".$chunkFilePath." from ".$tempPath,
"uploaded_chunk_file" => $chunkByteArray,
"is_uploaded_file" => is_uploaded_file($tempPath)
);
}
}
else {
$responseJson = array(
"status" => 3,
"message" => "Chunk file user directory not created # ".$chunkFileDir
);
}
}
else if (!empty($startMerge) && !empty($totalFileSize)) {
$targetFileName = $target_file_name;
$chunkFileDir = chunksFileDirectoryPath($folder_name);
$targetFileTempDir = NormalizePath(targetFileDirectoryPath($folder_name));
$targetFileTempPath = CombinePath($targetFileTempDir, $targetFileName);
if(createDirectory($targetFileTempDir)) {
mergeChunkFiles($targetFileName, $chunkFileDir, $targetFileTempPath);
removeFolder($chunkFileDir);
if (filesize($targetFileTempPath) == $totalFileSize) {
$responseJson = array(
"status" => 1,
"message" => "Target file saved successfully!"
);
}
else {
$responseJson = array(
"status" => 2,
"message" => "Target file size doesn't match with actual file size. ".
"Please try again! Target File Size: ".filesize($targetFileTempPath).
" & Input File Size: ".$totalFileSize);
}
}
else {
$responseJson = array(
"status" => 3,
"message" => "Unable to create target directory for merging chunks # ".$targetFileTempDir
);
}
}
else if (!empty($startRollback)) {
$responseJson = array(
"status" => 4,
"message" => "Rollback successful!"
);
}
else {
$responseJson = array(
"status" => 0,
"message" => "Invalid request parameters!!"
);
}
}
else {
$responseJson = array(
"status" => 0,
"message" => "Invalid request method!!"
);
}
/* Output header */
header('Content-type: application/json;charset=utf-8');
echo json_encode($responseJson, JSON_UNESCAPED_UNICODE);
//Remove folder and its inner folder and files at the input path
function removeFolder($folder) {
if (empty($folder)) {
return;
}
$folder = NormalizePath($folder);
if(is_file($folder)) {
unlink($folder);
}
else if(is_dir($folder)) {
$files = scandir($folder);
foreach($files as $file) {
if (( $file != '.' ) && ( $file != '..' )) {
$file = CombinePath($folder, $file);
if(is_dir($file)) {
removeFolder($file);
}
else {
unlink($file);
}
}
}
rmdir($folder);
}
}
//Check if directory is exist return true, else create new directory and returns bool
function createDirectory($directoryPath) {
$directoryPath = NormalizePath($directoryPath);
if(!is_dir($directoryPath)) {
return mkdir($directoryPath, 0775, true);
}
else {
return true;
}
}
//Method to combine local file or folder paths using a DIRECTORY_SEPARATOR
function NormalizePath($path)
{
//normalize
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
$path = str_replace('\\', DIRECTORY_SEPARATOR, $path);
//remove leading/trailing dir separators
if(!empty($path) && substr($path, -1) == DIRECTORY_SEPARATOR) {
$path = substr($path, 0, -1);
}
return $path;
}
//Method to combine local file or folder paths using a DIRECTORY_SEPARATOR
function CombinePath($one, $other, $normalize = true)
{
//normalize
if($normalize) {
$one = NormalizePath($one);
$other = NormalizePath($other);
}
//remove leading/trailing dir separators
if(!empty($one)) {
$one = rtrim($one, DIRECTORY_SEPARATOR);
}
if(!empty($other)) {
$other = ltrim($other, DIRECTORY_SEPARATOR);
}
//return combined path
if(empty($one)) {
return $other;
} elseif(empty($other)) {
return $one;
} else {
return $one.DIRECTORY_SEPARATOR.$other;
}
}
?>
It works for videos less than 100 MB, but somehow the videos greater than 100 MB does not play properly. I am testing it in local wampserver and upload_max_filesize and post_max_size are set to 20M in php.ini.
I have tried varying the chunk size to 5 MB, but still the same issue. The video gets uploaded successfully and I can also see the video filesize exactly the same as the one on the clientside, but still, somehow it gets corrupted in case of uploading a bigger video.
Just to re-iterate, it somehow works for videos less than 100 MB. As in, the videos are broken into chunks of 10 MB raw bytes uploaded to localhost and merged back to the full file and the video plays as good as the original one.
What am I doing wrong here? Please help.
Edit:
Not sure if it might help, but I checked error in the video file using ffmpeg on the uploaded video that was of 106 MB. Below is the command I executed:
ffmpeg -v error -i {video_file_path} -f null - 2>{error_log_file_path}
Here is the error log file:
https://drive.google.com/file/d/1YQ0DNtNlhl4cLUJaw20k91Vv6tfjnqsX/view?usp=sharing
On the server side, you read in the chunks completely into memory before you write out your target file. This approach is limited by PHPs maximum memory usage. It is configured via the memory_limit setting, that has a default of 128MB. You will need some memory for other things besides the actual final file as well, so the seen limit of ~ 100 MB looks as if it is a result of this limitation. (See the link, it also contains docs how to increase the limit.)
But increasing the memory limit is not a good solution in my opinion, because your server will not have endless memory. I recommend one of the following solutions:
use rsync - it is widely used, available for many operating systems, often even preinstalled and you would not have to fiddle around with splitting up and rejoining the big files. I'm not an expert in it's usage and there are enough tutorials available so I will not explain the correct usage in detail. It is also super fast.
if you cannot use rsync for whatever reason, you should write out the chunks to the disk on the server as soon as you receive them. You will have to ensure the correct order on upload (which will make parallel uploads for chunks of the same file not really feasible), and you have to use the fopen mode "a" (for append) instead of "w".
if you upload the part-files individually and store them as part-files on disk on the server, for Linux you could just use the cat command (abbrevation of con_cat_enate) or for Windows the copy command with the + parameter to join the part files into one big one.
i don't know exactly what is wrong with your script, but i can theorize:
you're using "w" and "r" fopen modes, they're horrible in theory, and if you're running on Microsoft Windows, they're horrible in practice as well, use "wb" and "rb", perhaps your files are getting corrupted beacuse of your non-binary fopen modes? (but that doesn't explain why it works on smaller video files)
you lack error checking on fwrite, if fwrite does not return strlen(input) you're ignoring a potential error. maybe try something like the fwrite_all function from https://www.php.net/manual/en/function.fwrite.php#125731
you also lack error checking on fread, at no point after $buff = fread($myfile,filesize($filePath)); do you make sure that strlen($buff) === filesize($filePath)
i had several problems uploading 10MB on ubuntu+php-fpm+nginx, nginx's default client_max_body_size was 1M, php-fpm's default php.ini upload_max_filesize was 8M, and post_max_size was 2M (or maybe it was the other way around, either way...)
buuuut your script is kind of hard to debug/read nonetheless, how about a Kiss simpler implementation?
my attempt:
Warning, there is no authentication to this code, and a hacker could easily pwn your webserver with this code, uploading evil.php as a "movie".
<?php
declare(strict_types = 1);
function jsresponse($response)
{
header("Content-Type: application/json");
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
}
if ($_SERVER['REQUEST_METHOD'] !== "POST") {
http_response_code(405);
jsresponse(["error" => "invalid request method"]);
die();
}
$folder_name = isset($_POST['folder_name']) ? trim($_POST['folder_name']) : '';
if (empty($folder_name)) {
$folder_name = getcwd();
} elseif (!is_dir($folder_name) && !mkdir($folder_name, 0755, true)) {
http_response_code(400);
jsresponse(["error" => "could not create folder name"]);
die();
}
if (!chdir($folder_name)) {
http_response_code(400);
jsresponse(["error" => "could not access folder"]);
die();
}
$target_file_name = isset($_POST['target_file_name']) ? trim($_POST['target_file_name']) : '';
if (empty($target_file_name)) {
http_response_code(400);
jsresponse(["error" => "target file name is empty"]);
die();
}
if (!touch($target_file_name)) {
http_response_code(400);
jsresponse(["error" => "could not touch target file"]);
die();
}
if (empty($_FILES['chunk_byte_array']['tmp_name'])) {
http_response_code(400);
jsresponse(["error" => "chunk byte array is missing"]);
die();
}
// todo: ram-optimize with stream_copy_to_stream(), this is a very ram-hungry way of appending
$bytes_to_append = file_get_contents($_FILES['chunk_byte_array']['tmp_name']);
if (strlen($bytes_to_append) !== $_FILES['chunk_byte_array']['size']) {
// should never happen
http_response_code(500);
jsresponse(["error" => "could not read chunk byte array file.."]);
die();
}
$bytes_appended = file_put_contents($target_file_name, $bytes_to_append, FILE_APPEND | LOCK_EX);
if (strlen($bytes_to_append) !== $bytes_appended) {
http_response_code(500);
jsresponse(["error" => "could not append all bytes!",
"data" => ["bytes_to_append" => strlen($bytes_to_append), "bytes_actually_appended" => $bytes_appended,
"error_get_last" => error_get_last()]]);
}
jsresponse("success!");
testing it:
$ pwd
/temp
$ b3sum John.Wick3.mp4
2c6445acd31ac3153df52917ca4ab003624377cf50b6e78d0b3c8065d7d2d9f6 John.Wick3.mp4
$ du -h John.Wick3.mp4
2.1G John.Wick3.mp4
$ cat John.Wick3.mp4 | php -r '$i=0;while(!feof(STDIN) && false!==($str=stream_get_contents(STDIN,10*1024*1024))){++$i;file_put_contents("John.Wick3.mp4.part".$i,$str);}'
$ ls | sort -V | head
John.Wick3.mp4
John.Wick3.mp4.part1
John.Wick3.mp4.part2
John.Wick3.mp4.part3
John.Wick3.mp4.part4
John.Wick3.mp4.part5
John.Wick3.mp4.part6
John.Wick3.mp4.part7
John.Wick3.mp4.part8
John.Wick3.mp4.part9
$ cat $(ls | grep -i part | sort -V) | b3sum
2c6445acd31ac3153df52917ca4ab003624377cf50b6e78d0b3c8065d7d2d9f6 -
$ ls | grep -i part | sort -V | xargs --max-args=1 --max-procs=1 '-I{}' curl \
-F folder_name="testfolder" \
-F target_file_name="John.Wick3.mp4" \
-F chunk_byte_array=#"{}" \
http://localhost:81/upload.php
"success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!""success!"
$ du -h /srv/http/default/www/testfolder/John.Wick3.mp4
2.1G /srv/http/default/www/testfolder/John.Wick3.mp4
$ b3sum /srv/http/default/www/testfolder/John.Wick3.mp4
2c6445acd31ac3153df52917ca4ab003624377cf50b6e78d0b3c8065d7d2d9f6 /srv/http/default/www/testfolder/John.Wick3.mp4
$ b3sum John.Wick3.mp4
2c6445acd31ac3153df52917ca4ab003624377cf50b6e78d0b3c8065d7d2d9f6 John.Wick3.mp4
success! uploaded a 2.1GB file with no corruption, as proven by the b3sum being equivalent :) (btw i'm sure there's a better way to split the movie, couldn't think of any though)
I have created a JavaFX client to send large files in chunks of max post size (I am using 2 MB) and a PHP receiver script to assemble the chunks into original file. I am releasing the code under apache license here : http://code.google.com/p/gigaupload/ Feel free to use/modify/distribute.

file uploads script problems

I am having issues with my file uploads script this is the function(jp_upload_pic()) the are i am having issues specifically is the move_uploaded() function, The second parameter "destination" this is my value ("../usr/ceo/JPCEO_20") but this error it is telling me.
Warning: move_uploaded_file(../usr/ceo/JPCEO_20): failed to open stream: No such file or directory in /var/www/jobinpal/includes/func.php on line 1115 Warning: move_uploaded_file(): Unable to move '/tmp/phpgf1k7y' to '../usr/ceo/JPCEO_20' in /var/www/jobinpal/includes/func.php on line 1115
function jp_upload_pic()
{
if (isset($_GET['upload'])) {
$jp_img=$_FILES['file_to_be_uploaded'];
// file uploader for jobinpal...
$jp_img_name=$jp_img['name'];// name of the file
$jp_img_type=$jp_img['type'];
$jp_img_size=$jp_img['size'];
$jp_img_tmp_name=$jp_img['tmp_name'];//$_FILES['userfile']['tmp_name']
$jp_img_err=$jp_img['error'];// the error of the file...
// check if the image post isset before working...
if (isset($jp_img)) {
//do the string of the file name to get the .xxx extension
$jp_img_name_len=strlen($jp_img_name);
$jp_img_ext=substr($jp_img_name ,-4, $jp_img_name_len );
//check the image type of the image
$jp_img_size;
if (
/* file must be any of this format else bounce */
(
($jp_img_ext == '.jpg') ||
($jp_img_ext == '.png') ||
($jp_img_ext == '.gif')
) && ($jp_img_size < 10240)
)
{
//call the session file to get the current user
include("jobinpal_session.php");
$jp_usr_verified_ses=$_SESSION['jp_new_usr'];
//use the user session to create a folder in the 'usr/ceo' folder
//*** pattern for the foldername ***//
//------>>> JPCEO_ID_FILEID
//write a function to ouput from the database if...
//the user is a ceo,staff,student account
//function jp_check_usr_acc()
//{
$jp_usr_verified_ses=$_SESSION['jp_new_usr'];
//*****-----------------------------******//
//----------------------------------------//
//*****-----------------------------******//
include('jobinpal_db_config.php');
$jp_run=$jobinpal_db_lite->query("SELECT account_type,id FROM `jp_user` WHERE email='$jp_usr_verified_ses'");
//$jp_aff_rows=$jobinpal_db_lite->affected_rows;
while ($jp_result=$jp_run->fetch_array(MYSQLI_BOTH)) {
$jp_results[] = $jp_result;
}
foreach ($jp_results as $jp_result) {
$jp_res=$jp_result['account_type'];
$jp_res=strtoupper($jp_res);
$jp_res2=$jp_result['id'];
}
rmdir('../usr/ceo/JPCEO_20');
if (!is_dir("../usr/ceo/"."JP".$jp_res."_".$jp_res2))
{
mkdir("../usr/ceo/"."JP".$jp_res."_".$jp_res2, 0700);
$JP_new_usr_dir="../usr/ceo/"."JP".$jp_res."_".$jp_res2;
$JP_new_usr_dir="JP".$jp_res."_".$jp_res2;
//please i am having issues with the file uploads please put it stackoverflow
//for help...(?)
move_uploaded_file($jp_img_tmp_name,"`../usr/ceo/".$JP_new_usr_dir);
}
//$path=/*"http://".$domain.*/".."."/"."jobinpal"."/"."usr"."/"."ceo"."/".$JP_new_usr_dir;
//move_uploaded_file($jp_img_tmp_name,'../usr/ceo');
//}
//jp_check_usr_acc();
// move the uploaded file to the directory created for the user...
//move_uploaded_file($jp_img_tmp_name,$JP_new_usr_dir);
}
else
{
if (
/* file must be any of this format else bounce */
!
($jp_img_ext == '.jpg') ||
($jp_img_ext == '.png') ||
($jp_img_ext == '.gif')
)
{
echo "<h6 id='img_upload_err'>image must be this extensions (.jpg), (.png), (.gif)<h6>";
return false;
}
}
}
}
}
It looks like a typo:
move_uploaded_file($jp_img_tmp_name,"`../usr/ceo/".$JP_new_usr_dir);
^ is this supposed to be here?
You see the backtick in your error message as well but not in the directory you create and check for.

PHP Uploading images and getting the url

I've been working on a premade image upload template for fun and I'm not too good with php so I can't seem to get around this problem.
I need to be able to extract the direct link to my image (the $upload_dir variable + file extension) so I can use it in my index.php page. I've tried to include my post_file.php file in my index.php but I am getting the Wrong HTTP-method message.
My website is in html5 and it's using the drag-and-drop to initiate the uploading if that is something that messes with my upload file.
post_file.php:
$demo_mode = false;
$upload_dir = 'uploads/'.date(d).rand(0000,9999);
$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!');
}
// Uploads are being ignored, but logged.
if ($demo_mode) {
$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 image,rename it and log it all
if (move_uploaded_file($pic['tmp_name'], $upload_dir.'.'.get_extension($pic['name']))) {
$line = implode(' ', array( date(r), 'http://website.com/'.$upload_dir.'.'.get_extension($pic['name'])));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Upload was successful');
}
}
exit_status('Something went wrong with your upload!');
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);
}
When I use the include('post_file.php') is when I receive the error message, how can I get the new image name + path and extension without including the post_file.php in my index.php file and then echo it in a variable?
Thanks in advance!

PHP Filehandling, code never reached

I've got a piece of code with some error i've been trying to find all day... what this (should) does is: go through all the files in a folder, check if it's a image type, if it is, create a thumbnail in some folder. It does the job BUT: it doesnt continue afterwards, I put a echo command and its never executed. I apprechiate any help! thanks alot.
$bilddateitypen = array('gif','jpg','JPG','GIF');
$importdir = '../sync';
if ($handle = opendir($importdir)) {
while (($file = readdir($handle)) !== false) {
if (!is_dir($importdir."/".$file) && is_file($importdir."/".$file)) {
$ex = explode('.',$file);
if(in_array($ex[count($ex)-1], $bilddateitypen)) {
$file = utf8_decode($file);
$thumbnail = new thumbnail($importdir."/".$file);
$thumbnail->jpeg_quality(93);
$thumbnail->save("../shop/images/product_images/original_images/".$file);
$thumbnail->size_auto(500);
$thumbnail->save("../shop/images/product_images/popup_images/".$file);
$thumbnail->size_auto(200);
$thumbnail->save("../shop/images/product_images/info_images/".$file);
$thumbnail->size_auto(112);
$thumbnail->save("../shop/images/product_images/thumbnail_images/".$file);
} else {
continue;
}
}
}
closedir($handle);
}
echo "Hallo Welt";
It looks like you never update the value of $handle within the while loop, therefore creating an infinite loop.
Try run code only with echo without resizing images. Try var_dump variables and check what is in. Make sure you have error reporting on. If some error occur.
Check image extension this way:
public static function isImage($fileName)
{
$type = exif_imagetype($fileName);
if (!(($type == IMAGETYPE_JPEG) || ($type == IMAGETYPE_GIF) || ($type == IMAGETYPE_PNG)))
return false;
return true;
}

can't upload multiple images iin zend freamework on server

i have a problem with upload mutilply files using zend framework on server
actually my code works correctly on localhost but on remote server it gives me application error message
my host is ipage.com
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->setDestination('projects\\'.$_pId);
// $_pid is my project folder where all files related to it uploded
$files = $upload->getFileInfo();
$i = 1;$g = 1;
foreach ($files as $file => $info)
{
// i have three kinds of images
// innerfinishingphotos_ images which can be more than 1 file eg :innerfinishingphotos_1, innerfinishingphotos_2, innerfinishingphotos_3.
// outerfinishingphotos_ images which can be more than 1 file eg :outerfinishingphotos_1, outerfinishingphotos_2, outerfinishingphotos_3.
// _main_photo image an image.
// here i made if statements to determine which file came from which input file
if( $info == $files["innerfinishingphotos_".$i] && $info["name"] == $files["innerfinishingphotos_".$i]["name"] && !empty( $info["name"] ) )
{
$filename = "inner_finishing".$_pId.uniqid().$files["innerfinishingphotos_".$i]["name"];
$upload->addFilter('Rename', $filename, $files["innerfinishingphotos_".$i]);
$photodata = Array ("project_id"=> $_pId, "photo_link"=> "/projects/".$_pId."/".$filename, "photo_name"=> "inner_finishing");
$projectModel->addInProjectGalary($photodata);
$i++;
}
else if( $info == $files["outerfinishingphotos_".$g] && $info["name"] == $files["outerfinishingphotos_".$g]["name"] &&!empty( $info["name"] ) )
{
$filename = "outer_finishing".$_pId.uniqid().$files["outerfinishingphotos_".$g]["name"];
$upload->addFilter('Rename', $filename, $files["outerfinishingphotos_".$g]);
$photodata = Array ("project_id"=> $_pId, "photo_link"=> "/projects/".$_pId."/".$filename, "photo_name"=> "outer_finishing");
$projectModel->addInProjectGalary($photodata);
$g++;
}
else if ($info == $files["_main_photo"] && !empty( $info["name"] ))
{
$filename = "main_photo".$_pId.uniqid().$files["_main_photo"]["name"];
$upload->addFilter('Rename', $filename, $files["_main_photo"]);
$photodata = Array ("project_id"=> $_pId, "photo_link"=> "/projects/".$_pId."/".$filename, "photo_name"=> "project_photo");
$projectModel->addInProjectGalary($photodata);
}
//then i receive the image
if($upload->isValid($file))
{
try {
$upload->receive($file);
}
catch (Exception $e) {
echo "upload exteption";
}
}
}
i tested this code and i works correctly on localhost and all images uploaded and their data entered my database
but on my remote host 'ipage.com' not work.
please guys help me
after many hours trying, i solved the problem , it wase in this line
$upload->setDestination('projects\\'.$_pId);
changing it to
$upload->setDestination('projects/'.$_pId);
thank you mr. Tim Fountain

Categories