can someone help me fix my code? - php

I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol
Ol, sorry stackoverflow is a new thing for me. Not sure how to think of it. As a forum or a place to post a question... hmmm, I'm sorry for being rude with my method of asking.
I was wondering i you could give me some guidance on how to properly insert directory structures with how i written this code. I wasn't sure how to tell the PHP where to upload my files and whatnot, I got some help from a friend who helped me sort out some of my bugs, but I'm still lost with dealing with the mkdir and link, unlink functions. Is this how I am suppose to refer to my diretories?
I know php 5.3 uses the _ DIR _ and php 5.0 use dirname(_ _ FILE_ _), I have tried both and I get the same errors. My files are set to 0777 for testing purposes. What could be the problem with it now wanting to write and move my uploaded file?
} elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) {
$errors['img_fileexists'] = true;
}
if (! empty($errors)) {
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
// Create thumbnail
if (empty($errors)) {
// Make directory if it doesn't exist
if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) {
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
$folders = explode("\\", $dir);
// Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec)
$dirTmp = '';
foreach ($folders as $fldr) {
if ($dirTmp != '') { $dirTmp .= "\\"; }
$dirTmp .= $fldr;
mkdir("\\".$dirTmp); //ignoring errors deliberately!
}
// Check again whether it exists
if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
}
if (empty($errors)) {
// Move uploaded file to final destination
if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
} else {
// Create thumbnail in new dir
if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
$errors['thumb'] = true;
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
}
}
}
}
// Record in database
if (empty($errors)) {
// Find existing record and delete existing images
$sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
$numResults = mysql_num_rows($result);
if ($numResults == 1) {
$row = mysql_fetch_assoc($result);
// Delete old files
unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
}
// Update/create record with new images
if ($numResults == 1) {
$sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
} else {
$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
}
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
}
// Print success message and how the thumbnail image created
if (empty($errors)) {
echo "<p>Thumbnail created Successfully!</p>\n";
echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n";
echo "<br />\n";
}
}
I get the following errors:
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112

One way is to check from within your code whether a certain command/function is available for use. You can use the function_exists function for that eg:
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set("GMT");
}
else
{
echo 'date_default_timezone_set is not supported....';
}

Ahh! I'm sorry, didn't mean to vent my frustration on you guys. But I have been at this for hours now it seems.
Like i mentioned this code works but since my server is picky I can't user the 5.3 syntax I coded. This is my attempt to make it work on the 5.0 php my server has.
In particular I think there is something wrong with the mkdir() and the unlink() functions.
if you go to www.helixagent.com log in with test/test then in the url go to /upload2.php then you will see the errors its throwing at me.
well, it works perfect if i use 5.3 and DIR but since I'm on 5.0 i tried a different method
the errors i get are
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112

It looks like you don't have access to the folder (or file)
/uploads/$username/images/banner/$filename
which could be because of a basedir restriction on the host (e.g. you may not leve the parent directory /services/webdata/) or just a missing permission in the os.
Try to (temporary) set permission of /uploads/ to 777 or execute the script from console to see if you have a basedir restriction.

Take a closer look at the paths in the error messages:
./uploads/saiyanz2k/images/banner/azumanga-wall.jpg
/services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php
The destination is a relative path, most likely relative to upload2.php's directory. The one relative path I see is the line:
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
Which should probably be:
// Take directory and break it down into folders
$dir = "\\uploads\\{$username}\\images\\banner\\thumbs";
Actually, it should be
$dir = "/uploads/{$username}/images/banner/thumbs";
since PHP supports using a forward slash as directory separator on all platforms, while the backslash is only supported on MS platforms.

Related

PHP copy() is only copying half the image

