Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.
If mail returns true, it doesn't mean that the email was sent properly, just that it was passed off to the host os or some sort of mail server. This might be sendmail or something else depending on how php and your webserver is configured. It could be that the messages are getting passed successfully to sendmail, but then sendmail is eating them.

You should work to get mail() so that it successfully sends a message to an account, then go from there. Check out how your server is setup.

Adbot
ADBOT LOVES YOU

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
Are there any decent PHP CSS "compilers"? The only thing I could really find is the following and it's not very feature filled...
http://interfacelab.com/variables-in-css-via-php/

Zorilla
Mar 23, 2005

GOING APE SPIT

supster posted:

Are there any decent PHP CSS "compilers"? The only thing I could really find is the following and it's not very feature filled...
http://interfacelab.com/variables-in-css-via-php/

Interesting idea, but it seems kind of over-engineered in my opinion. I'm pulling this out of my rear end, but would something like this work? Sorry if I'm missing your point by a mile:

style.css.php
php:
<?php
$red "#f00";

$column1_width 400;
$column2_width 300;

header('Content-type: text/css');
?>
.fart_container {width: <?php echo ($column1_width $column2_width); ?>px;}
.fart {color: <?php echo $red?>;}

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
No exactly. Take a look at this:
http://blog.davidziegler.net/post/92203003/css-compilers-rock

BondGamer
Sep 22, 2004
If you don't put in your 2 cents how can you expect change?
Why does ++$i execute faster than $i++?

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

BondGamer posted:

Why does ++$i execute faster than $i++?

What do you mean by faster? Like take less processor time? Or do you mean that with ++$i you will see $i incremented within the statement, while $i++ sees the value incremented afterward? If you mean the latter that is by design and how it works in all languages that support the ++ operator.

gibbed
Apr 10, 2006

Begby posted:

What do you mean by faster? Like take less processor time? Or do you mean that with ++$i you will see $i incremented within the statement, while $i++ sees the value incremented afterward? If you mean the latter that is by design and how it works in all languages that support the ++ operator.
Apparently the PHP devs actually have cocked it up to where pre-increment is actually faster than post-increment. :woop:

(pre-increment doesn't copy a value where post-increment does)

gibbed fucked around with this message at 03:55 on Jul 13, 2009

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
A few days ago I decided to see what type of neat text encryption PHP can do.

I stumbled upon this and within the same execution cycle it works fine:
php:
<?
   //encrypt3.php?key=balls&text=i like to move it move it
    $key_value = $_REQUEST["key"];
    $plain_text = $_REQUEST["text"];
    echo "key = '$key_value' and text = '$plain_text'<br>";
    $encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT);
    echo "encrypted text = '$encrypted_text'<br>";
    $decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT);
    $decrypted_text = trim($decrypted_text);
    echo "decrypted text = '$decrypted_text'";?>
