R
roy17

  • Aug 24, 2012
  • Joined Apr 11, 2012
  • you'll have a lot of DB work to do

    I don't understand what you mean? How come database is involved in this? Isn't it just passing everything the user input to the mail function?
    And by your experience, may I know how long will this kind of project last?

    Thanks in advance.

    • Hi,

      I am quite a beginner to PHP. I am currently want to do a project to further my knowledge.
      My idea is to create a reminder system.
      Something like google calendar which can remind you about your meeting and appointment.
      However, i want to make it using a simple interface (user email, time, time zone, what is the reminder).
      So, people who visit the site can just type in, and will receive email, one hour, 30 minutes and 10 minutes before the time which the user type in.
      I believe PHP have a mail function, but I am still figuring it out.
      May I know whether it can be implemented using PHP?

      Thanks in advance.

      • Hi,

        I am trying to create a web application where I want to merge Java and PHP.
        I am new to Java and have some experience using PHP.
        Right now, I know how to create a simple Java applet and embed it into the PHP using a HTML tag applet.
        However, I realize that it is a client side only, as after I disconnect my internet connection, the applet is still working.
        I would like to create some simple text display. Lets say I press a button then a html text is displayed below. However I need to use java for it.
        Do I need to write the socket connection on both Java application and inside the PHP?

        I already attempted using AJAX and it is working perfectly, however it is not the same with my current requirement where I need php and java working together.
        Please help, already confuse.

        If you have any links to tutorial to this problem, please kindly post it too. The ones I find say that php client and java server which doesn't make sense because php is a server scripting language.

        Thanks in advance.

        • I try this code

          echo"<form action='' method=POST enctype=multipart/form-data>";
          echo"<input type=submit value='Export' name=downloadaszip class=downloadaszip>";
          echo"</form>";
          if(isset($_POST['downloadaszip']))
          {
              //Directory
          	$dir='.\\'.$_SESSION['folder'].'\cfile\\';
          	$files=glob($dir.'*');
          	$base=realpath($dir);
          	$zip = new ZipArchive();
          	//Open a ZIP file archive
          	$zip->open('./user_'.$_SESSION['membername'].'/project.zip', ZipArchive::CREATE);
          	//add each file to archive
          	foreach ($files as $file) 
          	{
          		$target=str_replace($base,'',$file);
          		//Adds a file to a ZIP archive from the given path
          		$zip->addFile($file, $target);
          	}
          	//Close the active archive
          	$zip->close();
          	//identify browser type of file downloaded
          	header('Content-Type: application/zip');
          	//to produce download box and prompt user with project.zip
          	header('Content-disposition: attachment; filename=project.zip');
          	//download
          	//header("Pragma: no-cache");
          	header("Expires: 0");
          	header("Pragma: "); header("Cache-Control: ");
          	readfile("./user_".$_SESSION['membername']."/project.zip");
                  //unlink('./'.$_SESSION['folder'].'/project.zip');
          }

          The current code still result in a downloaded file which when I open still produce an invalid error message.
          The project.zip is created in the directory in the server that I specify. Inside the zip file in the server another project.zip is created and it is invalid too.

          • So I need to change

            $zip->addFile($file); 

            to

             zip->addFile($file,$target) 

            Is that correct?
            If it is, can you explain more on what you mean by

            target could be everything but the drive path like path\to\file.ext

            Do you mean that I should insert

            $target="project.zip";
            

            The error messages still appear.

            • Hi,

              I am trying to download multiple files using a zip file.
              I want the php script to form a zip file after adding all the file from the folder that I want, then download that zip file.
              I added an unlink function to make my zip file disappear, so the zip file downloaded will always be the one inside the folder.

              Right now, by commenting the unlink, I can know that the zip folder is created inside the server. However there is nothing inside.
              The downloaded zip file when I open, I see the message, the zip file folder is invalid. windows can't open the file ( I use a WAMP server). However, if I use 7zip to extract it, I can obtain and see the file, which is very confusing.

              What am I missing? Is it the header?

              echo"<form action='' method=POST enctype=multipart/form-data>";
              echo"<input type=submit value='Export' name=downloadaszip class=downloadaszip>";
              echo"</form>";
              if(isset($_POST['downloadaszip']))
              {
                      //Directory
              	$files=glob('.\\'.$_SESSION['folder'].'\cfile\*');
              	$zip = new ZipArchive();
              	//Open a ZIP file archive
              	$zip->open('./user_'.$_SESSION['membername'].'/project.zip', ZipArchive::CREATE);
              	//add each file to archive
              	foreach ($files as $file) 
              	{
              		//Adds a file to a ZIP archive from the given path
              		$zip->addFile($file);
              	}
              	//Close the active archive
              	$zip->close();
              	//identify browser type of file downloaded
              	header('Content-Type: application/zip');
              	//to produce download box and prompt user with project.zip
              	header('Content-disposition: attachment; filename=project.zip');
              	//download
              	 header("Pragma: no-cache");
                header("Expires: 0");
              
              readfile("./user_".$_SESSION['membername']."/project.zip");
                  //unlink('./'.$_SESSION['folder'].'/project.zip');
              }

              Thanks in advance.

              • The message shows that you're trying to access a directory called "user_andrew" in the root of your drive (e.g. "C:\user_andrew\"). Is that correct?

                No, user_andrew is located inside my webroot. I know this is a bad practice, but I just wanted to know whether it will work first.

                user_andrew is the $_SESSION['folder']

                echo"<input type=hidden name=filename value='"; 
                $filename; 
                echo "'> 
                </form>";  

                I used the code above because I manage to get a working solution. However, this working solution produced a new window which is not as I wanted it to do. I wanted it to be in one window.

                This is the working solution.

                index.php

                if ($handle = opendir('.\\'.$folder.'\cfile\\')) 
                {
                    while (false !== ($file = readdir($handle))) 
                    {
                        if ($file != ".." && $file != ".") 
                        {	
                	echo "<a href=scriptedit.php?path=.&filename=$file>$file</a><br />";
                        }
                    }
                    closedir($handle);
                }

                scriptedit.php

                <?php
                $path=$_REQUEST['path'];
                $filename=$_REQUEST['filename'];
                ?>
                <html>
                <head>
                <title>Script example</title>
                	<script language="Javascript" type="text/javascript" src="../edit_area/edit_area_full.js"></script>
                	<script language="Javascript" type="text/javascript">
                		// initialisation
                		editAreaLoader.init({
                			id: "content"	// id of the textarea to transform		
                			,start_highlight: true	// if start with highlight
                			,allow_resize: "both"
                			,allow_toggle: true
                			,word_wrap: true
                			,language: "en"
                			,syntax: "c"	
                			,toolbar: "  save, |, search, go_to_line, |, undo, redo,"
                
                		,save_callback: "my_save"
                		});
                
                	// callback functions
                	function my_save(id, content){
                	form1.content1.value=content;
                	document.forms["form1"].submit();
                			}
                
                
                </script>
                </head>
                <body>
                <textarea name=content id=content style="height: 700px; width: 780px;"><?php 
                $script="edit";
                if($filename!="scriptinclude.php"){
                include "scriptinclude.php";
                }
                else{ echo "Scriptinclude may not be edited";}
                ?>
                </textarea>
                <form name=form1 method=post action=scriptupdate.php>
                <table>
                <tr><td><textarea name=content1 id=content1 style="height: 0px; width: 0px;">
                </textarea></td></tr>
                </table>
                <input type=hidden name=path value='<?php echo $path;?>'>
                <input type=hidden name=filename value='<?php echo $filename;?>'>
                </form>
                </body>
                </html>

                scriptinclude.php

                <?php
                session_start();
                if($script=="edit")
                {
                    //$lines = file("../$path/upload/$filename");
                    //$lines = file("$path/upload/$filename");
                    $lines = file($path."/".$_SESSION['folder']."/cfile/".$filename);
                	foreach($lines as $line)
                	{
                	echo str_replace("</textarea>","<textarea>",$line);
                	}
                }
                else
                    {
                    $content= stripslashes(str_replace("<textarea>","</textarea>",$_REQUEST['content1']));
                    }
                ?>

                scriptupdate.php

                <?php
                session_start();
                //chdir($_REQUEST['path']."/upload");
                chdir($_REQUEST['path']."/".$_SESSION['folder']."/cfile");
                $fp = fopen($_REQUEST['filename'], 'w');
                include "scriptinclude.php";
                fwrite($fp, $content);
                fclose($fp);
                //include 'vars.php';
                header('Location: ../index.php');
                ?>

                All of these script works from the functionality works as I wanted. It is just it is not in the same page. It open a new window.

                where do you ever define the variables $script, $path, and $filename ?

                Sorry, I am new to PHP. I though that

                include "scriptinclude.php"; 

                is just a link so that you don't have to write the code all over again. As I study authentication for the mysql database. Usually the mysql_connect..... always using include.
                So, as all of them are linking to index.php. I don't have to define it again. May I know how to define it in the script include?

                $filename does exist, it must have an empty/NULL value.

                Yes, I notice it from the watch variable. That it didn't receive any value.
                I believe it come from this part

                $path=$_REQUEST['path']; 
                $filename=$_REQUEST['filename']; 

                how can I obtain it the value for $filename?

                • I'll ask the question that is so obvious that it should not have to be asked:

                  I am really sorry. I forgot to attach the warning message.
                  Below is the warning message that appear every time I press the save button on the toolbar of the javascript editor that I use.

                  <br />
                  <b>Warning</b>: file(/user_andrew/cfile/) [<a href='function.file'>function.file</a>]: failed to open stream: No such file or directory in <b>C:\Program Files\EasyPHP-5.3.9\www\index.php</b> on line <b>271</b><br />
                  <br />
                  <b>Warning</b>: Invalid argument supplied for foreach() in <b>C:\Program Files\EasyPHP-5.3.9\www\index.php</b> on line <b>272</b><br />

                  Line 271 and 272 is

                  $lines = file($path."/".$_SESSION['folder']."/cfile/".$filename);
                              foreach($lines as $line)

                  Perhaps you wanted to echo $filename here?

                  Yes. In the working solution for the save button for this editor, I use echo $filename. However, that working solution doesn't show the editor in the same page as the directory. It will open another page.

                  And perhaps you wanted at some stage to prevent people from supplying any path and filename that they liked (in other words: the path and filename to any file on your server?)

                  I currently not concerned by that matter at the moment.

                  • Hi, I am trying to use a javascript editor called edit area into my web.
                    Maybe this post is out of place but I don't think the problem is in my javascript but instead on my php coding regarding path.

                    I am trying to use it's save feature. So what I type will be saved. If I open the link again. I will obtain the code that I just write .
                    What I want to create is a list of directory on the left of the page and the editor on the right in one web page. If I press the link, the file content will be loaded to the inside of the editor.

                    I have successfully implement the editor but it is on separate window. Not one page. I press the link. New window open. I press save. The new window with the editor closed. I don't want this one.

                    Below is my current code
                    index.php
                    This is my javascript code inside index.php

                    <script language="javascript" type="text/javascript" src="/editarea/edit_area/edit_area_full.js"></script>
                    <script language="javascript" type="text/javascript">
                    editAreaLoader.init({
                    	id : "content"		  	// textarea id
                    	,syntax: "c"				// syntax to be uses for highgliting
                    	,start_highlight: true		// to display with highlight mode on start-up
                    	,language:"en"
                    	,toolbar: "save,| ,undo, redo, |, search, go_to_line"
                    	,is_multiple_files:true
                    	,allow_toggle:false
                            ,allow_resize:false
                    	,word_wrap:true
                            ,replace_tab_by_spaces:4
                            ,save_callback:"save_feature"
                    });
                    
                    function save_feature(id, content)
                    {
                        form1.content1.value=content;
                        document.forms["form1"].submit();
                    
                    }
                    </script>
                    if ($handle = opendir('.\\'.$folder.'\cfile\\')) 
                    {
                        while (false !== ($file = readdir($handle))) 
                        {
                            if ($file != ".." && $file != ".") 
                            {	
                    	echo "<a href=index.php?path=.&filename=$file>$file</a><br />";
                            }
                        }
                        closedir($handle);
                    }
                    
                    //EDITAREA
                    $path=$_REQUEST['path'];
                    $filename=$_REQUEST['filename'];
                    echo'
                    <textarea name=content id=content style="height:700px; width:900px">'; 
                    $script="edit";
                    if($filename!="scriptinclude.php")
                        {
                        include "scriptinclude.php";
                        }
                    else
                        {
                        echo "Scriptinclude may not be edited";
                        }
                    echo'
                    </textarea>
                    <form name=form1 method=post action=scriptupdate.php>
                    <table>
                    <tr><td><textarea name=content1 id=content1 style="display:none;">
                    </textarea></td></tr>
                    </table>';
                    //<textarea name=content1 id=content1 style="height: 0px; width: 0px;">
                    echo'
                    <input type=hidden name=path value='; 
                    echo $path;
                    echo"'>";
                    
                    echo"<input type=hidden name=filename value='";
                    $filename;
                    echo "'>
                    </form>";
                    

                    scriptinclude.php

                    <?php
                    if($script=="edit")
                    {
                        //$lines = file("../$path/upload/$filename");
                        //$lines = file("$path/upload/$filename");
                        $lines = file($path."/".$_SESSION['folder']."/cfile/".$filename);
                    	foreach($lines as $line)
                    	{
                    	echo str_replace("</textarea>","<#textarea>",$line);
                    	}
                    }
                    else
                        {
                        $content= stripslashes(str_replace("<#textarea>","</textarea>",$_REQUEST['content1']));
                        }
                    ?>

                    scriptupdate.php

                    <?php
                    session_start();
                    //chdir($_REQUEST['path']."/upload");
                    chdir($_REQUEST['path']."/".$_SESSION['folder']."/cfile");
                    $fp = fopen($_REQUEST['filename'], 'w');
                    include "scriptinclude.php";
                    fwrite($fp, $content);
                    fclose($fp);
                    header('Location: ../index.php');
                    ?>

                    Right now, I can load the file into the editor everytime I press the link.
                    However, everytime I press the save button

                    $path=$_REQUEST['path'];
                    $filename=$_REQUEST['filename'];

                    These two lines inside index.php always say that it is undefined.
                    Also,

                    $lines = file($path."/".$_SESSION['folder']."/cfile/".$filename);
                    	foreach($lines as $line)

                    These two line always have a warning message.
                    What am I missing? Please help.
                    Thanks in advance🙂

                    • Are you referring to the scriptedit.php or the string manipulation?
                      If I can put either part in one script. It will be very useful for me.
                      Could you show me how can I do that?

                      • Hi,

                        I am trying to do a string manipulation from the name of the files that I have in a certain directory.
                        Until now, I have successfully listed down all the files in that directory.
                        However, I still need these file names for string manipulation that I just mention.

                        Below is my code:

                        if ($handle = opendir('user\cfile\\')) 
                        {
                            //loop over directory
                            while (false !== ($file = readdir($handle))) 
                            {
                                //eliminate unnecessary file
                                if ($file != ".." && $file != ".") 
                                {
                        
                                //echo "<a href=scriptedit.php?path=.&filename=$file>$file</a><br>";
                                echo $file."<br>";
                            }
                        }
                        closedir($handle);
                        } 

                        Rightnow, I can produce this in the web

                        test1.html
                        test2.html
                        test3.html

                        I need to get all of these file names which right now contain in $file and do some string manipulation. One method that comes to my mind is storing $file in a variable. Then use session to pass that variable to another file.
                        How can I do this? or are there any better way to do get the file names?
                        Thanks in advance

                        • As you're compiling on an Ubuntu system, it won't create an exe file (not in the true sense) because it is compiling it for the Linux architecture, so it won't run on a Windows machine.

                          Yes, I agree with this. I try to download the file and run it in windows. It can't be run on windows. If I try to run it, it produce some error which I can conclude as a corrupt file.

                          it's probably best to stick with '/usr/bin/gcc'

                          Actually, at first, I intended to stick with the gcc. However, in the detail of gcc inside ubuntu. The type is not executable but a link which I don't think will work. Hence right now, I am sticking with gcc-4.5 which can produce the output file which I want.

                          Sorry, for asking in this thread, all over again. Is it possible to get the error message which is usually produced when your c file has some error?
                          Meaning those error that say which line is wrong, etc.
                          I would like to have those error maybe stored inside a variable or inside a text file and produced it to the web page?
                          Are there any suggestion on how to put that to the variable or text file using system()?
                          😕
                          Thanks in advance.

                          • @
                            Thanks for your suggestion. I managed to get it running now.
                            Below is the working code

                            $source = '/var/www/upload/' . $_FILES['compiledfile']['name'];
                            $destination = '/var/www/upload/' . pathinfo($_FILES['compiledfile']['name'], PATHINFO_FILENAME) . '.exe';
                            $output = system('"/usr/bin/gcc-4.5" ' . $source . ' -O3 -o ' . $destination);
                            

                            Is /usr/bin/gcc-4.5.executable reallythe executable?

                            No, that's why I open this thread as before I don't understand how to run the gcc in ubuntu.🙂

                            I installed codeblocks in ubuntu server and I use the compiler installed to compile the c file.

                            Also, when you said you set the permissions, what did you actually set?

                            I use the command

                            gksudo nautilus

                            I set the group and user to be able to create and delete files as I am not sure where the problem lies when I try to compile the file.
                            Is this bad practice? Is it better to use your read/write? If so, how can I do that?

                            you would be better off compiling the stuff in a different location, like a home directory.

                            What do you mean by this? The c file and the exe file to be put inside home directory? or the compiler inside home directory? As currently the compiler is inside bin under user while the c file is inside the web root. (var/www folder)

                            I also need to ask how can I produce an output like you usually see if there is a compilation error? (Those comments that appear below your comment if the command in the command line or terminal is wrong or if there is something wrong with your c file code, the error message will show right)
                            I try using the return value after the system(), however it only produce 1 or 0 which is not helping me if I want to show the error inside the c file code.
                            Thanks in advance.

                            • Hi,

                              I was doing a compilation of c file in wamp server
                              I use

                               if ((move_uploaded_file($_FILES['compiledfile']['tmp_name'], $newname))) {
                                              $source = 'upload\\' . $_FILES['compiledfile']['name'];
                                              //echo $source;
                                              $destination = 'upload\\' . pathinfo($_FILES['compiledfile']['name'], PATHINFO_FILENAME) . '.exe';
                                              //echo $destination;
                                              $output = system('"C:\Program Files\CodeBlocks\MinGW\bin\gcc.exe" ' . $source . ' -O3 -o ' . $destination);
                                              echo $output;

                              which has been working correctly.

                              I decided to migrate to an ubuntu server
                              I have installed all the component from apache, php, mysql, and phpmyadmin.
                              I also install a codeblock for gcc compiler.
                              Then I try to correct the path as ubuntu use / not \ like windows.
                              However, I can't find what is wrong.
                              Below is my code

                              if ((move_uploaded_file($_FILES['compiledfile']['tmp_name'], $newname))) {
                                              $source = 'upload\\' . $_FILES['compiledfile']['name'];
                                              //echo $source;
                                              $destination = 'upload\\' . pathinfo($_FILES['compiledfile']['name'], PATHINFO_FILENAME) . '.exe';
                                              //echo $destination;
                                              $output = system('"/usr/bin/gcc-4.5.executable" ' . $source . ' -O3 -o ' . $destination);
                                              echo $output;
                              

                              I already set the permission from root so I can create and delete the file inside the bin folder (where gcc is installed) and do the same thing for the upload folder inside my webroot.
                              What am I missing?

                              I try using $returnvalue after the command string

                               $output = system('"/usr/bin/gcc-4.5.executable" ' . $source . ' -O3 -o ' . $destination,$returnvalue);
                                              echo $output;
                              echo $returnvalue;

                              However, the output if I upload a syntax error file is 1 which is not helping me to know what is the problem. How can I output the text error that usually appear under your command in the ubuntu terminal or windows command line in order to know what is wrong with my $output?

                              Thanks in advance🙂

                              • Figure out the problem already. It was some permission issue for the folder inside ubuntu server.

                                However, still a question why does this statement

                                (preg_match("/^[A-Za-z0-9].*\.[a-z]{0,3}$/", $_FILES['uploadedfile']['tmp_name'])) 

                                can't be executed?

                                • Hi,

                                  I just recently migrate from a WAMP server to a ubuntu server.
                                  I was doing a simple file uploading with simple parameter.

                                  This is my code working on a WAMP Server

                                  echo"<form action='' method=POST enctype=multipart/form-data>";
                                  
                                  //method post to make it invisible
                                  echo"<input type=hidden name=MAX_FILE_SIZE value=100000>";
                                  
                                  //echo"<input type=file name=uploadedfile onchange=this.form.submit()>";
                                  echo"<input type=button value='File to Upload' class=choose1 id=pseudobutton>";
                                  echo"<input type=file name=uploadedfile class=hide1 id=openssme>";
                                  echo"<input type=hidden name=uploadedfile>";
                                  echo"<input type=submit name=upload value=Upload class=upload>";
                                  echo"</form>";
                                  
                                  //START OF UPLOAD
                                  //check if upload is selected
                                  if (isset($_POST['upload'])) {
                                      $ext = "";
                                      //Check the availability of the file. empty evaluate to true if empty. check if it is the recent uploaded file. validate filename
                                  echo "First Condition";
                                      if ((!empty($_FILES["uploadedfile"])) && ($_FILES['uploadedfile']['error'] == 0) && (is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) && (preg_match("/^[A-Za-z0-9].*\.[a-z]{0,3}$/", $_FILES['uploadedfile']['tmp_name']))) {
                                          //basename return component name. strtolower change to lowercase.
                                          $filename = strtolower(basename($_FILES['uploadedfile']['name']));
                                          //substr return some string after dot
                                          $ext = substr($filename, strrpos($filename, '.') + 1);
                                  echo"Second Condition";
                                  
                                      //check if file extension is c and less than 100000kb
                                      if (($ext == "c") && ($_FILES["uploadedfile"]["size"] < 100000) && ($_FILES["uploadedfile"]["type"] == "text/plain")) {
                                          //add the dot
                                          $ext = "." . $ext;
                                          //file directory
                                          $newname = dirname(__FILE__) . '/upload/' . $_FILES["uploadedfile"]["name"];
                                  echo $newname;
                                              //move_uploaded_file is php function for directory
                                              if ((move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $newname))) {
                                                  print('<br><br><br><br><br><table>');
                                                  print('<tr><td width=100px>File Name</td><td width=100px>File Size</td><td width=100px>Last Modified</td></tr>');
                                                  print('<tr><td><a href="$newname">'.$_FILES['uploadedfile']['name'].'</a></td><td>' . round($_FILES['uploadedfile']['size'] / 1024, 4) . ' Kb</td><td>' . date("d F Y H:i:s.", filemtime($newname)) . '</td></tr>');
                                                  print('</table>');
                                              } else {
                                                  print('error');
                                              }
                                          } else {
                                              print('Error: Only .c files <500Kb');
                                          }
                                      } else {
                                          $filename = NULL;
                                      }
                                  }

                                  In the ubuntu server, the code above is not working. I need to modify

                                  if ((!empty($_FILES["uploadedfile"])) && ($_FILES['uploadedfile']['error'] == 0) && (is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) && (preg_match("/^[A-Za-z0-9].*\.[a-z]{0,3}$/", $_FILES['uploadedfile']['tmp_name'])))

                                  into

                                  ((!empty($_FILES["uploadedfile"])) && ($_FILES['uploadedfile']['error'] == 0) && (is_uploaded_file($_FILES['uploadedfile']['tmp_name'])))

                                  The if statement parameter

                                  (preg_match("/^[A-Za-z0-9].*\.[a-z]{0,3}$/", $_FILES['uploadedfile']['tmp_name']))

                                  is not executed.
                                  Why is it giving a false statement?

                                  Now I am stuck at

                                  if ((move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $newname)))

                                  At first I though it was some problem with the directory.
                                  However the $newname provide me with
                                  /var/www/upload/test1.c which I believe is correct.
                                  why does the move_uploaded_file not working?

                                  The output message that I am currently receiving
                                  first conditionsecond condition/var/www/upload/test1.cerror
                                  How can I fix this problem? Is it permission issue perhaps?
                                  Thanks in advance

                                  • Thanks a lot Weedpacket.
                                    That has solved my problem.
                                    I misunderstand your sentence and just add another if statement to check if $check2 is an object with the

                                    $check2->username == $_POST['username'] 

                                    still exist.

                                    @, it is an awesome tutorial. Great job. Definitely will try to implement your tutorial.

                                    • $check2 is not an object if there were no records in the table with username='$_POST[username]'.

                                      Yes, I understand this point.
                                      My problem is how do I remove the message
                                      Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register1.php on line 70
                                      when I register a new user?

                                      What I want the system to work is just output
                                      "Registration successful.
                                      Click here to login to your account"
                                      whenever the registration is a success.

                                      Right now the output is
                                      Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register1.php on line 70
                                      Registration successful.
                                      Click here to login to your account

                                      Do you understand my problem?🙂

                                      • Hi,

                                        I try this code

                                         //check for unique name            
                                        $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'"); if (!$check1) { echo mysql_error();
                                        } else { $check2 = mysql_fetch_object($check1); var_dump($check2); if(!is_object($check2)) { echo"check2 is not an object"; } }

                                        The message "check 2 is not an object" appear. So it is verified that $check2 is not an object. How can I fix this?

                                        It's also important to note two things: first, your code is vulnerable to SQL Injection; and second, the MySQL extension is deprecated.

                                        I am new to php. Do I need to also prevent this on the registration form as I already use the code below in my login.php

                                        // To protect MySQL injection
                                        $membername = stripslashes($membername);
                                        $memberpass = stripslashes($memberpass);
                                        $memberemail= stripslashes($memberemail);
                                        $membername = mysql_real_escape_string($membername);
                                        $memberpass = mysql_real_escape_string($memberpass);
                                        $memberemail= mysql_real_escape_string($memberemail);

                                        This is my full code to process the registration

                                        <?php
                                        $server="localhost"; // Host name
                                        $username=""; // Mysql username
                                        $password=""; // Mysql password
                                        $db_name="test_db"; // Database name
                                        $tbl_name="test"; // Table name
                                        
                                        //Connect to server
                                        mysql_connect("$server", "$username", "$password")or die("cannot connect to server");
                                        //Connect to database
                                        mysql_select_db("$db_name")or die("cannot select database");
                                        
                                        if(isset($_POST['register']))
                                        {
                                            //USERNAME CHECKING
                                            if(!$_POST['username'])
                                            {
                                                die('Username is empty');
                                            }
                                            else
                                            {
                                                //check for invalid character
                                                $invalid=array('.',',','/','\\',"'",';','[',']','-','_','*','&','^', '%','$','#','@','!','~','+','(',')','|','{','}','<','>','?',':','"','=');
                                        
                                            //length of username
                                            $length = strlen($_POST['username']);
                                        
                                            //replace invalid characters
                                            $_POST['username'] = str_replace($invalid, '', $_POST['username']);
                                            $test = $_POST['username'];
                                        
                                            //if lenghts are different ($len smaller), invalid characters found, so prompt error.
                                            if(strlen($test) != $length)
                                            {
                                                die('Username Error: Username contained invalid characters. You can only use A-Z, 0-9 and the underscore (_).');
                                            }
                                            else
                                            {
                                                //check for unique name            
                                                $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
                                                if (!$check1) 
                                                { 
                                                    echo mysql_error();  
                                                }
                                                else 
                                                {
                                                    $check2 = mysql_fetch_object($check1);
                                                    var_dump($check2);
                                                    if(!is_object($check2))
                                                    {
                                                        echo"check2 is not an object";
                                                    }
                                                }  
                                        
                                                $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
                                                if (!$check1) 
                                                { 
                                                    echo mysql_error();  
                                                }
                                                else 
                                                {
                                                    $check2 = mysql_fetch_object($check1);
                                                    if($check2->username == $_POST['username'])
                                                    {
                                                         die('Sorry but username "'.$check2->username.'" is taken');
                                                    }
                                                    else
                                                    {
                                                        //PASSWORD CHECKING
                                                        if(!$_POST['password']) 
                                                        {
                                                            die('Error: Password field was blank');
                                                        }
                                                        else
                                                        {
                                                            if(!$_POST['verifypassword']) 
                                                            {
                                                                die('Error: Verify Password field was blank.');
                                                            }
                                                            else
                                                            {
                                                                if($_POST['password'] != $_POST['verifypassword']) 
                                                                { 
                                                                    die('Error: The passwords do not match.');
                                                                }
                                                                else
                                                                {
                                                                    if(strlen($_POST['password']) < 6 ) 
                                                                    {
                                                                        die('Error: Your password is too short. Must be 6 or more characters in length.');
                                                                    } 
                                                                    else
                                                                    {
                                                                        //EMAIL CHECKING
                                                                        if(!$_POST['email'])
                                                                        {
                                                                            die('Error: Email field was blank');
                                                                        }
                                                                        else
                                                                        {
                                                                            //check for invalid character
                                                                            $emailinvalid=array(',','/','\\',"'",';','[',']','-','_','*','&','^', '%','$','#','!','~','+','(',')','|','{','}','<','>','?',':','"','=');
                                        
                                                                            //length of username
                                                                            $emaillength = strlen($_POST['email']);
                                        
                                                                            //replace invalid characters
                                                                            $_POST['email'] = str_replace($emailinvalid, '', $_POST['email']);
                                                                            $emailcheck = $_POST['email'];
                                        
                                                                            //if lenghts are different ($len smaller), invalid characters found, so prompt error.
                                                                            if(strlen($emailcheck) != $emaillength)
                                                                            {
                                                                                die('Email Error: Email contained invalid characters.');
                                                                            }
                                                                            else
                                                                            {                                          
                                                                                $insertuser="INSERT INTO $tbl_name (username, password,email) VALUE('".$_POST['username']."','".md5($_POST['password'])."','".$_POST['email']."')";
                                                                                $insertuser2=mysql_query($insertuser);
                                                                                if(!$insertuser2)
                                                                                {
                                                                                    die(mysql_error());
                                                                                }
                                                                                else
                                                                                {
                                                                                    echo "Registration Succesful";
                                                                                    echo "<br><a href=login.html>Click Here</a> to login to your account";
                                                                                }    
                                                                            }    
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }    
                                                }
                                            }
                                        }
                                        }
                                        else
                                        {
                                        
                                        }
                                        ?>
                                        

                                        Does my code still vulnerable to SQL injection even if I already put some parameter?

                                        • Hi,

                                          I am trying to build a registration system, where user needs to input username, password and email.
                                          I use a checking procedure to make sure that username for each user is unique.

                                          Right now I already try a few way to solve this.
                                          At first, the notice appear when the username is already exist.
                                          Now, the notice appear when i create a new username and the registration is successful.

                                          Below is my code

                                          //check for unique name
                                          
                                          $qry = "SELECT * FROM $tbl_name WHERE username = '" . $_POST['username'] . "' ";
                                          echo $qry;
                                          
                                          $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'");
                                          if (!$check1) 
                                          { 
                                          echo mysql_error();  
                                          } else { $check2 = mysql_fetch_object($check1); var_dump($check2); } $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'"); $rows = mysql_num_rows($check1); if ($rows == 1) { // a similar name exists, issue error message. echo "error"; } $check1 = mysql_query("SELECT * FROM $tbl_name WHERE username= '".$_POST['username']."'"); if (!$check1) { echo mysql_error();
                                          } else { }

                                          The error message if I enter a new user is
                                          SELECT * FROM test WHERE username = 'chicken'
                                          boolean false

                                          Notice: Trying to get property of non-object in C:\Program Files\EasyPHP-5.3.9\www\register1.php on line 70
                                          Registration Succesful
                                          Click Here to login to your account

                                          Line 70 is
                                          if($check2->username == $_POST['username'])

                                          The error message if I enter an existing user id
                                          SELECT * FROM test WHERE username = 'burger'
                                          object(stdClass)[1]
                                          public 'id' => string '46' (length=2)
                                          public 'username' => string 'burger' (length=6)
                                          public 'password' => string '6e69685d22c94ffd42ccd7e70e246bd9' (length=32)
                                          public 'email' => string 'burger' (length=6)
                                          errorSorry but username "burger" is taken

                                          How to solve this notice? or are there any better way to do the username checking to avoid this notice?
                                          Thanks in advance🙂