https://trevim.pt/header-4/
I'm copying this image to this link
https://trevim.pt/anuncios/header.png
When I run the script it always says 'File copied successfully' but some times I only get the top half of the image... it's not at all a large file (22.6KB), is this behavior normal? How can I copy the whole image every time? Any ideas? Here's my code:
foreach($to_activate as $data_row)
{
$template_id = $data_row['template_id'];
$img_url = $data_row['img_url'];
$template = mysqli_query($conn, "SELECT name FROM `wp_ad_templates` WHERE id = '$template_id' limit 1")->fetch_object()->name;
$dst = "../" . $template . ".png";
if(!#copy($img_url, $dst))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br>".$errors['message']."<br><br>";
} else {
echo "File copied from remote!";
}
}
By the way I found this similar question Php copy only copies part of file which is solved by using exec() but that solution didn't work for me, I get:
COPY ERROR: 2
exec() has been disabled for security reasons

Why can't php find this file?

I have an Apache/PHP site running on a Drobo5n in Linux.
utilities.php is in /Choir/inc
hitCounter.txt is in /Choir/etc/tbc
In utilities.php, we have the following line of code:
$hits = file_get_contents('../etc/tbc/hitCounter.txt');
Which produces this error:
Warning: file_get_contents(../etc/tbc/hitCounter.txt): failed to open
stream: No such file or directory in
/mnt/DroboFS/Shares/DroboApps/apache/www/Choir/inc/utilities.php
on line 6
This is my first time fiddling with PHP and I cannot figure out why it can't find the file. I've tried both single and double quotes around the path to no avail.
I know someones gonna ask for the complete code so here's the utilities.php file:
<?php
session_cache_limiter('private_no_expire');
session_start();
function getHitCount() {
$hits = file_get_contents('../etc/tbc/hitCounter.txt');
if (!isset ($_SESSION['beenHere'])) {
$hits = $hits + 1;
file_put_contents('../etc/tbc/hitCounter.txt', "$hits");
$_SESSION['beenHere'] = "Yes I have";
}
return $hits;
}
?>
1) Should explicit your file path. Hard to say in this case. We should have our root application folder.
If we follow the MVC pattern, we will get the root application folder easily.
For example https://github.com/daveh/php-mvc
I like something:
$file = APP_ROOT . '/etc/tbc/hitCounter.txt';
#APP_ROOT has the path /mnt/DroboFS/Shares/DroboApps/apache/www/Choir
2) Check file_exists
if (!file_exists($file)) {
//Throw error here
}
3) Check: is_readable
if (!is_readable($File)) {
......
}

PHP permission Denied using unlink and rmdir

i've been trying to figure out why my Php code is giving me a annoying error. I've tried countless functions from previous post but the error its been giving is "Permission Denied". From my understanding either i have to have special privledges to delete files, etc.. I've tried multiple solutions but I'm still getting this error. If anyone can point me in the right direction, that'll be great. Ive post a snippet of my code below.. Thanksss
$first_sub = "my_dir";
if(is_dir($first_sub)){
$read_sub1 = opendir($first_sub);
while(false !== ($files = readdir($read_sub1))){
if($files!="." && $files!=".."){
unlink($first_sub ."/". $files);
}
}
closedir($read_sub1);
You should set proper permission to your server directories:
Visit: http://bd1.php.net/chmod
<?php
// Read and write for owner, nothing for everybody else
chmod($first_sub ."/". $files, 0600);
// Read and write for owner, read for everybody else
chmod($first_sub ."/". $files, 0644);
// Everything for owner, read and execute for others
chmod($first_sub ."/". $files, 0755);
// Everything for owner, read and execute for owner's group
chmod($first_sub ."/". $files, 0750);
?>
just before unlink you can call this function.
I got that an error from unlink permission denied.
But I fix it. The error displays like this unlink(../foldername/) Permission denied.
My wrong code is like this:
$image = select_table('webpage', 'wp_name', '$id');
$update = "UPDATE webpage SET wp_image = NULL, wp_modifiedby = '{$position}', wp_datemodified = '{$date_now}' WHERE wp_name = '{$id}'";
if ( unlink('../webpage/'.$image_dir) && $qry_update = mysqli_query($connection, $update) ) {
// success
} else {
// failed
}
now i fix it
my correct code is like this:
$image = select_table('webpage', 'wp_name', $id);
$update = "UPDATE webpage SET wp_image = NULL, wp_modifiedby = '{$position}', wp_datemodified = '{$date_now}' WHERE wp_name = '{$id}'";
if ( unlink('../webpage/'.$image['wp_image']) && $qry_update = mysqli_query($connection, $update) ) {
// success
} else {
// failed
}
For those who land on this page, it may be as simple as not setting $files to an existing file.
It is unfortunate, but I found that the message: Warning: move_uploaded_file(): Unable to move can also mean file not found.
Not likely the cause of this OP's problem, but certainly worth verifying the file represented by the variable you pass actually exists in the directory.

Trying to validate a folder being dynamically created using PHP

I am trying validate: whether or not the folder I am attempting to create exists. Sure, I get a message... an error message :/ telling me it does! (if it doesn't exist, no error message, and everything goes as planned).
It outputs this error message
Directory exists
Warning: mkdir() [function.mkdir]: File exists in /home/***/public_html/***/formulaires/processForm-test.php on line 75
UPLOADS folder has NOT been created
The current code I use is this one:
$dirPath = $_POST['company'];
if(is_dir($dirPath))
echo 'Directory exists';
else
echo 'directory not exist';
function ftp_directory_exists($ftp, $dirPath)
{
// Get the current working directory
$origin = ftp_pwd($ftp);
// Attempt to change directory, suppress errors
if (#ftp_chdir($ftp, $dirPath))
{
// If the directory exists, set back to origin
ftp_chdir($ftp, $origin);
return true;
}
// Directory does not exist
return false;
}
$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo '<br/>'.$dirPath . " has been created".'<br/>';
} else {
echo '<br/>'.$dirPath . " has NOT been created".'<br/>';
}
I added the middle part recently (I don't know if that would even have an impact). The one that starts off with "function ftp_directory_exists($ftp, $dirPath)"
Use file_exists() to check if a file / directory exists:
if(!file_exists('/path/to/your/directory')){
//yay, the directory doesn't exist, continue
}
The function ftp_directory_exists you added won't have any impact on your code as it is never called...
You might tried something like this (not tested...) :
$dirPath = $_POST['company'];
$dirExists = is_dir($dirPath);
if(!dirExists)
$dirExists = mkdir($dirPath, 0755);
echo '<br/>'.$dirPath . (($dirExists)? "" : "DO NOT") . " exists".'<br/>';

move_uploaded_file() fails to open stream due to invalid argument - PHP

I have this code to move my uploaded file to a specific directory:
if (isset($_FILES["image"]["name"])){
if (!is_dir('pf/' . $uid)) {
mkdir('pf/' . $uid);
$large_image_location = "pf/" . $uid;
}else {
$large_image_location = "pf/" . $uid;
}
chmod ($large_image_location, 0777);
move_uploaded_file("$userfile_tmp", "$large_image_location/$userfile_tmp");
}
However that gives the following error:
( ! ) Warning: move_uploaded_file(pf/BfyhieniKJGGqTNm/C:\wamp\tmp\phpF08A.tmp) [function.move-uploaded-file]: failed to open stream: Invalid argument in C:\wamp\www\mingle\upload_dp.php on line 26
Any help on how to sort this out would be greatly appreciated!
This is 90% of your woes:
move_uploaded_file("$userfile_tmp", "$large_image_location/$userfile_tmp");
You using the moved to path at the beginning of the upload path. Try:
move_uploaded_file("$userfile_tmp", "$large_image_location/".$_FILES['image']['name']);
That should work better.
The error itself is pretty clear, pf/BfyhieniKJGGqTNm/C:\wamp\tmp\phpF08A.tmp is not a valid filename.
Don't change the contents of $_FILES[n]['tmp_name'] (or $userfile_tmp for that matter), since it will always contain the full path to the uploaded file.

Categories