shows the output
code:
key = 'balls' and text = 'i like to move it move it'
encrypted text = ''}OXh׍P:|V.{'
decrypted text = 'i like to move it move it'
But as soon as I start submitting it with a html form with encrypted text, funny things start happening, here's my form code: http://pastebin.com/m77339235

Comparing the output of my test script with the output from my main form, it's encrypting fine. It just seems the special characters aren't being transmitted to the server correctly when deycrpting. Could anybody please give me pointers why?

gibbed
Apr 10, 2006

I wouldn't spit out raw binary to a browser for it to resubmit, you should probably encode it somehow (base64, for example).

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

gibbed posted:

I wouldn't spit out raw binary to a browser for it to resubmit, you should probably encode it somehow (base64, for example).

Thank you, that worked a treat!

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!
I'm trying to graph Hard Drive utilization by partitions for a project I am working on. My goal is to allow user input of partitions of a server. From that point forward they can track changes in partition free space by entering the amount of free space on each partition at any given point of time. It can the be plotted out on a line graph.
Here is some sample data:
code:
[0] => Array
        (
            [partition_id] => 1
            [partition_name] => Drive C:
            [partition_size] => 30
            [partition_size_type] => GB
            [partition_free] => 22
            [partition_free_type] => GB
            [partition_create_date] => 2009-05-14
            [entries] => Array
                (
                    [0] => Array
                        (
                            [partition_free] => 21
                            [partition_free_type] => GB
                            [partition_entry_date] => 2009-06-14
                        )

                    [1] => Array
                        (
                            [partition_free] => 19
                            [partition_free_type] => GB
                            [partition_entry_date] => 2009-07-14
                        )

                )

        )
I would like to dynamically create a line graph that supports multiple partitions. Using the initial partition size and free space along with the date the partition was added give us a baseline for each partition. Each entry will then have a new date and freespace for the given partition. This should allow graphing by Date on the X axis and Size on the Y axis. The scale would be simple Y minimum would be ZERO, Y maximum would be the largest available partition size out of all of the partitions. In this example we are looking at one partition so the Y max would be 30 GB. The X axis would be by date, so the farthest to the left would be partition_create_date and the farthest on the right would be the last partition_entry_date.

All I want is a good recommendation on a PHP graphing Class or package and maybe a push in the right direction.

chips
Dec 25, 2004
Mein Führer! I can walk!

DarkLotus posted:

I would like to dynamically create a line graph that supports multiple partitions. Using the initial partition size and free space along with the date the partition was added give us a baseline for each partition. Each entry will then have a new date and freespace for the given partition. This should allow graphing by Date on the X axis and Size on the Y axis. The scale would be simple Y minimum would be ZERO, Y maximum would be the largest available partition size out of all of the partitions. In this example we are looking at one partition so the Y max would be 30 GB. The X axis would be by date, so the farthest to the left would be partition_create_date and the farthest on the right would be the last partition_entry_date.

All I want is a good recommendation on a PHP graphing Class or package and maybe a push in the right direction.

Have a look at jpgraph if you just want to generate images, but have you considered using either flash or javascript to do the plotting? Obviously it depends on what the client is and what it might support/be reasonable.

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

chips posted:

Have a look at jpgraph if you just want to generate images, but have you considered using either flash or javascript to do the plotting? Obviously it depends on what the client is and what it might support/be reasonable.

I was looking at JPGraph and it looks like it might work. I also looked at PHP/SWF Charts which definitely looks much nicer but also more involved. I like the idea of displaying an image or a swf, and not having the browser draw the plots with javascript.

This will all be web based obviously so IE / FF / Safari support is required.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



There's also the Google Chart API: http://code.google.com/apis/chart/

I'm sure you could find a ton of PHP wrappers for it, too.

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

Munkeymon posted:

There's also the Google Chart API: http://code.google.com/apis/chart/

I'm sure you could find a ton of PHP wrappers for it, too.

Very cool. I forgot Google had this available. I will have to look into that as well. I think I will need something different that can be included in a commercial application since this web app I am developing will probably be sold or subscription based.

spiritual bypass
Feb 19, 2008

Grimey Drawer
GNUPlot makes nice graphs in a reasonable time frame. I used it plenty in college and enjoyed it. The website is ugly, but the graphs are actually pretty good.

Ferg
May 6, 2007

Lipstick Apathy

DarkLotus posted:

Very cool. I forgot Google had this available. I will have to look into that as well. I think I will need something different that can be included in a commercial application since this web app I am developing will probably be sold or subscription based.

I just discovered the Charts API a few weeks ago when I banged out this quick Jetpack extension: http://userscripts.org/jetpacks/87

It's a slick API that they definitely don't publicize enough.

Alex007
Jul 8, 2004

Artichow works really well and offers a lot of features, but the docs are only in french :(

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
Pinging this question again, and also a new one: When I use mysqli->bind_result and the result is a MySQL NULL, is the variable set to null or "NULL"?

Golbez posted:

Because of duz, I looked into using __get and __set, and kind of like them. However, I'm running into a problem:

php:
<?
$stmt->bind_param('iisi',$this->Type,$this->UserID,$this->UserEmail,$this->UserCompany);
?>
returns notices like this for each $this:

code:
Notice: Indirect modification of overloaded property Record::$UserEmail has no effect in /var/www/foo/bar/Record.php on line 187
etc etc. This is a read function, not a write, yet it's giving a notice about writing it. I prefer to avoid all notices, I like my code clean. Is there any way around this other than writing all of the $this->etc to variables, then pass those variables to the bind_param?

On a similar note, is there any way to see the raw query text of a query mysqli has just executed? It would help with debugging.

PS, the answer to this last one lies in mysqld's query log. It's been quite useful.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

Golbez posted:

Pinging this question again, and also a new one: When I use mysqli->bind_result and the result is a MySQL NULL, is the variable set to null or "NULL"?

I am not sure, I think its either null or an empty string, but its certainly not a string with the word NULL in it.

Execute the query "SELECT NULL AS myTestResult". Bind the result, then do var_dump on it to see what it spits out.


As far as your other question. You are creating some whackiness by passing in overloaded properties that may or may not exist as far as the compiler is concerned. When you use bind_param you are binding a reference to the variable, not passing the value stored in the variable. That way you can modify the value of the variable right up until you call execute. When execute is called it then pulls the values. When you pass in the overloaded property it may not exist when execute is called.

You can fix this by doing $val1 = $this->val1; $val2 = $this->val2; etc then bind $val1 and $val2 to the query.

You could also switch to PDO and use bindValue instead. IMO PDO is easier to use anyways.

Begby fucked around with this message at 20:47 on Jul 16, 2009

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Begby posted:

I am not sure, I think its either null or an empty string, but its certainly not a string with the word NULL in it.
Thanks, that works for me. As long as it wasn't sending a string that would evaluate in PHP to anything but false.

Begby posted:

As far as your other question. You are creating some whackiness by passing in overloaded properties that may or may not exist as far as the compiler is concerned. When you use bind_param you are binding a reference to the variable, not passing the value stored in the variable. That way you can modify the value of the variable right up until you call execute. When execute is called it then pulls the values. When you pass in the overloaded property it may not exist when execute is called.

You can fix this by doing $val1 = $this->val1; $val2 = $this->val2; etc then bind $val1 and $val2 to the query.

You could also switch to PDO and use bindValue instead. IMO PDO is easier to use anyways.

Ah, okay. Yeah, I was hoping to avoid the extra variable settings but I'll probably end up doing that just for the sake of avoiding notices. (The code works as-is, just with notices)

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Golbez posted:

Thanks, that works for me. As long as it wasn't sending a string that would evaluate in PHP to anything but false.
I know that if the value in a column is NULL (in the SQL sense) then mysqli_fetch_assoc gives the value NULL (in the PHP sense) to the corresponding array entry. Makes sense to suppose that this behaviour is consistent across mysqli functions.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
I've started working on a CSS preprocessor writte in in PHP (and intended to be used in PHP applications) but I am a little unsure about which route to go regarding syntax.

My initial thought was to borrow heavily from CleverCSS and Python to have syntax like this:
code:
ul#comments, ol#comments:
  margin: 0
  padding: 0

  li:
    padding: 0.4em
    margin: 0.8em 0 0.8em

    h3:
      font-size: 1.2em
    p:
      padding: 0.3em
    p.meta:
      text-align: right
      color: #ddd
But then I realized that perhaps I am being bias as I love Python and it's syntax. Additionally I realized that switching between writing PHP/JS and that type of CSS might be a bit awkward because you are switching from curly brackets and semicolons to Python-like syntax.

So I figured that perhaps syntax like the following may be more fitting:
code:
ul#comments, ol#comments
{
  margin: 0;
  padding: 0;

  li
  {
    padding: 0.4em;
    margin: 0.8em 0 0.8em;

    h3
    {
      font-size: 1.2em;
    }
    
    p
    {
      padding: 0.3em;
    }
    
    p.meta
    {
      text-align: right;
      color: #ddd;
    }
  }
}
But I am pretty unhappy with the way this looks and feels and would much prefer to write in the first style.

I wanted to get some opinions from other PHP developers that may have less Python bias than I do and see what they might prefer. I am also open to suggestions for a different type of syntax than the above two.

supster fucked around with this message at 01:09 on Jul 17, 2009

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

Golbez posted:

Ah, okay. Yeah, I was hoping to avoid the extra variable settings but I'll probably end up doing that just for the sake of avoiding notices. (The code works as-is, just with notices)

You know what might work? You can set your __get and __set methods to write to an array, then call the array directly

code:
// The syntax may be incorrect as I have been doing c# instead of php recently
private $vars = array();

function __set($var, $value)
{
  $this->vars[$var] = $value;
}
then reference $this->vars['var'] within your bind_params call. That might make it so you don't have to do all the assigning and eliminate the notices.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Begby posted:

You know what might work? You can set your __get and __set methods to write to an array, then call the array directly

code:
// The syntax may be incorrect as I have been doing c# instead of php recently
private $vars = array();

function __set($var, $value)
{
  $this->vars[$var] = $value;
}
then reference $this->vars['var'] within your bind_params call. That might make it so you don't have to do all the assigning and eliminate the notices.

That's a good idea, I've been trying to be all fancy with the setting and unsetting but I don't have to do that within the object really, do I.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



supster posted:

CSS Preprocessor

CSS already uses culy braces to group stuff so I would think it'd be more natural to use that way.

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right
I have an upload script that uploads an image for me, resizes it and saves both files. It works fine, but it gives me a few errors. Let's start with the code.

php:
<?
<form action="<?php echo $_server['php-self'];  ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
        <input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
        <button name="submit" type="submit" class="submitButton">Upload/Resize Image</button>
</form>

<?php
        if(isset($_POST['submit'])){
          if (isset ($_FILES['new_image'])){
              $imagename $_FILES['new_image']['name'];
              $source $_FILES['new_image']['tmp_name'];
              $target "upload/".$imagename;
              move_uploaded_file($source$target);
 
              $imagepath $imagename;
              $save "upload/" $imagepath//This is the new file you saving
              $file "temp/" $imagepath//This is the original file
 
              list($width$height) = getimagesize($file) ; 
 
              $modwidth 150; 
 
              $diff $width $modwidth;
 
              $modheight $height $diff; 
              $tn imagecreatetruecolor($modwidth$modheight) ; 
              $image imagecreatefromjpeg($file) ; 
              imagecopyresampled($tn$image0000$modwidth$modheight$width$height) ; 
 
              imagejpeg($tn$save100) ; 
 
              $save "upload/sml_" $imagepath//This is the new file you saving
              $file "upload/" $imagepath//This is the original file
 
              list($width$height) = getimagesize($file) ; 
 
              $modwidth 320; 
 
              $diff $width $modwidth;
 
              $modheight $height $diff; 
              $tn imagecreatetruecolor($modwidth$modheight) ; 
              $image imagecreatefromjpeg($file) ; 
              imagecopyresampled($tn$image0000$modwidth$modheight$width$height) ; 
 
              imagejpeg($tn$save100) ; 
            echo "Large image: <img src='upload/".$imagepath."'><br>
                  
Code: <a href='http://www.mysite.com/dir'.$imagepath."; 

            echo "Thumbnail: <img src='upload/sml_".$imagepath."'>"; 
            
echo "<br><code> BB-Code: [b]here goes the BB-code, but will remove the URL[/b]
          }
        }
?>
?>


I get these errors:

code:
Warning: getimagesize(temp/anna-faris-arp-06.jpg) [function.getimagesize]: failed to open stream: No such file or directory in /home/grawl/public_html/mystuff/upload.php on line 18

Warning: Division by zero in /home/grawl/public_html/mystuff/upload.php on line 24

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/grawl/public_html/mystuff/upload.php on line 25

Warning: imagecreatefromjpeg(temp/anna-faris-arp-06.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in /home/grawl/public_html/mystuff/upload.php on line 26

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/grawl/public_html/mystuff/upload.php on line 27

Warning: imagejpeg(): supplied argument is not a valid Image resource in /home/grawl/public_html/mystuff/upload.php on line 29
I understand this is because the image isn't saved into the directory, but I don't know why not. If you just ignore the errors the script works fine, as long as you use a JPG (PNG, and it'll give a black thumbnail) and the image is bigger than what the thumbnail will be like (320 px width).

Grawl fucked around with this message at 19:51 on Jul 17, 2009

spiritual bypass
Feb 19, 2008

Grimey Drawer
What do you get from print_r($_FILES)? Your upload is probably not doing what you're expecting.

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right

royallthefourth posted:

What do you get from print_r($_FILES)? Your upload is probably not doing what you're expecting.

code:
Array ( [new_image] => Array ( [name] => anna-faris-hollywood-01.jpg [type] => image/jpeg [tmp_name] => /tmp/phpG7G1Rd [error] => 0 [size] => 103949 ) ) 
The temp dir is chmodded to 755.

spiritual bypass
Feb 19, 2008

Grimey Drawer
I think I've found it

php:
<?php
$file "temp/" $imagepath//This must be a typo
?>
I should be working on programs at work, but I'm doing this instead. Talk about low morale

:smith:

gibbed
Apr 10, 2006

Grawl posted:

php:
<?
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "upload/".$imagename;
move_uploaded_file($source, $target);
?>
This is insecure. The client has control over the 'name' value. You should sanitize it somehow, at least do basename().

Grawl posted:

php:
<?
$imagepath = $imagename;
$save = "upload/" . $imagepath; //This is the new file you saving
$file = "temp/" . $imagepath; //This is the original file
 
list($width, $height) = getimagesize($file);
?>

Grawl posted:

php:
<?
$image = imagecreatefromjpeg($file) ; 
?>
You've moved the uploaded file to upload/, not temp/, which is probably why this is failing.

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right
What I have here is what I put together by scripts written by others, since my PHP isn't good enough to do it myself - I probably should mention that.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Grawl posted:

What I have here is what I put together by scripts written by others, since my PHP isn't good enough to do it myself - I probably should mention that.

Good news! There's a secure image upload script written by R1CH in the first post!

gibbed
Apr 10, 2006

duz posted:

Good news! There's a secure image upload script written by R1CH in the first post!
It doesn't do thumbnails though, but yeah, it would be a good idea to hack on that one to add thumbnailing.

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right

gibbed posted:

It doesn't do thumbnails though, but yeah, it would be a good idea to hack on that one to add thumbnailing.

That isn't working for me. Without .htaccess it'll give an error, but when I do upload the file I get an 500 Internal Server Error.

Alex007
Jul 8, 2004

Grawl posted:

That isn't working for me. Without .htaccess it'll give an error, but when I do upload the file I get an 500 Internal Server Error.

Check your server logs to see what the error is.

EDIT: Apache error log to be more precise.

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right

Alex007 posted:

Check your server logs to see what the error is.

EDIT: Apache error log to be more precise.

code:
[Fri Jul 17 14:31:37 2009] [error] [client 76.90.39.2] File does not exist: /home/grawl/public_html/500.shtml
[Fri Jul 17 14:31:37 2009] [alert] [client 76.90.39.2] /home/grawl/public_html/blabla/.htaccess: Invalid command 'php_flag', perhaps misspelled or defined by a module not included in the server configuration
edit: using HostGator

edit 2: I managed to override it using php.ini

Grawl fucked around with this message at 20:55 on Jul 17, 2009

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right
I tweaked with the image upload script, but I'm stuck at the part where I set it where to upload the file. I want the file to be named something like "thumb_filename" or even better "filename_thumb" and be saved in the same folder.

php:
<?
// Resize

    // Set new dimensions

list($width, $height) = getimagesize($file);
$new_width = 320; // Set to custom number in pixels
$new_height = ($new_width * $height) / $width;

    // Resample

$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    // Moving into final dir

$user_supplied_filename_thumb = basename($_FILES['filename']['name']);

$final_filename_thumb = $final_prefix . $added . $file_format
$final_basename_thumb = $user_supplied_filename_thumb . $added . $file_format;

if (!move_uploaded_file ($image, $final_filename_thumb))
    $error = "Thumbnail failed to save.";

// Resize?>
Assuming the code is correct till the "Moving into final dir" part, how do I finish this? Full script to be sure:

php:
<?php
if (ini_get ("register_globals") == "1")
    die ("Insecure PHP settings detected. Please make sure register_globals is disabled.");

error_reporting (E_NONE);

require_once ('config.php');

if (!isset ($config))
    die ("Config did not load. Please check config.php settings.");
?>

<html>
    <head>
        <title>Image Uploader</title>
    </head>
    <body>
        <h1>Image Uploader</h1>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
?>
        <form method="post" action="<?=$_SERVER['PHP_SELF']?>" enctype="multipart/form-data">
            <p>Select an image to upload (max size: <?=$config['max_size']?> KiB):<br>
            <input type="file" name="filename"></p>
            <p><input type="submit" value="Upload"></p>
        </form>
<?php
}
else
{
    if (!isset($_FILES['filename']) || $_FILES['filename']['tmp_name'] == '')
    {
        $error "Upload failed, please check the filename and try again.";
    }
    else
    {
        $file $_FILES['filename']['tmp_name'];

        $file_size filesize($file) / 1024;
        if ($file_size $config['max_size'])
            $error "File size exceeded, maximum allowed file is {$config['max_size']} KiB, your file was " sprintf ("%.2f"$file_size) . " KiB.";

        if (!isset($error))
        {
            $fh fopen ($file"rb");
            if ($fh)
            {
                $header_bytes fread($fh8);

                if (!strncmp ($header_bytes"\xFF\xD8"2))
                    $file_format ".jpg";
                else if (!strncmp ($header_bytes"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"8))
                    $file_format ".png";
                else if (!strncmp ($header_bytes"GIF"3))
                    $file_format ".gif";
                else
                    $error "Unknown file format, only JPEG, PNG and GIF files are allowed.";

                fclose ($fh);

                if (!isset($error))
                {
                    //Remove path
                    $user_supplied_filename basename($_FILES['filename']['name']);

                    //Strip extension(s)
                    $dot strpos ($user_supplied_filename".");

                    if ($dot !== FALSE)
                        $user_supplied_filename substr ($user_supplied_filename0$dot);

                    //Rewrite filename if it's invalid
                    if ($user_supplied_filename == '' || preg_match ("/\W/"$user_supplied_filename))
                        $user_supplied_filename sha1($file);

                    //Check for overwrite prior to extension
                    $final_prefix $config['data_dir'] . "/" $user_supplied_filename;
                    $added '';
                    while (file_exists ($final_prefix $added $file_format))
                        $added++;

                    $final_filename $final_prefix $added $file_format;
                    $final_basename $user_supplied_filename $added $file_format;

                    //Move it to the upload directory
                    if (!move_uploaded_file ($file$final_filename))
                        $error "Internal error, unable to move uploaded file. Please check permissions and disk space.";
                }
            }
            else
            {
                $error "Internal error, unable to open uploaded file.";
            }
        }
    }

    if (isset($error))
    {
?>
        <span style="color: #F00"><strong>ERROR:</strong> <?=$error?></span>
        <p><a href=".">Try again</a></p>
<?php
    }
    else
    {
?>
        <p>Your file was uploaded successfully.</p>

        <p>Direct link: <a href="<?=$config['web_dir'] . $final_basename?>"><?=$config['web_dir'] . $final_basename?></a></p>
        <p>Forum code: [img]<?=$config['web_dir'] . $final_basename?>[/img]</p>
<?php
    }
}
?>
</body>
</html>

Grawl fucked around with this message at 22:45 on Jul 17, 2009

standard
Jan 1, 2005
magic
Does anyone know of a nice image serving type script?
The type that I can use in img tags, instead of serving images directly. eg.

<img src="image.php?src=whatever.jpg" />

You get the idea...

Adbot
ADBOT LOVES YOU

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

standard posted:

Does anyone know of a nice image serving type script?
The type that I can use in img tags, instead of serving images directly. eg.

<img src="image.php?src=whatever.jpg" />

You get the idea...

You could make one fairly easily if you are good with PHP. The problem isn't just serving images, you have to somehow tell the script where the image is stored on the server. What exactly are you trying to accomplish by not hard coding image paths?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply